settings.js 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112
  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. const preferredPortSelect = document.getElementById('preferredPortSelect');
  104. if (portsElement) {
  105. portsElement.textContent = ports.length > 0 ? ports.join(', ') : 'No ports available';
  106. }
  107. if (portSelect) {
  108. // Clear existing options except the first one
  109. while (portSelect.options.length > 1) {
  110. portSelect.remove(1);
  111. }
  112. // Add new options
  113. ports.forEach(port => {
  114. const option = document.createElement('option');
  115. option.value = port;
  116. option.textContent = port;
  117. portSelect.appendChild(option);
  118. });
  119. // If there's exactly one port available, select and connect to it
  120. if (ports.length === 1) {
  121. portSelect.value = ports[0];
  122. // Trigger connect button click
  123. const connectButton = document.getElementById('connectButton');
  124. if (connectButton) {
  125. connectButton.click();
  126. }
  127. }
  128. }
  129. // Also update the preferred port select dropdown
  130. if (preferredPortSelect) {
  131. // Store current selection
  132. const currentPreferred = preferredPortSelect.value;
  133. // Clear existing options except the first one (no preference)
  134. while (preferredPortSelect.options.length > 1) {
  135. preferredPortSelect.remove(1);
  136. }
  137. // Add all available ports
  138. ports.forEach(port => {
  139. const option = document.createElement('option');
  140. option.value = port;
  141. option.textContent = port;
  142. preferredPortSelect.appendChild(option);
  143. });
  144. // Restore selection if it's still available
  145. if (currentPreferred && ports.includes(currentPreferred)) {
  146. preferredPortSelect.value = currentPreferred;
  147. }
  148. }
  149. }
  150. } catch (error) {
  151. logMessage(`Error fetching serial ports: ${error.message}`, LOG_TYPE.ERROR);
  152. }
  153. }
  154. // Function to load and display preferred port setting
  155. async function loadPreferredPort() {
  156. try {
  157. const response = await fetch('/api/preferred-port');
  158. if (response.ok) {
  159. const data = await response.json();
  160. const preferredPortSelect = document.getElementById('preferredPortSelect');
  161. const currentPreferredPort = document.getElementById('currentPreferredPort');
  162. const preferredPortDisplay = document.getElementById('preferredPortDisplay');
  163. if (preferredPortSelect && data.preferred_port) {
  164. // Check if the preferred port is in the options
  165. const optionExists = Array.from(preferredPortSelect.options).some(
  166. opt => opt.value === data.preferred_port
  167. );
  168. if (optionExists) {
  169. preferredPortSelect.value = data.preferred_port;
  170. } else {
  171. // Add the preferred port as an option (it might not be currently available)
  172. const option = document.createElement('option');
  173. option.value = data.preferred_port;
  174. option.textContent = `${data.preferred_port} (not currently available)`;
  175. preferredPortSelect.appendChild(option);
  176. preferredPortSelect.value = data.preferred_port;
  177. }
  178. }
  179. // Show current preferred port indicator
  180. if (currentPreferredPort && preferredPortDisplay && data.preferred_port) {
  181. preferredPortDisplay.textContent = `Currently set to: ${data.preferred_port}`;
  182. currentPreferredPort.classList.remove('hidden');
  183. } else if (currentPreferredPort) {
  184. currentPreferredPort.classList.add('hidden');
  185. }
  186. }
  187. } catch (error) {
  188. logMessage(`Error loading preferred port: ${error.message}`, LOG_TYPE.ERROR);
  189. }
  190. }
  191. // Function to save preferred port setting
  192. async function savePreferredPort() {
  193. const preferredPortSelect = document.getElementById('preferredPortSelect');
  194. if (!preferredPortSelect) return;
  195. const preferredPort = preferredPortSelect.value || null;
  196. try {
  197. const response = await fetch('/api/preferred-port', {
  198. method: 'POST',
  199. headers: { 'Content-Type': 'application/json' },
  200. body: JSON.stringify({ preferred_port: preferredPort })
  201. });
  202. if (response.ok) {
  203. const data = await response.json();
  204. const currentPreferredPort = document.getElementById('currentPreferredPort');
  205. const preferredPortDisplay = document.getElementById('preferredPortDisplay');
  206. if (data.preferred_port) {
  207. showStatusMessage(`Preferred port set to: ${data.preferred_port}`, 'success');
  208. if (currentPreferredPort && preferredPortDisplay) {
  209. preferredPortDisplay.textContent = `Currently set to: ${data.preferred_port}`;
  210. currentPreferredPort.classList.remove('hidden');
  211. }
  212. } else {
  213. showStatusMessage('Preferred port cleared - will auto-detect on startup', 'success');
  214. if (currentPreferredPort) {
  215. currentPreferredPort.classList.add('hidden');
  216. }
  217. }
  218. } else {
  219. throw new Error('Failed to save preferred port');
  220. }
  221. } catch (error) {
  222. showStatusMessage(`Failed to save preferred port: ${error.message}`, 'error');
  223. }
  224. }
  225. function setWledButtonState(isSet) {
  226. const saveWledConfig = document.getElementById('saveWledConfig');
  227. if (!saveWledConfig) return;
  228. if (isSet) {
  229. 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';
  230. saveWledConfig.innerHTML = '<span class="material-icons text-lg">close</span><span class="truncate">Clear WLED IP</span>';
  231. } else {
  232. 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';
  233. saveWledConfig.innerHTML = '<span class="material-icons text-lg">save</span><span class="truncate">Save Configuration</span>';
  234. }
  235. }
  236. // Handle LED provider selection and show/hide appropriate config sections
  237. function updateLedProviderUI() {
  238. const provider = document.querySelector('input[name="ledProvider"]:checked')?.value || 'none';
  239. const wledConfig = document.getElementById('wledConfig');
  240. const dwLedsConfig = document.getElementById('dwLedsConfig');
  241. if (wledConfig && dwLedsConfig) {
  242. if (provider === 'wled') {
  243. wledConfig.classList.remove('hidden');
  244. dwLedsConfig.classList.add('hidden');
  245. } else if (provider === 'dw_leds') {
  246. wledConfig.classList.add('hidden');
  247. dwLedsConfig.classList.remove('hidden');
  248. } else {
  249. wledConfig.classList.add('hidden');
  250. dwLedsConfig.classList.add('hidden');
  251. }
  252. }
  253. }
  254. // Load LED configuration from server
  255. async function loadLedConfig() {
  256. try {
  257. const response = await fetch('/get_led_config');
  258. if (response.ok) {
  259. const data = await response.json();
  260. // Set provider radio button
  261. const providerRadio = document.getElementById(`ledProvider${providerToCamelCase(data.provider)}`);
  262. if (providerRadio) {
  263. providerRadio.checked = true;
  264. } else {
  265. document.getElementById('ledProviderNone').checked = true;
  266. }
  267. // Set WLED IP if configured
  268. if (data.wled_ip) {
  269. const wledIpInput = document.getElementById('wledIpInput');
  270. if (wledIpInput) {
  271. wledIpInput.value = data.wled_ip;
  272. }
  273. }
  274. // Set DW LED configuration if configured
  275. if (data.dw_led_num_leds) {
  276. const numLedsInput = document.getElementById('dwLedNumLeds');
  277. if (numLedsInput) {
  278. numLedsInput.value = data.dw_led_num_leds;
  279. }
  280. }
  281. if (data.dw_led_gpio_pin) {
  282. const gpioPinInput = document.getElementById('dwLedGpioPin');
  283. if (gpioPinInput) {
  284. gpioPinInput.value = data.dw_led_gpio_pin;
  285. }
  286. }
  287. if (data.dw_led_pixel_order) {
  288. const pixelOrderInput = document.getElementById('dwLedPixelOrder');
  289. if (pixelOrderInput) {
  290. pixelOrderInput.value = data.dw_led_pixel_order;
  291. }
  292. }
  293. // Update UI to show correct config section
  294. updateLedProviderUI();
  295. }
  296. } catch (error) {
  297. logMessage(`Error loading LED config: ${error.message}`, LOG_TYPE.ERROR);
  298. }
  299. }
  300. // Initialize settings page
  301. document.addEventListener('DOMContentLoaded', async () => {
  302. // Initialize UI with default disconnected state
  303. updateConnectionUI({ connected: false });
  304. // Handle scroll to section if hash is present in URL
  305. if (window.location.hash) {
  306. setTimeout(() => {
  307. const targetSection = document.querySelector(window.location.hash);
  308. if (targetSection) {
  309. targetSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
  310. // Add a subtle highlight animation
  311. targetSection.style.transition = 'background-color 0.5s ease';
  312. const originalBg = targetSection.style.backgroundColor;
  313. targetSection.style.backgroundColor = 'rgba(14, 165, 233, 0.1)';
  314. setTimeout(() => {
  315. targetSection.style.backgroundColor = originalBg;
  316. }, 2000);
  317. }
  318. }, 300); // Delay to ensure page is fully loaded
  319. }
  320. // Load all data asynchronously
  321. Promise.all([
  322. // Check connection status
  323. fetch('/serial_status').then(response => response.json()).catch(() => ({ connected: false })),
  324. // Load LED configuration (replaces old WLED-only loading)
  325. fetch('/get_led_config').then(response => response.json()).catch(() => ({ provider: 'none', wled_ip: null })),
  326. // Load current version and check for updates
  327. fetch('/api/version').then(response => response.json()).catch(() => ({ current: '1.0.0', latest: '1.0.0', update_available: false })),
  328. // Load available serial ports
  329. fetch('/list_serial_ports').then(response => response.json()).catch(() => []),
  330. // Load available pattern files for clear pattern selection
  331. getCachedPatternFiles().catch(() => []),
  332. // Load current custom clear patterns
  333. fetch('/api/custom_clear_patterns').then(response => response.json()).catch(() => ({ custom_clear_from_in: null, custom_clear_from_out: null })),
  334. // Load current clear pattern speed
  335. fetch('/api/clear_pattern_speed').then(response => response.json()).catch(() => ({ clear_pattern_speed: 200 })),
  336. // Load current app name
  337. fetch('/api/app-name').then(response => response.json()).catch(() => ({ app_name: 'Dune Weaver' })),
  338. // Load Still Sands settings
  339. fetch('/api/scheduled-pause').then(response => response.json()).catch(() => ({ enabled: false, time_slots: [] })),
  340. // Load preferred port setting
  341. fetch('/api/preferred-port').then(response => response.json()).catch(() => ({ preferred_port: null }))
  342. ]).then(([statusData, ledConfigData, updateData, ports, patterns, clearPatterns, clearSpeedData, appNameData, scheduledPauseData, preferredPortData]) => {
  343. // Update connection status
  344. setCachedConnectionStatus(statusData);
  345. updateConnectionUI(statusData);
  346. // Update LED configuration
  347. const providerRadio = document.getElementById(`ledProvider${providerToCamelCase(ledConfigData.provider)}`);
  348. if (providerRadio) {
  349. providerRadio.checked = true;
  350. } else {
  351. document.getElementById('ledProviderNone').checked = true;
  352. }
  353. if (ledConfigData.wled_ip) {
  354. const wledIpInput = document.getElementById('wledIpInput');
  355. if (wledIpInput) wledIpInput.value = ledConfigData.wled_ip;
  356. }
  357. // Load DW LED settings
  358. if (ledConfigData.dw_led_num_leds) {
  359. const numLedsInput = document.getElementById('dwLedNumLeds');
  360. if (numLedsInput) numLedsInput.value = ledConfigData.dw_led_num_leds;
  361. }
  362. if (ledConfigData.dw_led_gpio_pin) {
  363. const gpioPinInput = document.getElementById('dwLedGpioPin');
  364. if (gpioPinInput) gpioPinInput.value = ledConfigData.dw_led_gpio_pin;
  365. }
  366. if (ledConfigData.dw_led_pixel_order) {
  367. const pixelOrderInput = document.getElementById('dwLedPixelOrder');
  368. if (pixelOrderInput) pixelOrderInput.value = ledConfigData.dw_led_pixel_order;
  369. }
  370. updateLedProviderUI()
  371. // Update version display
  372. const currentVersionText = document.getElementById('currentVersionText');
  373. const latestVersionText = document.getElementById('latestVersionText');
  374. const updateButton = document.getElementById('updateSoftware');
  375. const updateIcon = document.getElementById('updateIcon');
  376. const updateText = document.getElementById('updateText');
  377. if (currentVersionText) {
  378. currentVersionText.textContent = updateData.current;
  379. }
  380. if (latestVersionText) {
  381. if (updateData.error) {
  382. latestVersionText.textContent = 'Error checking updates';
  383. latestVersionText.className = 'text-red-500 text-sm font-normal leading-normal';
  384. } else {
  385. latestVersionText.textContent = updateData.latest;
  386. latestVersionText.className = 'text-slate-500 text-sm font-normal leading-normal';
  387. }
  388. }
  389. // Update button state
  390. if (updateButton && updateIcon && updateText) {
  391. if (updateData.update_available) {
  392. updateButton.disabled = false;
  393. 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';
  394. updateIcon.textContent = 'download';
  395. updateText.textContent = 'Update';
  396. } else {
  397. updateButton.disabled = true;
  398. 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';
  399. updateIcon.textContent = 'check';
  400. updateText.textContent = 'Up to date';
  401. }
  402. }
  403. // Update port selection
  404. const portSelect = document.getElementById('portSelect');
  405. if (portSelect) {
  406. // Clear existing options except the first one
  407. while (portSelect.options.length > 1) {
  408. portSelect.remove(1);
  409. }
  410. // Add new options
  411. ports.forEach(port => {
  412. const option = document.createElement('option');
  413. option.value = port;
  414. option.textContent = port;
  415. portSelect.appendChild(option);
  416. });
  417. // If there's exactly one port available, select it
  418. if (ports.length === 1) {
  419. portSelect.value = ports[0];
  420. }
  421. }
  422. // Update preferred port selection
  423. const preferredPortSelect = document.getElementById('preferredPortSelect');
  424. const currentPreferredPort = document.getElementById('currentPreferredPort');
  425. const preferredPortDisplay = document.getElementById('preferredPortDisplay');
  426. if (preferredPortSelect) {
  427. // Clear existing options except the first one (no preference)
  428. while (preferredPortSelect.options.length > 1) {
  429. preferredPortSelect.remove(1);
  430. }
  431. // Add all available ports
  432. ports.forEach(port => {
  433. const option = document.createElement('option');
  434. option.value = port;
  435. option.textContent = port;
  436. preferredPortSelect.appendChild(option);
  437. });
  438. // Set the current preferred port value
  439. if (preferredPortData && preferredPortData.preferred_port) {
  440. // Check if the preferred port is in the available ports
  441. const isAvailable = ports.includes(preferredPortData.preferred_port);
  442. if (isAvailable) {
  443. preferredPortSelect.value = preferredPortData.preferred_port;
  444. } else {
  445. // Add the preferred port as an option (it might not be currently available)
  446. const option = document.createElement('option');
  447. option.value = preferredPortData.preferred_port;
  448. option.textContent = `${preferredPortData.preferred_port} (not currently available)`;
  449. preferredPortSelect.appendChild(option);
  450. preferredPortSelect.value = preferredPortData.preferred_port;
  451. }
  452. // Show the current preferred port indicator
  453. if (currentPreferredPort && preferredPortDisplay) {
  454. preferredPortDisplay.textContent = `Currently set to: ${preferredPortData.preferred_port}`;
  455. currentPreferredPort.classList.remove('hidden');
  456. }
  457. }
  458. }
  459. // Initialize autocomplete for clear patterns
  460. const clearFromInInput = document.getElementById('customClearFromInInput');
  461. const clearFromOutInput = document.getElementById('customClearFromOutInput');
  462. if (clearFromInInput && clearFromOutInput && patterns && Array.isArray(patterns)) {
  463. // Store patterns globally for autocomplete
  464. window.availablePatterns = patterns;
  465. // Set current values if they exist
  466. if (clearPatterns && clearPatterns.custom_clear_from_in) {
  467. clearFromInInput.value = clearPatterns.custom_clear_from_in;
  468. }
  469. if (clearPatterns && clearPatterns.custom_clear_from_out) {
  470. clearFromOutInput.value = clearPatterns.custom_clear_from_out;
  471. }
  472. // Initialize autocomplete for both inputs
  473. initializeAutocomplete('customClearFromInInput', 'clearFromInSuggestions', 'clearFromInClear', patterns);
  474. initializeAutocomplete('customClearFromOutInput', 'clearFromOutSuggestions', 'clearFromOutClear', patterns);
  475. console.log('Autocomplete initialized with', patterns.length, 'patterns');
  476. }
  477. // Set clear pattern speed
  478. const clearPatternSpeedInput = document.getElementById('clearPatternSpeedInput');
  479. const effectiveClearSpeed = document.getElementById('effectiveClearSpeed');
  480. if (clearPatternSpeedInput && clearSpeedData) {
  481. // Only set value if clear_pattern_speed is not null
  482. if (clearSpeedData.clear_pattern_speed !== null && clearSpeedData.clear_pattern_speed !== undefined) {
  483. clearPatternSpeedInput.value = clearSpeedData.clear_pattern_speed;
  484. if (effectiveClearSpeed) {
  485. effectiveClearSpeed.textContent = `Current: ${clearSpeedData.clear_pattern_speed} steps/min`;
  486. }
  487. } else {
  488. // Leave empty to show placeholder for default
  489. clearPatternSpeedInput.value = '';
  490. if (effectiveClearSpeed && clearSpeedData.effective_speed) {
  491. effectiveClearSpeed.textContent = `Using default pattern speed: ${clearSpeedData.effective_speed} steps/min`;
  492. }
  493. }
  494. }
  495. // Update app name
  496. const appNameInput = document.getElementById('appNameInput');
  497. if (appNameInput && appNameData.app_name) {
  498. appNameInput.value = appNameData.app_name;
  499. }
  500. // Store Still Sands data for later initialization
  501. window.initialStillSandsData = scheduledPauseData;
  502. }).catch(error => {
  503. logMessage(`Error initializing settings page: ${error.message}`, LOG_TYPE.ERROR);
  504. });
  505. // Set up event listeners
  506. setupEventListeners();
  507. });
  508. // Setup event listeners
  509. function setupEventListeners() {
  510. // Save App Name
  511. const saveAppNameButton = document.getElementById('saveAppName');
  512. const appNameInput = document.getElementById('appNameInput');
  513. if (saveAppNameButton && appNameInput) {
  514. saveAppNameButton.addEventListener('click', async () => {
  515. const appName = appNameInput.value.trim() || 'Dune Weaver';
  516. try {
  517. const response = await fetch('/api/app-name', {
  518. method: 'POST',
  519. headers: { 'Content-Type': 'application/json' },
  520. body: JSON.stringify({ app_name: appName })
  521. });
  522. if (response.ok) {
  523. const data = await response.json();
  524. showStatusMessage('Application name updated successfully. Refresh the page to see changes.', 'success');
  525. // Update the page title and header immediately
  526. document.title = `Settings - ${data.app_name}`;
  527. const headerTitle = document.querySelector('h1.text-gray-800');
  528. if (headerTitle) {
  529. // Update just the text content, preserving the connection status dot
  530. const textNode = headerTitle.childNodes[0];
  531. if (textNode && textNode.nodeType === Node.TEXT_NODE) {
  532. textNode.textContent = data.app_name;
  533. }
  534. }
  535. } else {
  536. throw new Error('Failed to save application name');
  537. }
  538. } catch (error) {
  539. showStatusMessage(`Failed to save application name: ${error.message}`, 'error');
  540. }
  541. });
  542. // Handle Enter key in app name input
  543. appNameInput.addEventListener('keypress', (e) => {
  544. if (e.key === 'Enter') {
  545. saveAppNameButton.click();
  546. }
  547. });
  548. }
  549. // LED provider selection change handlers
  550. const ledProviderRadios = document.querySelectorAll('input[name="ledProvider"]');
  551. ledProviderRadios.forEach(radio => {
  552. radio.addEventListener('change', updateLedProviderUI);
  553. });
  554. // Save LED configuration
  555. const saveLedConfig = document.getElementById('saveLedConfig');
  556. if (saveLedConfig) {
  557. saveLedConfig.addEventListener('click', async () => {
  558. const provider = document.querySelector('input[name="ledProvider"]:checked')?.value || 'none';
  559. let requestBody = { provider };
  560. if (provider === 'wled') {
  561. const wledIp = document.getElementById('wledIpInput')?.value;
  562. if (!wledIp) {
  563. showStatusMessage('Please enter a WLED IP address', 'error');
  564. return;
  565. }
  566. requestBody.ip_address = wledIp;
  567. } else if (provider === 'dw_leds') {
  568. const numLeds = parseInt(document.getElementById('dwLedNumLeds')?.value) || 60;
  569. const gpioPin = parseInt(document.getElementById('dwLedGpioPin')?.value) || 12;
  570. const pixelOrder = document.getElementById('dwLedPixelOrder')?.value || 'GRB';
  571. requestBody.num_leds = numLeds;
  572. requestBody.gpio_pin = gpioPin;
  573. requestBody.pixel_order = pixelOrder;
  574. }
  575. try {
  576. const response = await fetch('/set_led_config', {
  577. method: 'POST',
  578. headers: { 'Content-Type': 'application/json' },
  579. body: JSON.stringify(requestBody)
  580. });
  581. if (response.ok) {
  582. const data = await response.json();
  583. if (provider === 'wled' && data.wled_ip) {
  584. localStorage.setItem('wled_ip', data.wled_ip);
  585. showStatusMessage('WLED configured successfully', 'success');
  586. } else if (provider === 'dw_leds') {
  587. // Check if there's a warning (hardware not available but settings saved)
  588. if (data.warning) {
  589. showStatusMessage(
  590. `Settings saved for testing. Hardware issue: ${data.warning}`,
  591. 'warning'
  592. );
  593. } else {
  594. showStatusMessage(
  595. `DW LEDs configured: ${data.dw_led_num_leds} LEDs on GPIO${data.dw_led_gpio_pin}`,
  596. 'success'
  597. );
  598. }
  599. } else if (provider === 'none') {
  600. localStorage.removeItem('wled_ip');
  601. showStatusMessage('LED controller disabled', 'success');
  602. }
  603. } else {
  604. // Extract error detail from response
  605. const errorData = await response.json().catch(() => ({}));
  606. const errorMessage = errorData.detail || 'Failed to save LED configuration';
  607. showStatusMessage(errorMessage, 'error');
  608. }
  609. } catch (error) {
  610. showStatusMessage(`Failed to save LED configuration: ${error.message}`, 'error');
  611. }
  612. });
  613. }
  614. // Update software
  615. const updateSoftware = document.getElementById('updateSoftware');
  616. if (updateSoftware) {
  617. updateSoftware.addEventListener('click', async () => {
  618. if (updateSoftware.disabled) {
  619. return;
  620. }
  621. try {
  622. const response = await fetch('/api/update', {
  623. method: 'POST'
  624. });
  625. const data = await response.json();
  626. if (data.success) {
  627. showStatusMessage('Software update started successfully', 'success');
  628. } else if (data.manual_update_url) {
  629. // Show modal with manual update instructions, but use wiki link
  630. const wikiData = {
  631. ...data,
  632. manual_update_url: 'https://github.com/tuanchris/dune-weaver/wiki/Updating-software'
  633. };
  634. showUpdateInstructionsModal(wikiData);
  635. } else {
  636. showStatusMessage(data.message || 'No updates available', 'info');
  637. }
  638. } catch (error) {
  639. logMessage(`Error updating software: ${error.message}`, LOG_TYPE.ERROR);
  640. showStatusMessage('Failed to check for updates', 'error');
  641. }
  642. });
  643. }
  644. // Connect button
  645. const connectButton = document.getElementById('connectButton');
  646. if (connectButton) {
  647. connectButton.addEventListener('click', async () => {
  648. const portSelect = document.getElementById('portSelect');
  649. if (!portSelect || !portSelect.value) {
  650. logMessage('Please select a port first', LOG_TYPE.WARNING);
  651. return;
  652. }
  653. try {
  654. const response = await fetch('/connect', {
  655. method: 'POST',
  656. headers: { 'Content-Type': 'application/json' },
  657. body: JSON.stringify({ port: portSelect.value })
  658. });
  659. if (response.ok) {
  660. logMessage('Connected successfully', LOG_TYPE.SUCCESS);
  661. await updateSerialStatus(true); // Force update after connecting
  662. } else {
  663. throw new Error('Failed to connect');
  664. }
  665. } catch (error) {
  666. logMessage(`Error connecting to device: ${error.message}`, LOG_TYPE.ERROR);
  667. }
  668. });
  669. }
  670. // Disconnect button
  671. const disconnectButton = document.getElementById('disconnectButton');
  672. if (disconnectButton) {
  673. disconnectButton.addEventListener('click', async () => {
  674. try {
  675. const response = await fetch('/disconnect', {
  676. method: 'POST'
  677. });
  678. if (response.ok) {
  679. logMessage('Device disconnected successfully', LOG_TYPE.SUCCESS);
  680. await updateSerialStatus(true); // Force update after disconnecting
  681. } else {
  682. throw new Error('Failed to disconnect device');
  683. }
  684. } catch (error) {
  685. logMessage(`Error disconnecting device: ${error.message}`, LOG_TYPE.ERROR);
  686. }
  687. });
  688. }
  689. // Save preferred port button
  690. const savePreferredPortButton = document.getElementById('savePreferredPort');
  691. if (savePreferredPortButton) {
  692. savePreferredPortButton.addEventListener('click', savePreferredPort);
  693. }
  694. // Save custom clear patterns button
  695. const saveClearPatterns = document.getElementById('saveClearPatterns');
  696. if (saveClearPatterns) {
  697. saveClearPatterns.addEventListener('click', async () => {
  698. const clearFromInInput = document.getElementById('customClearFromInInput');
  699. const clearFromOutInput = document.getElementById('customClearFromOutInput');
  700. if (!clearFromInInput || !clearFromOutInput) {
  701. return;
  702. }
  703. // Validate that the entered patterns exist (if not empty)
  704. const inValue = clearFromInInput.value.trim();
  705. const outValue = clearFromOutInput.value.trim();
  706. if (inValue && window.availablePatterns && !window.availablePatterns.includes(inValue)) {
  707. showStatusMessage(`Pattern not found: ${inValue}`, 'error');
  708. return;
  709. }
  710. if (outValue && window.availablePatterns && !window.availablePatterns.includes(outValue)) {
  711. showStatusMessage(`Pattern not found: ${outValue}`, 'error');
  712. return;
  713. }
  714. try {
  715. const response = await fetch('/api/custom_clear_patterns', {
  716. method: 'POST',
  717. headers: { 'Content-Type': 'application/json' },
  718. body: JSON.stringify({
  719. custom_clear_from_in: inValue || null,
  720. custom_clear_from_out: outValue || null
  721. })
  722. });
  723. if (response.ok) {
  724. showStatusMessage('Clear patterns saved successfully', 'success');
  725. } else {
  726. const error = await response.json();
  727. throw new Error(error.detail || 'Failed to save clear patterns');
  728. }
  729. } catch (error) {
  730. showStatusMessage(`Failed to save clear patterns: ${error.message}`, 'error');
  731. }
  732. });
  733. }
  734. // Save clear pattern speed button
  735. const saveClearSpeed = document.getElementById('saveClearSpeed');
  736. if (saveClearSpeed) {
  737. saveClearSpeed.addEventListener('click', async () => {
  738. const clearPatternSpeedInput = document.getElementById('clearPatternSpeedInput');
  739. if (!clearPatternSpeedInput) {
  740. return;
  741. }
  742. let speed;
  743. if (clearPatternSpeedInput.value === '' || clearPatternSpeedInput.value === null) {
  744. // Empty value means use default (None)
  745. speed = null;
  746. } else {
  747. speed = parseInt(clearPatternSpeedInput.value);
  748. // Validate speed only if it's not null
  749. if (isNaN(speed) || speed < 50 || speed > 2000) {
  750. showStatusMessage('Clear pattern speed must be between 50 and 2000, or leave empty for default', 'error');
  751. return;
  752. }
  753. }
  754. try {
  755. const response = await fetch('/api/clear_pattern_speed', {
  756. method: 'POST',
  757. headers: { 'Content-Type': 'application/json' },
  758. body: JSON.stringify({ clear_pattern_speed: speed })
  759. });
  760. if (response.ok) {
  761. const data = await response.json();
  762. if (speed === null) {
  763. showStatusMessage(`Clear pattern speed set to default (${data.effective_speed} steps/min)`, 'success');
  764. } else {
  765. showStatusMessage(`Clear pattern speed set to ${speed} steps/min`, 'success');
  766. }
  767. // Update the effective speed display
  768. const effectiveClearSpeed = document.getElementById('effectiveClearSpeed');
  769. if (effectiveClearSpeed) {
  770. if (speed === null) {
  771. effectiveClearSpeed.textContent = `Using default pattern speed: ${data.effective_speed} steps/min`;
  772. } else {
  773. effectiveClearSpeed.textContent = `Current: ${speed} steps/min`;
  774. }
  775. }
  776. } else {
  777. const error = await response.json();
  778. throw new Error(error.detail || 'Failed to save clear pattern speed');
  779. }
  780. } catch (error) {
  781. showStatusMessage(`Failed to save clear pattern speed: ${error.message}`, 'error');
  782. }
  783. });
  784. }
  785. }
  786. // Button click handlers
  787. document.addEventListener('DOMContentLoaded', function() {
  788. // Home button
  789. const homeButton = document.getElementById('homeButton');
  790. if (homeButton) {
  791. homeButton.addEventListener('click', async () => {
  792. try {
  793. const response = await fetch('/send_home', {
  794. method: 'POST',
  795. headers: {
  796. 'Content-Type': 'application/json'
  797. }
  798. });
  799. const data = await response.json();
  800. if (data.success) {
  801. updateStatus('Moving to home position...');
  802. }
  803. } catch (error) {
  804. console.error('Error sending home command:', error);
  805. updateStatus('Error: Failed to move to home position');
  806. }
  807. });
  808. }
  809. // Stop button
  810. const stopButton = document.getElementById('stopButton');
  811. if (stopButton) {
  812. stopButton.addEventListener('click', async () => {
  813. try {
  814. const response = await fetch('/stop_execution', {
  815. method: 'POST',
  816. headers: {
  817. 'Content-Type': 'application/json'
  818. }
  819. });
  820. const data = await response.json();
  821. if (data.success) {
  822. updateStatus('Execution stopped');
  823. }
  824. } catch (error) {
  825. console.error('Error stopping execution:', error);
  826. updateStatus('Error: Failed to stop execution');
  827. }
  828. });
  829. }
  830. // Move to Center button
  831. const centerButton = document.getElementById('centerButton');
  832. if (centerButton) {
  833. centerButton.addEventListener('click', async () => {
  834. try {
  835. const response = await fetch('/move_to_center', {
  836. method: 'POST',
  837. headers: {
  838. 'Content-Type': 'application/json'
  839. }
  840. });
  841. const data = await response.json();
  842. if (data.success) {
  843. updateStatus('Moving to center position...');
  844. }
  845. } catch (error) {
  846. console.error('Error moving to center:', error);
  847. updateStatus('Error: Failed to move to center');
  848. }
  849. });
  850. }
  851. // Move to Perimeter button
  852. const perimeterButton = document.getElementById('perimeterButton');
  853. if (perimeterButton) {
  854. perimeterButton.addEventListener('click', async () => {
  855. try {
  856. const response = await fetch('/move_to_perimeter', {
  857. method: 'POST',
  858. headers: {
  859. 'Content-Type': 'application/json'
  860. }
  861. });
  862. const data = await response.json();
  863. if (data.success) {
  864. updateStatus('Moving to perimeter position...');
  865. }
  866. } catch (error) {
  867. console.error('Error moving to perimeter:', error);
  868. updateStatus('Error: Failed to move to perimeter');
  869. }
  870. });
  871. }
  872. });
  873. // Function to update status
  874. function updateStatus(message) {
  875. const statusElement = document.querySelector('.text-slate-800.text-base.font-medium.leading-normal');
  876. if (statusElement) {
  877. statusElement.textContent = message;
  878. // Reset status after 3 seconds if it's a temporary message
  879. if (message.includes('Moving') || message.includes('Execution')) {
  880. setTimeout(() => {
  881. statusElement.textContent = 'Status';
  882. }, 3000);
  883. }
  884. }
  885. }
  886. // Function to show status messages (using existing base.js showStatusMessage if available)
  887. function showStatusMessage(message, type) {
  888. if (typeof window.showStatusMessage === 'function') {
  889. window.showStatusMessage(message, type);
  890. } else {
  891. // Fallback to console logging
  892. console.log(`[${type}] ${message}`);
  893. }
  894. }
  895. // Function to show update instructions modal
  896. function showUpdateInstructionsModal(data) {
  897. // Create modal HTML
  898. const modal = document.createElement('div');
  899. modal.id = 'updateInstructionsModal';
  900. modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4';
  901. modal.innerHTML = `
  902. <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md">
  903. <div class="p-6">
  904. <div class="text-center mb-4">
  905. <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-200 mb-2">Manual Update Required</h2>
  906. <p class="text-gray-600 dark:text-gray-400 text-sm">
  907. ${data.message}
  908. </p>
  909. </div>
  910. <div class="text-gray-700 dark:text-gray-300 text-sm mb-6">
  911. <p class="mb-3">${data.instructions}</p>
  912. </div>
  913. <div class="flex gap-3 justify-center">
  914. <button id="openGitHubRelease" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">
  915. View Update Instructions
  916. </button>
  917. <button id="closeUpdateModal" class="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition-colors">
  918. Close
  919. </button>
  920. </div>
  921. </div>
  922. </div>
  923. `;
  924. document.body.appendChild(modal);
  925. // Add event listeners
  926. const openGitHubButton = modal.querySelector('#openGitHubRelease');
  927. const closeButton = modal.querySelector('#closeUpdateModal');
  928. openGitHubButton.addEventListener('click', () => {
  929. window.open(data.manual_update_url, '_blank');
  930. document.body.removeChild(modal);
  931. });
  932. closeButton.addEventListener('click', () => {
  933. document.body.removeChild(modal);
  934. });
  935. // Close on outside click
  936. modal.addEventListener('click', (e) => {
  937. if (e.target === modal) {
  938. document.body.removeChild(modal);
  939. }
  940. });
  941. }
  942. // Autocomplete functionality
  943. function initializeAutocomplete(inputId, suggestionsId, clearButtonId, patterns) {
  944. const input = document.getElementById(inputId);
  945. const suggestionsDiv = document.getElementById(suggestionsId);
  946. const clearButton = document.getElementById(clearButtonId);
  947. let selectedIndex = -1;
  948. if (!input || !suggestionsDiv) return;
  949. // Function to update clear button visibility
  950. function updateClearButton() {
  951. if (clearButton) {
  952. if (input.value.trim()) {
  953. clearButton.classList.remove('hidden');
  954. } else {
  955. clearButton.classList.add('hidden');
  956. }
  957. }
  958. }
  959. // Format pattern name for display
  960. function formatPatternName(pattern) {
  961. return pattern.replace('.thr', '').replace(/_/g, ' ');
  962. }
  963. // Filter patterns based on input
  964. function filterPatterns(searchTerm) {
  965. if (!searchTerm) return patterns.slice(0, 20); // Show first 20 when empty
  966. const term = searchTerm.toLowerCase();
  967. return patterns.filter(pattern => {
  968. const name = pattern.toLowerCase();
  969. return name.includes(term);
  970. }).sort((a, b) => {
  971. // Prioritize patterns that start with the search term
  972. const aStarts = a.toLowerCase().startsWith(term);
  973. const bStarts = b.toLowerCase().startsWith(term);
  974. if (aStarts && !bStarts) return -1;
  975. if (!aStarts && bStarts) return 1;
  976. return a.localeCompare(b);
  977. }).slice(0, 20); // Limit to 20 results
  978. }
  979. // Highlight matching text
  980. function highlightMatch(text, searchTerm) {
  981. if (!searchTerm) return text;
  982. const regex = new RegExp(`(${searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
  983. return text.replace(regex, '<mark>$1</mark>');
  984. }
  985. // Show suggestions
  986. function showSuggestions(searchTerm) {
  987. const filtered = filterPatterns(searchTerm);
  988. if (filtered.length === 0 && searchTerm) {
  989. suggestionsDiv.innerHTML = '<div class="suggestion-item" style="cursor: default; color: #9ca3af;">No patterns found</div>';
  990. suggestionsDiv.classList.remove('hidden');
  991. return;
  992. }
  993. suggestionsDiv.innerHTML = filtered.map((pattern, index) => {
  994. const displayName = formatPatternName(pattern);
  995. const highlighted = highlightMatch(displayName, searchTerm);
  996. return `<div class="suggestion-item" data-value="${pattern}" data-index="${index}">${highlighted}</div>`;
  997. }).join('');
  998. suggestionsDiv.classList.remove('hidden');
  999. selectedIndex = -1;
  1000. }
  1001. // Hide suggestions
  1002. function hideSuggestions() {
  1003. setTimeout(() => {
  1004. suggestionsDiv.classList.add('hidden');
  1005. selectedIndex = -1;
  1006. }, 200);
  1007. }
  1008. // Select suggestion
  1009. function selectSuggestion(value) {
  1010. input.value = value;
  1011. hideSuggestions();
  1012. updateClearButton();
  1013. }
  1014. // Handle keyboard navigation
  1015. function handleKeyboard(e) {
  1016. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  1017. if (e.key === 'ArrowDown') {
  1018. e.preventDefault();
  1019. selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
  1020. updateSelection(items);
  1021. } else if (e.key === 'ArrowUp') {
  1022. e.preventDefault();
  1023. selectedIndex = Math.max(selectedIndex - 1, -1);
  1024. updateSelection(items);
  1025. } else if (e.key === 'Enter') {
  1026. e.preventDefault();
  1027. if (selectedIndex >= 0 && items[selectedIndex]) {
  1028. selectSuggestion(items[selectedIndex].dataset.value);
  1029. } else if (items.length === 1) {
  1030. selectSuggestion(items[0].dataset.value);
  1031. }
  1032. } else if (e.key === 'Escape') {
  1033. hideSuggestions();
  1034. }
  1035. }
  1036. // Update visual selection
  1037. function updateSelection(items) {
  1038. items.forEach((item, index) => {
  1039. if (index === selectedIndex) {
  1040. item.classList.add('selected');
  1041. item.scrollIntoView({ block: 'nearest' });
  1042. } else {
  1043. item.classList.remove('selected');
  1044. }
  1045. });
  1046. }
  1047. // Event listeners
  1048. input.addEventListener('input', (e) => {
  1049. const value = e.target.value.trim();
  1050. updateClearButton();
  1051. if (value.length > 0 || e.target === document.activeElement) {
  1052. showSuggestions(value);
  1053. } else {
  1054. hideSuggestions();
  1055. }
  1056. });
  1057. input.addEventListener('focus', () => {
  1058. const value = input.value.trim();
  1059. showSuggestions(value);
  1060. });
  1061. input.addEventListener('blur', hideSuggestions);
  1062. input.addEventListener('keydown', handleKeyboard);
  1063. // Click handler for suggestions
  1064. suggestionsDiv.addEventListener('click', (e) => {
  1065. const item = e.target.closest('.suggestion-item[data-value]');
  1066. if (item) {
  1067. selectSuggestion(item.dataset.value);
  1068. }
  1069. });
  1070. // Mouse hover handler
  1071. suggestionsDiv.addEventListener('mouseover', (e) => {
  1072. const item = e.target.closest('.suggestion-item[data-value]');
  1073. if (item) {
  1074. selectedIndex = parseInt(item.dataset.index);
  1075. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  1076. updateSelection(items);
  1077. }
  1078. });
  1079. // Clear button handler
  1080. if (clearButton) {
  1081. clearButton.addEventListener('click', () => {
  1082. input.value = '';
  1083. updateClearButton();
  1084. hideSuggestions();
  1085. input.focus();
  1086. });
  1087. }
  1088. // Initialize clear button visibility
  1089. updateClearButton();
  1090. }
  1091. // auto_play Mode Functions
  1092. async function initializeauto_playMode() {
  1093. const auto_playToggle = document.getElementById('auto_playModeToggle');
  1094. const auto_playSettings = document.getElementById('auto_playSettings');
  1095. const auto_playPlaylistSelect = document.getElementById('auto_playPlaylistSelect');
  1096. const auto_playRunModeSelect = document.getElementById('auto_playRunModeSelect');
  1097. const auto_playPauseTimeInput = document.getElementById('auto_playPauseTimeInput');
  1098. const auto_playClearPatternSelect = document.getElementById('auto_playClearPatternSelect');
  1099. const auto_playShuffleToggle = document.getElementById('auto_playShuffleToggle');
  1100. // Load current auto_play settings
  1101. try {
  1102. const response = await fetch('/api/auto_play-mode');
  1103. const data = await response.json();
  1104. auto_playToggle.checked = data.enabled;
  1105. if (data.enabled) {
  1106. auto_playSettings.style.display = 'block';
  1107. }
  1108. // Set current values
  1109. auto_playRunModeSelect.value = data.run_mode || 'loop';
  1110. auto_playPauseTimeInput.value = data.pause_time || 5.0;
  1111. auto_playClearPatternSelect.value = data.clear_pattern || 'adaptive';
  1112. auto_playShuffleToggle.checked = data.shuffle || false;
  1113. // Load playlists for selection
  1114. const playlistsResponse = await fetch('/list_all_playlists');
  1115. const playlists = await playlistsResponse.json();
  1116. // Clear and populate playlist select
  1117. auto_playPlaylistSelect.innerHTML = '<option value="">Select a playlist...</option>';
  1118. playlists.forEach(playlist => {
  1119. const option = document.createElement('option');
  1120. option.value = playlist;
  1121. option.textContent = playlist;
  1122. if (playlist === data.playlist) {
  1123. option.selected = true;
  1124. }
  1125. auto_playPlaylistSelect.appendChild(option);
  1126. });
  1127. } catch (error) {
  1128. logMessage(`Error loading auto_play settings: ${error.message}`, LOG_TYPE.ERROR);
  1129. }
  1130. // Function to save settings
  1131. async function saveSettings() {
  1132. try {
  1133. const response = await fetch('/api/auto_play-mode', {
  1134. method: 'POST',
  1135. headers: { 'Content-Type': 'application/json' },
  1136. body: JSON.stringify({
  1137. enabled: auto_playToggle.checked,
  1138. playlist: auto_playPlaylistSelect.value || null,
  1139. run_mode: auto_playRunModeSelect.value,
  1140. pause_time: parseFloat(auto_playPauseTimeInput.value) || 0,
  1141. clear_pattern: auto_playClearPatternSelect.value,
  1142. shuffle: auto_playShuffleToggle.checked
  1143. })
  1144. });
  1145. if (!response.ok) {
  1146. throw new Error('Failed to save settings');
  1147. }
  1148. } catch (error) {
  1149. logMessage(`Error saving auto_play settings: ${error.message}`, LOG_TYPE.ERROR);
  1150. }
  1151. }
  1152. // Toggle auto_play settings visibility and save
  1153. auto_playToggle.addEventListener('change', async () => {
  1154. auto_playSettings.style.display = auto_playToggle.checked ? 'block' : 'none';
  1155. await saveSettings();
  1156. });
  1157. // Save when any setting changes
  1158. auto_playPlaylistSelect.addEventListener('change', saveSettings);
  1159. auto_playRunModeSelect.addEventListener('change', saveSettings);
  1160. auto_playPauseTimeInput.addEventListener('change', saveSettings);
  1161. auto_playPauseTimeInput.addEventListener('input', saveSettings); // Save as user types
  1162. auto_playClearPatternSelect.addEventListener('change', saveSettings);
  1163. auto_playShuffleToggle.addEventListener('change', saveSettings);
  1164. }
  1165. // Initialize auto_play mode when DOM is ready
  1166. document.addEventListener('DOMContentLoaded', function() {
  1167. initializeauto_playMode();
  1168. initializeStillSandsMode();
  1169. initializeHomingConfig();
  1170. });
  1171. // Still Sands Mode Functions
  1172. async function initializeStillSandsMode() {
  1173. logMessage('Initializing Still Sands mode', LOG_TYPE.INFO);
  1174. const stillSandsToggle = document.getElementById('scheduledPauseToggle');
  1175. const stillSandsSettings = document.getElementById('scheduledPauseSettings');
  1176. const addTimeSlotButton = document.getElementById('addTimeSlotButton');
  1177. const saveStillSandsButton = document.getElementById('savePauseSettings');
  1178. const timeSlotsContainer = document.getElementById('timeSlotsContainer');
  1179. const wledControlToggle = document.getElementById('stillSandsWledControl');
  1180. const finishPatternToggle = document.getElementById('stillSandsFinishPattern');
  1181. // Check if elements exist
  1182. if (!stillSandsToggle || !stillSandsSettings || !addTimeSlotButton || !saveStillSandsButton || !timeSlotsContainer) {
  1183. logMessage('Still Sands elements not found, skipping initialization', LOG_TYPE.WARNING);
  1184. logMessage(`Found elements: toggle=${!!stillSandsToggle}, settings=${!!stillSandsSettings}, addBtn=${!!addTimeSlotButton}, saveBtn=${!!saveStillSandsButton}, container=${!!timeSlotsContainer}`, LOG_TYPE.WARNING);
  1185. return;
  1186. }
  1187. logMessage('All Still Sands elements found successfully', LOG_TYPE.INFO);
  1188. // Track time slots
  1189. let timeSlots = [];
  1190. let slotIdCounter = 0;
  1191. // Load current Still Sands settings from initial data
  1192. try {
  1193. // Use the data loaded during page initialization, fallback to API if not available
  1194. let data;
  1195. if (window.initialStillSandsData) {
  1196. data = window.initialStillSandsData;
  1197. // Clear the global variable after use
  1198. delete window.initialStillSandsData;
  1199. } else {
  1200. // Fallback to API call if initial data not available
  1201. const response = await fetch('/api/scheduled-pause');
  1202. data = await response.json();
  1203. }
  1204. stillSandsToggle.checked = data.enabled || false;
  1205. if (data.enabled) {
  1206. stillSandsSettings.style.display = 'block';
  1207. }
  1208. // Load WLED control setting
  1209. if (wledControlToggle) {
  1210. wledControlToggle.checked = data.control_wled || false;
  1211. }
  1212. // Load finish pattern setting
  1213. if (finishPatternToggle) {
  1214. finishPatternToggle.checked = data.finish_pattern || false;
  1215. }
  1216. // Load existing time slots
  1217. timeSlots = data.time_slots || [];
  1218. // Assign IDs to loaded slots BEFORE rendering
  1219. if (timeSlots.length > 0) {
  1220. slotIdCounter = 0;
  1221. timeSlots.forEach(slot => {
  1222. slot.id = ++slotIdCounter;
  1223. });
  1224. }
  1225. renderTimeSlots();
  1226. } catch (error) {
  1227. logMessage(`Error loading Still Sands settings: ${error.message}`, LOG_TYPE.ERROR);
  1228. // Initialize with empty settings if load fails
  1229. timeSlots = [];
  1230. renderTimeSlots();
  1231. }
  1232. // Function to validate time format (HH:MM)
  1233. function isValidTime(timeString) {
  1234. const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
  1235. return timeRegex.test(timeString);
  1236. }
  1237. // Function to create a new time slot element
  1238. function createTimeSlotElement(slot) {
  1239. const slotDiv = document.createElement('div');
  1240. slotDiv.className = 'time-slot-item';
  1241. slotDiv.dataset.slotId = slot.id;
  1242. slotDiv.innerHTML = `
  1243. <div class="flex items-center gap-3">
  1244. <div class="flex-1 grid grid-cols-1 md:grid-cols-2 gap-3">
  1245. <div class="flex flex-col gap-1">
  1246. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">Start Time</label>
  1247. <input
  1248. type="time"
  1249. 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"
  1250. value="${slot.start_time || ''}"
  1251. required
  1252. />
  1253. </div>
  1254. <div class="flex flex-col gap-1">
  1255. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">End Time</label>
  1256. <input
  1257. type="time"
  1258. 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"
  1259. value="${slot.end_time || ''}"
  1260. required
  1261. />
  1262. </div>
  1263. </div>
  1264. <div class="flex flex-col gap-1">
  1265. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">Days</label>
  1266. <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">
  1267. <option value="daily" ${slot.days === 'daily' ? 'selected' : ''}>Daily</option>
  1268. <option value="weekdays" ${slot.days === 'weekdays' ? 'selected' : ''}>Weekdays</option>
  1269. <option value="weekends" ${slot.days === 'weekends' ? 'selected' : ''}>Weekends</option>
  1270. <option value="custom" ${slot.days === 'custom' ? 'selected' : ''}>Custom</option>
  1271. </select>
  1272. </div>
  1273. <button
  1274. type="button"
  1275. 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"
  1276. title="Remove time slot"
  1277. >
  1278. <span class="material-icons text-base">delete</span>
  1279. </button>
  1280. </div>
  1281. <div class="custom-days-container mt-2" style="display: ${slot.days === 'custom' ? 'block' : 'none'};">
  1282. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium mb-1 block">Select Days</label>
  1283. <div class="flex flex-wrap gap-2">
  1284. ${['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'].map(day => `
  1285. <label class="flex items-center gap-1 text-xs">
  1286. <input
  1287. type="checkbox"
  1288. name="custom-days-${slot.id}"
  1289. value="${day}"
  1290. ${slot.custom_days && slot.custom_days.includes(day) ? 'checked' : ''}
  1291. class="rounded border-slate-300 text-sky-600 focus:ring-sky-500"
  1292. />
  1293. <span class="text-slate-700 dark:text-slate-300 capitalize">${day.substring(0, 3)}</span>
  1294. </label>
  1295. `).join('')}
  1296. </div>
  1297. </div>
  1298. `;
  1299. // Add event listeners for this slot
  1300. const startTimeInput = slotDiv.querySelector('.start-time');
  1301. const endTimeInput = slotDiv.querySelector('.end-time');
  1302. const daysSelect = slotDiv.querySelector('.days-select');
  1303. const customDaysContainer = slotDiv.querySelector('.custom-days-container');
  1304. const removeButton = slotDiv.querySelector('.remove-slot-btn');
  1305. // Show/hide custom days based on selection
  1306. daysSelect.addEventListener('change', () => {
  1307. customDaysContainer.style.display = daysSelect.value === 'custom' ? 'block' : 'none';
  1308. updateTimeSlot(slot.id);
  1309. });
  1310. // Update slot data when inputs change
  1311. startTimeInput.addEventListener('change', () => updateTimeSlot(slot.id));
  1312. endTimeInput.addEventListener('change', () => updateTimeSlot(slot.id));
  1313. // Handle custom day checkboxes
  1314. customDaysContainer.addEventListener('change', () => updateTimeSlot(slot.id));
  1315. // Remove slot button
  1316. removeButton.addEventListener('click', () => {
  1317. removeTimeSlot(slot.id);
  1318. });
  1319. return slotDiv;
  1320. }
  1321. // Function to render all time slots
  1322. function renderTimeSlots() {
  1323. timeSlotsContainer.innerHTML = '';
  1324. if (timeSlots.length === 0) {
  1325. timeSlotsContainer.innerHTML = `
  1326. <div class="text-center py-8 text-slate-500 dark:text-slate-400">
  1327. <span class="material-icons text-4xl mb-2 block">schedule</span>
  1328. <p>No time slots configured</p>
  1329. <p class="text-xs mt-1">Click "Add Time Slot" to create a pause schedule</p>
  1330. </div>
  1331. `;
  1332. return;
  1333. }
  1334. timeSlots.forEach(slot => {
  1335. const slotElement = createTimeSlotElement(slot);
  1336. timeSlotsContainer.appendChild(slotElement);
  1337. });
  1338. }
  1339. // Function to add a new time slot
  1340. function addTimeSlot() {
  1341. const newSlot = {
  1342. id: ++slotIdCounter,
  1343. start_time: '22:00',
  1344. end_time: '08:00',
  1345. days: 'daily',
  1346. custom_days: []
  1347. };
  1348. timeSlots.push(newSlot);
  1349. renderTimeSlots();
  1350. }
  1351. // Function to remove a time slot
  1352. function removeTimeSlot(slotId) {
  1353. timeSlots = timeSlots.filter(slot => slot.id !== slotId);
  1354. renderTimeSlots();
  1355. }
  1356. // Function to update a time slot's data
  1357. function updateTimeSlot(slotId) {
  1358. const slotElement = timeSlotsContainer.querySelector(`[data-slot-id="${slotId}"]`);
  1359. if (!slotElement) return;
  1360. const slot = timeSlots.find(s => s.id === slotId);
  1361. if (!slot) return;
  1362. // Update slot data from inputs
  1363. slot.start_time = slotElement.querySelector('.start-time').value;
  1364. slot.end_time = slotElement.querySelector('.end-time').value;
  1365. slot.days = slotElement.querySelector('.days-select').value;
  1366. // Update custom days if applicable
  1367. if (slot.days === 'custom') {
  1368. const checkedDays = Array.from(slotElement.querySelectorAll(`input[name="custom-days-${slotId}"]:checked`))
  1369. .map(cb => cb.value);
  1370. slot.custom_days = checkedDays;
  1371. } else {
  1372. slot.custom_days = [];
  1373. }
  1374. }
  1375. // Function to validate all time slots
  1376. function validateTimeSlots() {
  1377. const errors = [];
  1378. timeSlots.forEach((slot, index) => {
  1379. if (!slot.start_time || !isValidTime(slot.start_time)) {
  1380. errors.push(`Time slot ${index + 1}: Invalid start time`);
  1381. }
  1382. if (!slot.end_time || !isValidTime(slot.end_time)) {
  1383. errors.push(`Time slot ${index + 1}: Invalid end time`);
  1384. }
  1385. if (slot.days === 'custom' && (!slot.custom_days || slot.custom_days.length === 0)) {
  1386. errors.push(`Time slot ${index + 1}: Please select at least one day for custom schedule`);
  1387. }
  1388. });
  1389. return errors;
  1390. }
  1391. // Function to save settings
  1392. async function saveStillSandsSettings() {
  1393. // Update all slots from current form values
  1394. timeSlots.forEach(slot => updateTimeSlot(slot.id));
  1395. // Validate time slots
  1396. const validationErrors = validateTimeSlots();
  1397. if (validationErrors.length > 0) {
  1398. showStatusMessage(`Validation errors: ${validationErrors.join(', ')}`, 'error');
  1399. return;
  1400. }
  1401. // Update button UI to show loading state
  1402. const originalButtonHTML = saveStillSandsButton.innerHTML;
  1403. saveStillSandsButton.disabled = true;
  1404. saveStillSandsButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1405. try {
  1406. const response = await fetch('/api/scheduled-pause', {
  1407. method: 'POST',
  1408. headers: { 'Content-Type': 'application/json' },
  1409. body: JSON.stringify({
  1410. enabled: stillSandsToggle.checked,
  1411. control_wled: wledControlToggle ? wledControlToggle.checked : false,
  1412. finish_pattern: finishPatternToggle ? finishPatternToggle.checked : false,
  1413. time_slots: timeSlots.map(slot => ({
  1414. start_time: slot.start_time,
  1415. end_time: slot.end_time,
  1416. days: slot.days,
  1417. custom_days: slot.custom_days
  1418. }))
  1419. })
  1420. });
  1421. if (!response.ok) {
  1422. const errorData = await response.json();
  1423. throw new Error(errorData.detail || 'Failed to save Still Sands settings');
  1424. }
  1425. // Show success state temporarily
  1426. saveStillSandsButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1427. showStatusMessage('Still Sands settings saved successfully', 'success');
  1428. // Restore button after 2 seconds
  1429. setTimeout(() => {
  1430. saveStillSandsButton.innerHTML = originalButtonHTML;
  1431. saveStillSandsButton.disabled = false;
  1432. }, 2000);
  1433. } catch (error) {
  1434. logMessage(`Error saving Still Sands settings: ${error.message}`, LOG_TYPE.ERROR);
  1435. showStatusMessage(`Failed to save settings: ${error.message}`, 'error');
  1436. // Restore button immediately on error
  1437. saveStillSandsButton.innerHTML = originalButtonHTML;
  1438. saveStillSandsButton.disabled = false;
  1439. }
  1440. }
  1441. // Note: Slot IDs are now assigned during initialization above, before first render
  1442. // Event listeners
  1443. stillSandsToggle.addEventListener('change', async () => {
  1444. logMessage(`Still Sands toggle changed: ${stillSandsToggle.checked}`, LOG_TYPE.INFO);
  1445. stillSandsSettings.style.display = stillSandsToggle.checked ? 'block' : 'none';
  1446. logMessage(`Settings display set to: ${stillSandsSettings.style.display}`, LOG_TYPE.INFO);
  1447. // Auto-save when toggle changes
  1448. try {
  1449. await saveStillSandsSettings();
  1450. const statusText = stillSandsToggle.checked ? 'enabled' : 'disabled';
  1451. showStatusMessage(`Still Sands ${statusText} successfully`, 'success');
  1452. } catch (error) {
  1453. logMessage(`Error saving Still Sands toggle: ${error.message}`, LOG_TYPE.ERROR);
  1454. showStatusMessage(`Failed to save Still Sands setting: ${error.message}`, 'error');
  1455. }
  1456. });
  1457. addTimeSlotButton.addEventListener('click', addTimeSlot);
  1458. saveStillSandsButton.addEventListener('click', saveStillSandsSettings);
  1459. // Add listener for WLED control toggle
  1460. if (wledControlToggle) {
  1461. wledControlToggle.addEventListener('change', async () => {
  1462. logMessage(`WLED control toggle changed: ${wledControlToggle.checked}`, LOG_TYPE.INFO);
  1463. // Auto-save when WLED control changes
  1464. await saveStillSandsSettings();
  1465. });
  1466. }
  1467. // Add listener for finish pattern toggle
  1468. if (finishPatternToggle) {
  1469. finishPatternToggle.addEventListener('change', async () => {
  1470. logMessage(`Finish pattern toggle changed: ${finishPatternToggle.checked}`, LOG_TYPE.INFO);
  1471. // Auto-save when finish pattern setting changes
  1472. await saveStillSandsSettings();
  1473. });
  1474. }
  1475. }
  1476. // Homing Configuration
  1477. async function initializeHomingConfig() {
  1478. logMessage('Initializing homing configuration', LOG_TYPE.INFO);
  1479. const homingModeCrash = document.getElementById('homingModeCrash');
  1480. const homingModeSensor = document.getElementById('homingModeSensor');
  1481. const angularOffsetInput = document.getElementById('angularOffsetInput');
  1482. const compassOffsetContainer = document.getElementById('compassOffsetContainer');
  1483. const saveHomingConfigButton = document.getElementById('saveHomingConfig');
  1484. const homingInfoContent = document.getElementById('homingInfoContent');
  1485. // Check if elements exist
  1486. if (!homingModeCrash || !homingModeSensor || !angularOffsetInput || !saveHomingConfigButton || !homingInfoContent || !compassOffsetContainer) {
  1487. logMessage('Homing configuration elements not found, skipping initialization', LOG_TYPE.WARNING);
  1488. return;
  1489. }
  1490. logMessage('Homing configuration elements found successfully', LOG_TYPE.INFO);
  1491. // Function to get selected homing mode
  1492. function getSelectedMode() {
  1493. return homingModeCrash.checked ? 0 : 1;
  1494. }
  1495. // Function to update info box and visibility based on selected mode
  1496. function updateHomingInfo() {
  1497. const mode = getSelectedMode();
  1498. // Show/hide compass offset based on mode
  1499. if (mode === 0) {
  1500. compassOffsetContainer.style.display = 'none';
  1501. homingInfoContent.innerHTML = `
  1502. <p class="font-medium text-blue-800">Crash Homing Mode:</p>
  1503. <ul class="mt-1 space-y-1 text-blue-700">
  1504. <li>• Y axis moves -22mm (or -30mm for mini) until physical stop</li>
  1505. <li>• Theta set to 0, rho set to 0</li>
  1506. <li>• No x0 y0 command sent</li>
  1507. <li>• No hardware sensors required</li>
  1508. </ul>
  1509. `;
  1510. } else {
  1511. compassOffsetContainer.style.display = 'block';
  1512. homingInfoContent.innerHTML = `
  1513. <p class="font-medium text-blue-800">Sensor Homing Mode:</p>
  1514. <ul class="mt-1 space-y-1 text-blue-700">
  1515. <li>• Requires hardware limit switches</li>
  1516. <li>• Requires additional configuration</li>
  1517. </ul>
  1518. `;
  1519. }
  1520. }
  1521. // Load current homing configuration
  1522. try {
  1523. const response = await fetch('/api/homing-config');
  1524. const data = await response.json();
  1525. // Set radio button based on mode
  1526. if (data.homing_mode === 1) {
  1527. homingModeSensor.checked = true;
  1528. } else {
  1529. homingModeCrash.checked = true;
  1530. }
  1531. angularOffsetInput.value = data.angular_homing_offset_degrees || 0;
  1532. updateHomingInfo();
  1533. logMessage(`Loaded homing config: mode=${data.homing_mode}, offset=${data.angular_homing_offset_degrees}°`, LOG_TYPE.INFO);
  1534. } catch (error) {
  1535. logMessage(`Error loading homing configuration: ${error.message}`, LOG_TYPE.ERROR);
  1536. // Initialize with defaults if load fails
  1537. homingModeCrash.checked = true;
  1538. angularOffsetInput.value = 0;
  1539. updateHomingInfo();
  1540. }
  1541. // Function to save homing configuration
  1542. async function saveHomingConfig() {
  1543. // Update button UI to show loading state
  1544. const originalButtonHTML = saveHomingConfigButton.innerHTML;
  1545. saveHomingConfigButton.disabled = true;
  1546. saveHomingConfigButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1547. try {
  1548. const response = await fetch('/api/homing-config', {
  1549. method: 'POST',
  1550. headers: { 'Content-Type': 'application/json' },
  1551. body: JSON.stringify({
  1552. homing_mode: getSelectedMode(),
  1553. angular_homing_offset_degrees: parseFloat(angularOffsetInput.value) || 0
  1554. })
  1555. });
  1556. if (!response.ok) {
  1557. const errorData = await response.json();
  1558. throw new Error(errorData.detail || 'Failed to save homing configuration');
  1559. }
  1560. // Show success state temporarily
  1561. saveHomingConfigButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1562. showStatusMessage('Homing configuration saved successfully', 'success');
  1563. // Restore button after 2 seconds
  1564. setTimeout(() => {
  1565. saveHomingConfigButton.innerHTML = originalButtonHTML;
  1566. saveHomingConfigButton.disabled = false;
  1567. }, 2000);
  1568. } catch (error) {
  1569. logMessage(`Error saving homing configuration: ${error.message}`, LOG_TYPE.ERROR);
  1570. showStatusMessage(`Failed to save homing configuration: ${error.message}`, 'error');
  1571. // Restore button immediately on error
  1572. saveHomingConfigButton.innerHTML = originalButtonHTML;
  1573. saveHomingConfigButton.disabled = false;
  1574. }
  1575. }
  1576. // Event listeners
  1577. homingModeCrash.addEventListener('change', updateHomingInfo);
  1578. homingModeSensor.addEventListener('change', updateHomingInfo);
  1579. saveHomingConfigButton.addEventListener('click', saveHomingConfig);
  1580. }
  1581. // Toggle password visibility helper
  1582. function togglePasswordVisibility(inputId, button) {
  1583. const input = document.getElementById(inputId);
  1584. if (!input || !button) return;
  1585. const icon = button.querySelector('.material-icons');
  1586. if (input.type === 'password') {
  1587. input.type = 'text';
  1588. if (icon) icon.textContent = 'visibility';
  1589. } else {
  1590. input.type = 'password';
  1591. if (icon) icon.textContent = 'visibility_off';
  1592. }
  1593. }
  1594. // MQTT Configuration
  1595. async function initializeMqttConfig() {
  1596. logMessage('Initializing MQTT configuration', LOG_TYPE.INFO);
  1597. const mqttEnableToggle = document.getElementById('mqttEnableToggle');
  1598. const mqttSettings = document.getElementById('mqttSettings');
  1599. const mqttStatusBanner = document.getElementById('mqttStatusBanner');
  1600. const mqttConnectedBanner = document.getElementById('mqttConnectedBanner');
  1601. const mqttDisconnectedBanner = document.getElementById('mqttDisconnectedBanner');
  1602. const mqttBrokerInput = document.getElementById('mqttBrokerInput');
  1603. const mqttPortInput = document.getElementById('mqttPortInput');
  1604. const mqttUsernameInput = document.getElementById('mqttUsernameInput');
  1605. const mqttPasswordInput = document.getElementById('mqttPasswordInput');
  1606. const mqttDeviceNameInput = document.getElementById('mqttDeviceNameInput');
  1607. const mqttDeviceIdInput = document.getElementById('mqttDeviceIdInput');
  1608. const mqttClientIdInput = document.getElementById('mqttClientIdInput');
  1609. const mqttDiscoveryPrefixInput = document.getElementById('mqttDiscoveryPrefixInput');
  1610. const testMqttButton = document.getElementById('testMqttConnection');
  1611. const mqttTestResult = document.getElementById('mqttTestResult');
  1612. const saveMqttButton = document.getElementById('saveMqttConfig');
  1613. const mqttRestartNotice = document.getElementById('mqttRestartNotice');
  1614. // Check if elements exist
  1615. if (!mqttEnableToggle || !mqttSettings || !saveMqttButton) {
  1616. logMessage('MQTT configuration elements not found, skipping initialization', LOG_TYPE.WARNING);
  1617. return;
  1618. }
  1619. logMessage('MQTT configuration elements found successfully', LOG_TYPE.INFO);
  1620. // Track if settings have changed (to show restart notice)
  1621. let originalConfig = null;
  1622. let configChanged = false;
  1623. // Function to update UI based on enabled state
  1624. function updateMqttSettingsVisibility() {
  1625. mqttSettings.style.display = mqttEnableToggle.checked ? 'block' : 'none';
  1626. if (mqttStatusBanner) {
  1627. mqttStatusBanner.classList.toggle('hidden', !mqttEnableToggle.checked);
  1628. }
  1629. }
  1630. // Function to update connection status banners
  1631. function updateConnectionStatus(connected) {
  1632. if (mqttConnectedBanner && mqttDisconnectedBanner) {
  1633. if (connected) {
  1634. mqttConnectedBanner.classList.remove('hidden');
  1635. mqttDisconnectedBanner.classList.add('hidden');
  1636. } else {
  1637. mqttConnectedBanner.classList.add('hidden');
  1638. mqttDisconnectedBanner.classList.remove('hidden');
  1639. }
  1640. }
  1641. }
  1642. // Function to check if config has changed
  1643. function checkConfigChanged() {
  1644. if (!originalConfig) return false;
  1645. const currentConfig = {
  1646. enabled: mqttEnableToggle.checked,
  1647. broker: mqttBrokerInput.value,
  1648. port: parseInt(mqttPortInput.value) || 1883,
  1649. username: mqttUsernameInput.value,
  1650. password: mqttPasswordInput.value,
  1651. device_name: mqttDeviceNameInput.value,
  1652. device_id: mqttDeviceIdInput.value,
  1653. client_id: mqttClientIdInput.value,
  1654. discovery_prefix: mqttDiscoveryPrefixInput.value
  1655. };
  1656. return JSON.stringify(currentConfig) !== JSON.stringify(originalConfig);
  1657. }
  1658. // Function to show/hide restart notice
  1659. function updateRestartNotice() {
  1660. configChanged = checkConfigChanged();
  1661. if (mqttRestartNotice) {
  1662. mqttRestartNotice.classList.toggle('hidden', !configChanged);
  1663. }
  1664. }
  1665. // Load current MQTT configuration
  1666. try {
  1667. const response = await fetch('/api/mqtt-config');
  1668. const data = await response.json();
  1669. mqttEnableToggle.checked = data.enabled || false;
  1670. mqttBrokerInput.value = data.broker || '';
  1671. mqttPortInput.value = data.port || 1883;
  1672. mqttUsernameInput.value = data.username || '';
  1673. // Note: Password is not returned from API for security
  1674. mqttDeviceNameInput.value = data.device_name || 'Dune Weaver';
  1675. mqttDeviceIdInput.value = data.device_id || 'dune_weaver';
  1676. mqttClientIdInput.value = data.client_id || 'dune_weaver';
  1677. mqttDiscoveryPrefixInput.value = data.discovery_prefix || 'homeassistant';
  1678. // Store original config for change detection
  1679. originalConfig = {
  1680. enabled: data.enabled || false,
  1681. broker: data.broker || '',
  1682. port: data.port || 1883,
  1683. username: data.username || '',
  1684. password: '', // We don't have the original password
  1685. device_name: data.device_name || 'Dune Weaver',
  1686. device_id: data.device_id || 'dune_weaver',
  1687. client_id: data.client_id || 'dune_weaver',
  1688. discovery_prefix: data.discovery_prefix || 'homeassistant'
  1689. };
  1690. updateMqttSettingsVisibility();
  1691. // Update connection status if MQTT is enabled
  1692. if (data.enabled) {
  1693. updateConnectionStatus(data.connected || false);
  1694. }
  1695. logMessage(`Loaded MQTT config: enabled=${data.enabled}, broker=${data.broker}`, LOG_TYPE.INFO);
  1696. } catch (error) {
  1697. logMessage(`Error loading MQTT configuration: ${error.message}`, LOG_TYPE.ERROR);
  1698. // Initialize with defaults if load fails
  1699. mqttEnableToggle.checked = false;
  1700. updateMqttSettingsVisibility();
  1701. }
  1702. // Function to save MQTT configuration
  1703. async function saveMqttConfig() {
  1704. // Validate required fields if MQTT is enabled
  1705. if (mqttEnableToggle.checked && !mqttBrokerInput.value.trim()) {
  1706. showStatusMessage('MQTT broker address is required when MQTT is enabled', 'error');
  1707. mqttBrokerInput.focus();
  1708. return;
  1709. }
  1710. // Update button UI to show loading state
  1711. const originalButtonHTML = saveMqttButton.innerHTML;
  1712. saveMqttButton.disabled = true;
  1713. saveMqttButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1714. try {
  1715. const requestBody = {
  1716. enabled: mqttEnableToggle.checked,
  1717. broker: mqttBrokerInput.value.trim(),
  1718. port: parseInt(mqttPortInput.value) || 1883,
  1719. username: mqttUsernameInput.value.trim() || null,
  1720. device_name: mqttDeviceNameInput.value.trim() || 'Dune Weaver',
  1721. device_id: mqttDeviceIdInput.value.trim() || 'dune_weaver',
  1722. client_id: mqttClientIdInput.value.trim() || 'dune_weaver',
  1723. discovery_prefix: mqttDiscoveryPrefixInput.value.trim() || 'homeassistant'
  1724. };
  1725. // Only include password if it was changed (not empty)
  1726. if (mqttPasswordInput.value) {
  1727. requestBody.password = mqttPasswordInput.value;
  1728. }
  1729. const response = await fetch('/api/mqtt-config', {
  1730. method: 'POST',
  1731. headers: { 'Content-Type': 'application/json' },
  1732. body: JSON.stringify(requestBody)
  1733. });
  1734. if (!response.ok) {
  1735. const errorData = await response.json();
  1736. throw new Error(errorData.detail || 'Failed to save MQTT configuration');
  1737. }
  1738. const data = await response.json();
  1739. // Update original config for change detection
  1740. originalConfig = {
  1741. enabled: requestBody.enabled,
  1742. broker: requestBody.broker,
  1743. port: requestBody.port,
  1744. username: requestBody.username || '',
  1745. password: '', // Reset password tracking
  1746. device_name: requestBody.device_name,
  1747. device_id: requestBody.device_id,
  1748. client_id: requestBody.client_id,
  1749. discovery_prefix: requestBody.discovery_prefix
  1750. };
  1751. // Clear password field after save
  1752. mqttPasswordInput.value = '';
  1753. // Show success state temporarily
  1754. saveMqttButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1755. showStatusMessage('MQTT configuration saved successfully. Restart the application to apply changes.', 'success');
  1756. // Show restart notice
  1757. if (mqttRestartNotice) {
  1758. mqttRestartNotice.classList.remove('hidden');
  1759. }
  1760. // Restore button after 2 seconds
  1761. setTimeout(() => {
  1762. saveMqttButton.innerHTML = originalButtonHTML;
  1763. saveMqttButton.disabled = false;
  1764. }, 2000);
  1765. } catch (error) {
  1766. logMessage(`Error saving MQTT configuration: ${error.message}`, LOG_TYPE.ERROR);
  1767. showStatusMessage(`Failed to save MQTT configuration: ${error.message}`, 'error');
  1768. // Restore button immediately on error
  1769. saveMqttButton.innerHTML = originalButtonHTML;
  1770. saveMqttButton.disabled = false;
  1771. }
  1772. }
  1773. // Function to test MQTT connection
  1774. async function testMqttConnection() {
  1775. // Validate broker address
  1776. if (!mqttBrokerInput.value.trim()) {
  1777. showStatusMessage('Please enter a broker address to test', 'error');
  1778. mqttBrokerInput.focus();
  1779. return;
  1780. }
  1781. // Update button UI to show loading state
  1782. const originalButtonHTML = testMqttButton.innerHTML;
  1783. testMqttButton.disabled = true;
  1784. testMqttButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Testing...</span>';
  1785. // Clear previous result
  1786. if (mqttTestResult) {
  1787. mqttTestResult.innerHTML = '';
  1788. }
  1789. try {
  1790. const requestBody = {
  1791. broker: mqttBrokerInput.value.trim(),
  1792. port: parseInt(mqttPortInput.value) || 1883,
  1793. username: mqttUsernameInput.value.trim() || null,
  1794. password: mqttPasswordInput.value || null
  1795. };
  1796. const response = await fetch('/api/mqtt-test', {
  1797. method: 'POST',
  1798. headers: { 'Content-Type': 'application/json' },
  1799. body: JSON.stringify(requestBody)
  1800. });
  1801. const data = await response.json();
  1802. if (data.success) {
  1803. if (mqttTestResult) {
  1804. mqttTestResult.innerHTML = '<span class="material-icons text-green-600 mr-1">check_circle</span><span class="text-green-600">Connection successful!</span>';
  1805. }
  1806. showStatusMessage('MQTT connection test successful', 'success');
  1807. } else {
  1808. if (mqttTestResult) {
  1809. mqttTestResult.innerHTML = `<span class="material-icons text-red-600 mr-1">error</span><span class="text-red-600">${data.error || 'Connection failed'}</span>`;
  1810. }
  1811. showStatusMessage(`MQTT test failed: ${data.error || 'Connection failed'}`, 'error');
  1812. }
  1813. } catch (error) {
  1814. logMessage(`Error testing MQTT connection: ${error.message}`, LOG_TYPE.ERROR);
  1815. if (mqttTestResult) {
  1816. mqttTestResult.innerHTML = `<span class="material-icons text-red-600 mr-1">error</span><span class="text-red-600">Test failed: ${error.message}</span>`;
  1817. }
  1818. showStatusMessage(`MQTT test failed: ${error.message}`, 'error');
  1819. } finally {
  1820. // Restore button
  1821. testMqttButton.innerHTML = originalButtonHTML;
  1822. testMqttButton.disabled = false;
  1823. }
  1824. }
  1825. // Event listeners
  1826. mqttEnableToggle.addEventListener('change', () => {
  1827. updateMqttSettingsVisibility();
  1828. updateRestartNotice();
  1829. });
  1830. // Track changes to show restart notice
  1831. [mqttBrokerInput, mqttPortInput, mqttUsernameInput, mqttPasswordInput,
  1832. mqttDeviceNameInput, mqttDeviceIdInput, mqttClientIdInput, mqttDiscoveryPrefixInput].forEach(input => {
  1833. if (input) {
  1834. input.addEventListener('input', updateRestartNotice);
  1835. }
  1836. });
  1837. testMqttButton.addEventListener('click', testMqttConnection);
  1838. saveMqttButton.addEventListener('click', saveMqttConfig);
  1839. }
  1840. // Initialize MQTT config when DOM is ready
  1841. document.addEventListener('DOMContentLoaded', function() {
  1842. initializeMqttConfig();
  1843. });