settings.js 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658
  1. // ============================================================================
  2. // Collapsible Section Toggle
  3. // ============================================================================
  4. function toggleSection(headerElement) {
  5. const contentElement = headerElement.nextElementSibling;
  6. if (headerElement.classList.contains('collapsed')) {
  7. // Expand
  8. headerElement.classList.remove('collapsed');
  9. contentElement.classList.remove('collapsed');
  10. } else {
  11. // Collapse
  12. headerElement.classList.add('collapsed');
  13. contentElement.classList.add('collapsed');
  14. }
  15. }
  16. // ============================================================================
  17. // Constants and Utilities
  18. // ============================================================================
  19. // Constants for log message types
  20. const LOG_TYPE = {
  21. SUCCESS: 'success',
  22. WARNING: 'warning',
  23. ERROR: 'error',
  24. INFO: 'info',
  25. DEBUG: 'debug'
  26. };
  27. // Helper function to convert provider name to camelCase for ID lookup
  28. // e.g., "dw_leds" -> "DwLeds", "wled" -> "Wled", "none" -> "None"
  29. function providerToCamelCase(provider) {
  30. return provider.split('_').map(word =>
  31. word.charAt(0).toUpperCase() + word.slice(1)
  32. ).join('');
  33. }
  34. // Constants for cache
  35. const CACHE_KEYS = {
  36. CONNECTION_STATUS: 'connection_status',
  37. LAST_UPDATE: 'last_status_update'
  38. };
  39. const CACHE_DURATION = 5000; // 5 seconds cache duration
  40. // Function to log messages
  41. function logMessage(message, type = LOG_TYPE.DEBUG) {
  42. console.log(`[${type}] ${message}`);
  43. }
  44. // Function to get cached connection status
  45. function getCachedConnectionStatus() {
  46. const cachedData = localStorage.getItem(CACHE_KEYS.CONNECTION_STATUS);
  47. const lastUpdate = localStorage.getItem(CACHE_KEYS.LAST_UPDATE);
  48. if (cachedData && lastUpdate) {
  49. const now = Date.now();
  50. const cacheAge = now - parseInt(lastUpdate);
  51. if (cacheAge < CACHE_DURATION) {
  52. return JSON.parse(cachedData);
  53. }
  54. }
  55. return null;
  56. }
  57. // Function to set cached connection status
  58. function setCachedConnectionStatus(data) {
  59. localStorage.setItem(CACHE_KEYS.CONNECTION_STATUS, JSON.stringify(data));
  60. localStorage.setItem(CACHE_KEYS.LAST_UPDATE, Date.now().toString());
  61. }
  62. // Function to update serial connection status
  63. async function updateSerialStatus(forceUpdate = false) {
  64. try {
  65. // Check cache first unless force update is requested
  66. if (!forceUpdate) {
  67. const cachedData = getCachedConnectionStatus();
  68. if (cachedData) {
  69. updateConnectionUI(cachedData);
  70. return;
  71. }
  72. }
  73. const response = await fetch('/serial_status');
  74. if (response.ok) {
  75. const data = await response.json();
  76. setCachedConnectionStatus(data);
  77. updateConnectionUI(data);
  78. }
  79. } catch (error) {
  80. logMessage(`Error checking serial status: ${error.message}`, LOG_TYPE.ERROR);
  81. }
  82. }
  83. // Function to update UI based on connection status
  84. function updateConnectionUI(data) {
  85. const statusElement = document.getElementById('serialStatus');
  86. const iconElement = document.querySelector('.material-icons.text-3xl');
  87. const disconnectButton = document.getElementById('disconnectButton');
  88. const portSelectionDiv = document.getElementById('portSelectionDiv');
  89. if (statusElement && iconElement) {
  90. if (data.connected) {
  91. statusElement.textContent = `Connected to ${data.port || 'unknown port'}`;
  92. statusElement.className = 'text-green-500 text-sm font-medium leading-normal';
  93. iconElement.textContent = 'usb';
  94. if (disconnectButton) {
  95. disconnectButton.hidden = false;
  96. }
  97. if (portSelectionDiv) {
  98. portSelectionDiv.hidden = true;
  99. }
  100. } else {
  101. statusElement.textContent = 'Disconnected';
  102. statusElement.className = 'text-red-500 text-sm font-medium leading-normal';
  103. iconElement.textContent = 'usb_off';
  104. if (disconnectButton) {
  105. disconnectButton.hidden = true;
  106. }
  107. if (portSelectionDiv) {
  108. portSelectionDiv.hidden = false;
  109. }
  110. }
  111. }
  112. }
  113. // Function to update available serial ports
  114. async function updateSerialPorts() {
  115. try {
  116. const response = await fetch('/list_serial_ports');
  117. if (response.ok) {
  118. const ports = await response.json();
  119. const portsElement = document.getElementById('availablePorts');
  120. const portSelect = document.getElementById('portSelect');
  121. const preferredPortSelect = document.getElementById('preferredPortSelect');
  122. if (portsElement) {
  123. portsElement.textContent = ports.length > 0 ? ports.join(', ') : 'No ports available';
  124. }
  125. if (portSelect) {
  126. // Clear existing options except the first one
  127. while (portSelect.options.length > 1) {
  128. portSelect.remove(1);
  129. }
  130. // Add new options
  131. ports.forEach(port => {
  132. const option = document.createElement('option');
  133. option.value = port;
  134. option.textContent = port;
  135. portSelect.appendChild(option);
  136. });
  137. // If there's exactly one port available, select and connect to it
  138. if (ports.length === 1) {
  139. portSelect.value = ports[0];
  140. // Trigger connect button click
  141. const connectButton = document.getElementById('connectButton');
  142. if (connectButton) {
  143. connectButton.click();
  144. }
  145. }
  146. }
  147. // Also update the preferred port select dropdown
  148. if (preferredPortSelect) {
  149. // Store current selection
  150. const currentPreferred = preferredPortSelect.value;
  151. // Clear existing options except the first one (no preference)
  152. while (preferredPortSelect.options.length > 1) {
  153. preferredPortSelect.remove(1);
  154. }
  155. // Add all available ports
  156. ports.forEach(port => {
  157. const option = document.createElement('option');
  158. option.value = port;
  159. option.textContent = port;
  160. preferredPortSelect.appendChild(option);
  161. });
  162. // Restore selection if it's still available
  163. if (currentPreferred && ports.includes(currentPreferred)) {
  164. preferredPortSelect.value = currentPreferred;
  165. }
  166. }
  167. }
  168. } catch (error) {
  169. logMessage(`Error fetching serial ports: ${error.message}`, LOG_TYPE.ERROR);
  170. }
  171. }
  172. // Function to load and display preferred port setting
  173. async function loadPreferredPort() {
  174. try {
  175. const response = await fetch('/api/preferred-port');
  176. if (response.ok) {
  177. const data = await response.json();
  178. const preferredPortSelect = document.getElementById('preferredPortSelect');
  179. const currentPreferredPort = document.getElementById('currentPreferredPort');
  180. const preferredPortDisplay = document.getElementById('preferredPortDisplay');
  181. if (preferredPortSelect && data.preferred_port) {
  182. // Check if the preferred port is in the options
  183. const optionExists = Array.from(preferredPortSelect.options).some(
  184. opt => opt.value === data.preferred_port
  185. );
  186. if (optionExists) {
  187. preferredPortSelect.value = data.preferred_port;
  188. } else {
  189. // Add the preferred port as an option (it might not be currently available)
  190. const option = document.createElement('option');
  191. option.value = data.preferred_port;
  192. option.textContent = `${data.preferred_port} (not currently available)`;
  193. preferredPortSelect.appendChild(option);
  194. preferredPortSelect.value = data.preferred_port;
  195. }
  196. }
  197. // Show current preferred port indicator
  198. if (currentPreferredPort && preferredPortDisplay && data.preferred_port) {
  199. preferredPortDisplay.textContent = `Currently set to: ${data.preferred_port}`;
  200. currentPreferredPort.classList.remove('hidden');
  201. } else if (currentPreferredPort) {
  202. currentPreferredPort.classList.add('hidden');
  203. }
  204. }
  205. } catch (error) {
  206. logMessage(`Error loading preferred port: ${error.message}`, LOG_TYPE.ERROR);
  207. }
  208. }
  209. // Function to save preferred port setting
  210. async function savePreferredPort() {
  211. const preferredPortSelect = document.getElementById('preferredPortSelect');
  212. if (!preferredPortSelect) return;
  213. const preferredPort = preferredPortSelect.value || null;
  214. try {
  215. const response = await fetch('/api/settings', {
  216. method: 'PATCH',
  217. headers: { 'Content-Type': 'application/json' },
  218. body: JSON.stringify({ connection: { preferred_port: preferredPort } })
  219. });
  220. if (response.ok) {
  221. await response.json();
  222. const currentPreferredPort = document.getElementById('currentPreferredPort');
  223. const preferredPortDisplay = document.getElementById('preferredPortDisplay');
  224. if (preferredPort) {
  225. showStatusMessage(`Preferred port set to: ${preferredPort}`, 'success');
  226. if (currentPreferredPort && preferredPortDisplay) {
  227. preferredPortDisplay.textContent = `Currently set to: ${preferredPort}`;
  228. currentPreferredPort.classList.remove('hidden');
  229. }
  230. } else {
  231. showStatusMessage('Preferred port cleared - will auto-detect on startup', 'success');
  232. if (currentPreferredPort) {
  233. currentPreferredPort.classList.add('hidden');
  234. }
  235. }
  236. } else {
  237. throw new Error('Failed to save preferred port');
  238. }
  239. } catch (error) {
  240. showStatusMessage(`Failed to save preferred port: ${error.message}`, 'error');
  241. }
  242. }
  243. function setWledButtonState(isSet) {
  244. const saveWledConfig = document.getElementById('saveWledConfig');
  245. if (!saveWledConfig) return;
  246. if (isSet) {
  247. 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';
  248. saveWledConfig.innerHTML = '<span class="material-icons text-lg">close</span><span class="truncate">Clear WLED IP</span>';
  249. } else {
  250. 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';
  251. saveWledConfig.innerHTML = '<span class="material-icons text-lg">save</span><span class="truncate">Save Configuration</span>';
  252. }
  253. }
  254. // Handle LED provider selection and show/hide appropriate config sections
  255. function updateLedProviderUI() {
  256. const provider = document.querySelector('input[name="ledProvider"]:checked')?.value || 'none';
  257. const wledConfig = document.getElementById('wledConfig');
  258. const dwLedsConfig = document.getElementById('dwLedsConfig');
  259. if (wledConfig && dwLedsConfig) {
  260. if (provider === 'wled') {
  261. wledConfig.classList.remove('hidden');
  262. dwLedsConfig.classList.add('hidden');
  263. } else if (provider === 'dw_leds') {
  264. wledConfig.classList.add('hidden');
  265. dwLedsConfig.classList.remove('hidden');
  266. } else {
  267. wledConfig.classList.add('hidden');
  268. dwLedsConfig.classList.add('hidden');
  269. }
  270. }
  271. }
  272. // Load LED configuration from server
  273. async function loadLedConfig() {
  274. try {
  275. const response = await fetch('/get_led_config');
  276. if (response.ok) {
  277. const data = await response.json();
  278. // Set provider radio button
  279. const providerRadio = document.getElementById(`ledProvider${providerToCamelCase(data.provider)}`);
  280. if (providerRadio) {
  281. providerRadio.checked = true;
  282. } else {
  283. document.getElementById('ledProviderNone').checked = true;
  284. }
  285. // Set WLED IP if configured
  286. if (data.wled_ip) {
  287. const wledIpInput = document.getElementById('wledIpInput');
  288. if (wledIpInput) {
  289. wledIpInput.value = data.wled_ip;
  290. }
  291. }
  292. // Set DW LED configuration if configured
  293. if (data.dw_led_num_leds) {
  294. const numLedsInput = document.getElementById('dwLedNumLeds');
  295. if (numLedsInput) {
  296. numLedsInput.value = data.dw_led_num_leds;
  297. }
  298. }
  299. if (data.dw_led_gpio_pin) {
  300. const gpioPinInput = document.getElementById('dwLedGpioPin');
  301. if (gpioPinInput) {
  302. gpioPinInput.value = data.dw_led_gpio_pin;
  303. }
  304. }
  305. if (data.dw_led_pixel_order) {
  306. const pixelOrderInput = document.getElementById('dwLedPixelOrder');
  307. if (pixelOrderInput) {
  308. pixelOrderInput.value = data.dw_led_pixel_order;
  309. }
  310. }
  311. // Update UI to show correct config section
  312. updateLedProviderUI();
  313. }
  314. } catch (error) {
  315. logMessage(`Error loading LED config: ${error.message}`, LOG_TYPE.ERROR);
  316. }
  317. }
  318. // Initialize settings page
  319. document.addEventListener('DOMContentLoaded', async () => {
  320. // Initialize UI with default disconnected state
  321. updateConnectionUI({ connected: false });
  322. // Handle scroll to section if hash is present in URL
  323. if (window.location.hash) {
  324. setTimeout(() => {
  325. const targetSection = document.querySelector(window.location.hash);
  326. if (targetSection) {
  327. targetSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
  328. // Add a subtle highlight animation
  329. targetSection.style.transition = 'background-color 0.5s ease';
  330. const originalBg = targetSection.style.backgroundColor;
  331. targetSection.style.backgroundColor = 'rgba(14, 165, 233, 0.1)';
  332. setTimeout(() => {
  333. targetSection.style.backgroundColor = originalBg;
  334. }, 2000);
  335. }
  336. }, 300); // Delay to ensure page is fully loaded
  337. }
  338. // Load all data asynchronously using unified settings endpoint
  339. Promise.all([
  340. // Unified settings endpoint (replaces multiple individual fetches)
  341. fetch('/api/settings').then(response => response.json()).catch(() => ({})),
  342. // Non-settings operational endpoints (kept separate)
  343. fetch('/serial_status').then(response => response.json()).catch(() => ({ connected: false })),
  344. fetch('/api/version').then(response => response.json()).catch(() => ({ current: '1.0.0', latest: '1.0.0', update_available: false })),
  345. fetch('/list_serial_ports').then(response => response.json()).catch(() => []),
  346. getCachedPatternFiles().catch(() => [])
  347. ]).then(([settings, statusData, updateData, ports, patterns]) => {
  348. // Map unified settings to legacy variable names for backward compatibility with existing UI code
  349. const ledConfigData = {
  350. provider: settings.led?.provider || 'none',
  351. wled_ip: settings.led?.wled_ip || null,
  352. dw_led_num_leds: settings.led?.dw_led?.num_leds,
  353. dw_led_gpio_pin: settings.led?.dw_led?.gpio_pin,
  354. dw_led_pixel_order: settings.led?.dw_led?.pixel_order
  355. };
  356. const clearPatterns = {
  357. custom_clear_from_in: settings.patterns?.custom_clear_from_in,
  358. custom_clear_from_out: settings.patterns?.custom_clear_from_out
  359. };
  360. const clearSpeedData = {
  361. clear_pattern_speed: settings.patterns?.clear_pattern_speed,
  362. effective_speed: settings.patterns?.clear_pattern_speed // Will be handled by UI
  363. };
  364. const appNameData = { app_name: settings.app?.name || 'Dune Weaver' };
  365. const scheduledPauseData = settings.scheduled_pause || { enabled: false, time_slots: [] };
  366. const preferredPortData = { preferred_port: settings.connection?.preferred_port };
  367. // Store full settings for other initialization functions
  368. window.unifiedSettings = settings;
  369. // Update connection status
  370. setCachedConnectionStatus(statusData);
  371. updateConnectionUI(statusData);
  372. // Update LED configuration
  373. const providerRadio = document.getElementById(`ledProvider${providerToCamelCase(ledConfigData.provider)}`);
  374. if (providerRadio) {
  375. providerRadio.checked = true;
  376. } else {
  377. document.getElementById('ledProviderNone').checked = true;
  378. }
  379. if (ledConfigData.wled_ip) {
  380. const wledIpInput = document.getElementById('wledIpInput');
  381. if (wledIpInput) wledIpInput.value = ledConfigData.wled_ip;
  382. }
  383. // Load DW LED settings
  384. if (ledConfigData.dw_led_num_leds) {
  385. const numLedsInput = document.getElementById('dwLedNumLeds');
  386. if (numLedsInput) numLedsInput.value = ledConfigData.dw_led_num_leds;
  387. }
  388. if (ledConfigData.dw_led_gpio_pin) {
  389. const gpioPinInput = document.getElementById('dwLedGpioPin');
  390. if (gpioPinInput) gpioPinInput.value = ledConfigData.dw_led_gpio_pin;
  391. }
  392. if (ledConfigData.dw_led_pixel_order) {
  393. const pixelOrderInput = document.getElementById('dwLedPixelOrder');
  394. if (pixelOrderInput) pixelOrderInput.value = ledConfigData.dw_led_pixel_order;
  395. }
  396. updateLedProviderUI()
  397. // Update version display
  398. const currentVersionText = document.getElementById('currentVersionText');
  399. const latestVersionText = document.getElementById('latestVersionText');
  400. const updateButton = document.getElementById('updateSoftware');
  401. const updateIcon = document.getElementById('updateIcon');
  402. const updateText = document.getElementById('updateText');
  403. if (currentVersionText) {
  404. currentVersionText.textContent = updateData.current;
  405. }
  406. if (latestVersionText) {
  407. if (updateData.error) {
  408. latestVersionText.textContent = 'Error checking updates';
  409. latestVersionText.className = 'text-red-500 text-sm font-normal leading-normal';
  410. } else {
  411. latestVersionText.textContent = updateData.latest;
  412. latestVersionText.className = 'text-slate-500 text-sm font-normal leading-normal';
  413. }
  414. }
  415. // Update button state
  416. if (updateButton && updateIcon && updateText) {
  417. if (updateData.update_available) {
  418. updateButton.disabled = false;
  419. 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';
  420. updateIcon.textContent = 'download';
  421. updateText.textContent = 'Update';
  422. } else {
  423. updateButton.disabled = true;
  424. 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';
  425. updateIcon.textContent = 'check';
  426. updateText.textContent = 'Up to date';
  427. }
  428. }
  429. // Update port selection
  430. const portSelect = document.getElementById('portSelect');
  431. if (portSelect) {
  432. // Clear existing options except the first one
  433. while (portSelect.options.length > 1) {
  434. portSelect.remove(1);
  435. }
  436. // Add new options
  437. ports.forEach(port => {
  438. const option = document.createElement('option');
  439. option.value = port;
  440. option.textContent = port;
  441. portSelect.appendChild(option);
  442. });
  443. // If there's exactly one port available, select it
  444. if (ports.length === 1) {
  445. portSelect.value = ports[0];
  446. }
  447. }
  448. // Update preferred port selection
  449. const preferredPortSelect = document.getElementById('preferredPortSelect');
  450. const currentPreferredPort = document.getElementById('currentPreferredPort');
  451. const preferredPortDisplay = document.getElementById('preferredPortDisplay');
  452. if (preferredPortSelect) {
  453. // Clear existing options except the first one (no preference)
  454. while (preferredPortSelect.options.length > 1) {
  455. preferredPortSelect.remove(1);
  456. }
  457. // Add all available ports
  458. ports.forEach(port => {
  459. const option = document.createElement('option');
  460. option.value = port;
  461. option.textContent = port;
  462. preferredPortSelect.appendChild(option);
  463. });
  464. // Set the current preferred port value
  465. if (preferredPortData && preferredPortData.preferred_port) {
  466. // Check if the preferred port is in the available ports
  467. const isAvailable = ports.includes(preferredPortData.preferred_port);
  468. if (isAvailable) {
  469. preferredPortSelect.value = preferredPortData.preferred_port;
  470. } else {
  471. // Add the preferred port as an option (it might not be currently available)
  472. const option = document.createElement('option');
  473. option.value = preferredPortData.preferred_port;
  474. option.textContent = `${preferredPortData.preferred_port} (not currently available)`;
  475. preferredPortSelect.appendChild(option);
  476. preferredPortSelect.value = preferredPortData.preferred_port;
  477. }
  478. // Show the current preferred port indicator
  479. if (currentPreferredPort && preferredPortDisplay) {
  480. preferredPortDisplay.textContent = `Currently set to: ${preferredPortData.preferred_port}`;
  481. currentPreferredPort.classList.remove('hidden');
  482. }
  483. }
  484. }
  485. // Initialize autocomplete for clear patterns
  486. const clearFromInInput = document.getElementById('customClearFromInInput');
  487. const clearFromOutInput = document.getElementById('customClearFromOutInput');
  488. if (clearFromInInput && clearFromOutInput && patterns && Array.isArray(patterns)) {
  489. // Store patterns globally for autocomplete
  490. window.availablePatterns = patterns;
  491. // Set current values if they exist
  492. if (clearPatterns && clearPatterns.custom_clear_from_in) {
  493. clearFromInInput.value = clearPatterns.custom_clear_from_in;
  494. }
  495. if (clearPatterns && clearPatterns.custom_clear_from_out) {
  496. clearFromOutInput.value = clearPatterns.custom_clear_from_out;
  497. }
  498. // Initialize autocomplete for both inputs
  499. initializeAutocomplete('customClearFromInInput', 'clearFromInSuggestions', 'clearFromInClear', patterns);
  500. initializeAutocomplete('customClearFromOutInput', 'clearFromOutSuggestions', 'clearFromOutClear', patterns);
  501. console.log('Autocomplete initialized with', patterns.length, 'patterns');
  502. }
  503. // Set clear pattern speed
  504. const clearPatternSpeedInput = document.getElementById('clearPatternSpeedInput');
  505. const effectiveClearSpeed = document.getElementById('effectiveClearSpeed');
  506. if (clearPatternSpeedInput && clearSpeedData) {
  507. // Only set value if clear_pattern_speed is not null
  508. if (clearSpeedData.clear_pattern_speed !== null && clearSpeedData.clear_pattern_speed !== undefined) {
  509. clearPatternSpeedInput.value = clearSpeedData.clear_pattern_speed;
  510. if (effectiveClearSpeed) {
  511. effectiveClearSpeed.textContent = `Current: ${clearSpeedData.clear_pattern_speed} steps/min`;
  512. }
  513. } else {
  514. // Leave empty to show placeholder for default
  515. clearPatternSpeedInput.value = '';
  516. if (effectiveClearSpeed && clearSpeedData.effective_speed) {
  517. effectiveClearSpeed.textContent = `Using default pattern speed: ${clearSpeedData.effective_speed} steps/min`;
  518. }
  519. }
  520. }
  521. // Update app name
  522. const appNameInput = document.getElementById('appNameInput');
  523. if (appNameInput && appNameData.app_name) {
  524. appNameInput.value = appNameData.app_name;
  525. }
  526. // Store Still Sands data for later initialization
  527. window.initialStillSandsData = scheduledPauseData;
  528. }).catch(error => {
  529. logMessage(`Error initializing settings page: ${error.message}`, LOG_TYPE.ERROR);
  530. });
  531. // Set up event listeners
  532. setupEventListeners();
  533. });
  534. // Setup event listeners
  535. function setupEventListeners() {
  536. // Save App Name
  537. const saveAppNameButton = document.getElementById('saveAppName');
  538. const appNameInput = document.getElementById('appNameInput');
  539. if (saveAppNameButton && appNameInput) {
  540. saveAppNameButton.addEventListener('click', async () => {
  541. const appName = appNameInput.value.trim() || 'Dune Weaver';
  542. try {
  543. const response = await fetch('/api/settings', {
  544. method: 'PATCH',
  545. headers: { 'Content-Type': 'application/json' },
  546. body: JSON.stringify({ app: { name: appName } })
  547. });
  548. if (response.ok) {
  549. await response.json();
  550. showStatusMessage('Application name updated successfully. Refresh the page to see changes.', 'success');
  551. // Update the page title and header immediately
  552. document.title = `Settings - ${appName}`;
  553. const headerTitle = document.querySelector('h1.text-gray-800');
  554. if (headerTitle) {
  555. // Update just the text content, preserving the connection status dot
  556. const textNode = headerTitle.childNodes[0];
  557. if (textNode && textNode.nodeType === Node.TEXT_NODE) {
  558. textNode.textContent = data.app_name;
  559. }
  560. }
  561. } else {
  562. throw new Error('Failed to save application name');
  563. }
  564. } catch (error) {
  565. showStatusMessage(`Failed to save application name: ${error.message}`, 'error');
  566. }
  567. });
  568. // Handle Enter key in app name input
  569. appNameInput.addEventListener('keypress', (e) => {
  570. if (e.key === 'Enter') {
  571. saveAppNameButton.click();
  572. }
  573. });
  574. }
  575. // LED provider selection change handlers
  576. const ledProviderRadios = document.querySelectorAll('input[name="ledProvider"]');
  577. ledProviderRadios.forEach(radio => {
  578. radio.addEventListener('change', updateLedProviderUI);
  579. });
  580. // Save LED configuration
  581. const saveLedConfig = document.getElementById('saveLedConfig');
  582. if (saveLedConfig) {
  583. saveLedConfig.addEventListener('click', async () => {
  584. const provider = document.querySelector('input[name="ledProvider"]:checked')?.value || 'none';
  585. let requestBody = { provider };
  586. if (provider === 'wled') {
  587. const wledIp = document.getElementById('wledIpInput')?.value;
  588. if (!wledIp) {
  589. showStatusMessage('Please enter a WLED IP address', 'error');
  590. return;
  591. }
  592. requestBody.ip_address = wledIp;
  593. } else if (provider === 'dw_leds') {
  594. const numLeds = parseInt(document.getElementById('dwLedNumLeds')?.value) || 60;
  595. const gpioPin = parseInt(document.getElementById('dwLedGpioPin')?.value) || 12;
  596. const pixelOrder = document.getElementById('dwLedPixelOrder')?.value || 'GRB';
  597. requestBody.num_leds = numLeds;
  598. requestBody.gpio_pin = gpioPin;
  599. requestBody.pixel_order = pixelOrder;
  600. }
  601. try {
  602. const response = await fetch('/set_led_config', {
  603. method: 'POST',
  604. headers: { 'Content-Type': 'application/json' },
  605. body: JSON.stringify(requestBody)
  606. });
  607. if (response.ok) {
  608. const data = await response.json();
  609. if (provider === 'wled' && data.wled_ip) {
  610. localStorage.setItem('wled_ip', data.wled_ip);
  611. showStatusMessage('WLED configured successfully', 'success');
  612. } else if (provider === 'dw_leds') {
  613. // Check if there's a warning (hardware not available but settings saved)
  614. if (data.warning) {
  615. showStatusMessage(
  616. `Settings saved for testing. Hardware issue: ${data.warning}`,
  617. 'warning'
  618. );
  619. } else {
  620. showStatusMessage(
  621. `DW LEDs configured: ${data.dw_led_num_leds} LEDs on GPIO${data.dw_led_gpio_pin}`,
  622. 'success'
  623. );
  624. }
  625. } else if (provider === 'none') {
  626. localStorage.removeItem('wled_ip');
  627. showStatusMessage('LED controller disabled', 'success');
  628. }
  629. } else {
  630. // Extract error detail from response
  631. const errorData = await response.json().catch(() => ({}));
  632. const errorMessage = errorData.detail || 'Failed to save LED configuration';
  633. showStatusMessage(errorMessage, 'error');
  634. }
  635. } catch (error) {
  636. showStatusMessage(`Failed to save LED configuration: ${error.message}`, 'error');
  637. }
  638. });
  639. }
  640. // Update software
  641. const updateSoftware = document.getElementById('updateSoftware');
  642. if (updateSoftware) {
  643. updateSoftware.addEventListener('click', async () => {
  644. if (updateSoftware.disabled) {
  645. return;
  646. }
  647. try {
  648. const response = await fetch('/api/update', {
  649. method: 'POST'
  650. });
  651. const data = await response.json();
  652. if (data.success) {
  653. showStatusMessage('Software update started successfully', 'success');
  654. } else if (data.manual_update_url) {
  655. // Show modal with manual update instructions, but use wiki link
  656. const wikiData = {
  657. ...data,
  658. manual_update_url: 'https://github.com/tuanchris/dune-weaver/wiki/Updating-software'
  659. };
  660. showUpdateInstructionsModal(wikiData);
  661. } else {
  662. showStatusMessage(data.message || 'No updates available', 'info');
  663. }
  664. } catch (error) {
  665. logMessage(`Error updating software: ${error.message}`, LOG_TYPE.ERROR);
  666. showStatusMessage('Failed to check for updates', 'error');
  667. }
  668. });
  669. }
  670. // Connect button
  671. const connectButton = document.getElementById('connectButton');
  672. if (connectButton) {
  673. connectButton.addEventListener('click', async () => {
  674. const portSelect = document.getElementById('portSelect');
  675. if (!portSelect || !portSelect.value) {
  676. logMessage('Please select a port first', LOG_TYPE.WARNING);
  677. return;
  678. }
  679. try {
  680. const response = await fetch('/connect', {
  681. method: 'POST',
  682. headers: { 'Content-Type': 'application/json' },
  683. body: JSON.stringify({ port: portSelect.value })
  684. });
  685. if (response.ok) {
  686. logMessage('Connected successfully', LOG_TYPE.SUCCESS);
  687. await updateSerialStatus(true); // Force update after connecting
  688. } else {
  689. throw new Error('Failed to connect');
  690. }
  691. } catch (error) {
  692. logMessage(`Error connecting to device: ${error.message}`, LOG_TYPE.ERROR);
  693. }
  694. });
  695. }
  696. // Disconnect button
  697. const disconnectButton = document.getElementById('disconnectButton');
  698. if (disconnectButton) {
  699. disconnectButton.addEventListener('click', async () => {
  700. try {
  701. const response = await fetch('/disconnect', {
  702. method: 'POST'
  703. });
  704. if (response.ok) {
  705. logMessage('Device disconnected successfully', LOG_TYPE.SUCCESS);
  706. await updateSerialStatus(true); // Force update after disconnecting
  707. } else {
  708. throw new Error('Failed to disconnect device');
  709. }
  710. } catch (error) {
  711. logMessage(`Error disconnecting device: ${error.message}`, LOG_TYPE.ERROR);
  712. }
  713. });
  714. }
  715. // Save preferred port button
  716. const savePreferredPortButton = document.getElementById('savePreferredPort');
  717. if (savePreferredPortButton) {
  718. savePreferredPortButton.addEventListener('click', savePreferredPort);
  719. }
  720. // Save custom clear patterns button
  721. const saveClearPatterns = document.getElementById('saveClearPatterns');
  722. if (saveClearPatterns) {
  723. saveClearPatterns.addEventListener('click', async () => {
  724. const clearFromInInput = document.getElementById('customClearFromInInput');
  725. const clearFromOutInput = document.getElementById('customClearFromOutInput');
  726. if (!clearFromInInput || !clearFromOutInput) {
  727. return;
  728. }
  729. // Validate that the entered patterns exist (if not empty)
  730. const inValue = clearFromInInput.value.trim();
  731. const outValue = clearFromOutInput.value.trim();
  732. if (inValue && window.availablePatterns && !window.availablePatterns.includes(inValue)) {
  733. showStatusMessage(`Pattern not found: ${inValue}`, 'error');
  734. return;
  735. }
  736. if (outValue && window.availablePatterns && !window.availablePatterns.includes(outValue)) {
  737. showStatusMessage(`Pattern not found: ${outValue}`, 'error');
  738. return;
  739. }
  740. try {
  741. const response = await fetch('/api/settings', {
  742. method: 'PATCH',
  743. headers: { 'Content-Type': 'application/json' },
  744. body: JSON.stringify({
  745. patterns: {
  746. custom_clear_from_in: inValue || null,
  747. custom_clear_from_out: outValue || null
  748. }
  749. })
  750. });
  751. if (response.ok) {
  752. showStatusMessage('Clear patterns saved successfully', 'success');
  753. } else {
  754. const error = await response.json();
  755. throw new Error(error.detail || 'Failed to save clear patterns');
  756. }
  757. } catch (error) {
  758. showStatusMessage(`Failed to save clear patterns: ${error.message}`, 'error');
  759. }
  760. });
  761. }
  762. // Logo upload functionality
  763. const logoFileInput = document.getElementById('logoFileInput');
  764. const resetLogoBtn = document.getElementById('resetLogoBtn');
  765. const logoPreview = document.getElementById('logoPreview');
  766. const logoUploadStatus = document.getElementById('logoUploadStatus');
  767. if (logoFileInput) {
  768. logoFileInput.addEventListener('change', async (event) => {
  769. const file = event.target.files[0];
  770. if (!file) return;
  771. // Show uploading status
  772. if (logoUploadStatus) {
  773. logoUploadStatus.textContent = 'Uploading...';
  774. logoUploadStatus.className = 'text-xs text-slate-500';
  775. }
  776. const formData = new FormData();
  777. formData.append('file', file);
  778. try {
  779. const response = await fetch('/api/upload-logo', {
  780. method: 'POST',
  781. body: formData
  782. });
  783. if (response.ok) {
  784. const data = await response.json();
  785. // Update preview image with cache-busting query param
  786. if (logoPreview) {
  787. logoPreview.src = data.url + '?t=' + Date.now();
  788. }
  789. // Show reset button
  790. if (resetLogoBtn) {
  791. resetLogoBtn.classList.remove('hidden');
  792. }
  793. // Show success status
  794. if (logoUploadStatus) {
  795. logoUploadStatus.textContent = 'Logo uploaded successfully!';
  796. logoUploadStatus.className = 'text-xs text-green-600';
  797. setTimeout(() => {
  798. logoUploadStatus.textContent = '';
  799. }, 3000);
  800. }
  801. showStatusMessage('Logo uploaded successfully. Refresh the page to see all changes.', 'success');
  802. } else {
  803. const error = await response.json();
  804. throw new Error(error.detail || 'Failed to upload logo');
  805. }
  806. } catch (error) {
  807. if (logoUploadStatus) {
  808. logoUploadStatus.textContent = `Error: ${error.message}`;
  809. logoUploadStatus.className = 'text-xs text-red-600';
  810. }
  811. showStatusMessage(`Failed to upload logo: ${error.message}`, 'error');
  812. }
  813. // Reset file input so the same file can be re-selected
  814. logoFileInput.value = '';
  815. });
  816. }
  817. if (resetLogoBtn) {
  818. resetLogoBtn.addEventListener('click', async () => {
  819. try {
  820. const response = await fetch('/api/custom-logo', {
  821. method: 'DELETE'
  822. });
  823. if (response.ok) {
  824. // Reset preview to default logo
  825. if (logoPreview) {
  826. logoPreview.src = '/static/apple-touch-icon.png?t=' + Date.now();
  827. }
  828. // Hide reset button
  829. resetLogoBtn.classList.add('hidden');
  830. showStatusMessage('Logo reset to default. Refresh the page to see all changes.', 'success');
  831. } else {
  832. const error = await response.json();
  833. throw new Error(error.detail || 'Failed to reset logo');
  834. }
  835. } catch (error) {
  836. showStatusMessage(`Failed to reset logo: ${error.message}`, 'error');
  837. }
  838. });
  839. }
  840. // Save clear pattern speed button
  841. const saveClearSpeed = document.getElementById('saveClearSpeed');
  842. if (saveClearSpeed) {
  843. saveClearSpeed.addEventListener('click', async () => {
  844. const clearPatternSpeedInput = document.getElementById('clearPatternSpeedInput');
  845. if (!clearPatternSpeedInput) {
  846. return;
  847. }
  848. let speed;
  849. if (clearPatternSpeedInput.value === '' || clearPatternSpeedInput.value === null) {
  850. // Empty value means use default (None)
  851. speed = null;
  852. } else {
  853. speed = parseInt(clearPatternSpeedInput.value);
  854. // Validate speed only if it's not null
  855. if (isNaN(speed) || speed < 50 || speed > 2000) {
  856. showStatusMessage('Clear pattern speed must be between 50 and 2000, or leave empty for default', 'error');
  857. return;
  858. }
  859. }
  860. try {
  861. const response = await fetch('/api/settings', {
  862. method: 'PATCH',
  863. headers: { 'Content-Type': 'application/json' },
  864. body: JSON.stringify({ patterns: { clear_pattern_speed: speed } })
  865. });
  866. if (response.ok) {
  867. await response.json();
  868. if (speed === null) {
  869. showStatusMessage('Clear pattern speed set to default', 'success');
  870. } else {
  871. showStatusMessage(`Clear pattern speed set to ${speed} steps/min`, 'success');
  872. }
  873. // Update the effective speed display
  874. const effectiveClearSpeed = document.getElementById('effectiveClearSpeed');
  875. if (effectiveClearSpeed) {
  876. if (speed === null) {
  877. effectiveClearSpeed.textContent = `Using default pattern speed: ${data.effective_speed} steps/min`;
  878. } else {
  879. effectiveClearSpeed.textContent = `Current: ${speed} steps/min`;
  880. }
  881. }
  882. } else {
  883. const error = await response.json();
  884. throw new Error(error.detail || 'Failed to save clear pattern speed');
  885. }
  886. } catch (error) {
  887. showStatusMessage(`Failed to save clear pattern speed: ${error.message}`, 'error');
  888. }
  889. });
  890. }
  891. }
  892. // Button click handlers
  893. document.addEventListener('DOMContentLoaded', function() {
  894. // Home button
  895. const homeButton = document.getElementById('homeButton');
  896. if (homeButton) {
  897. homeButton.addEventListener('click', async () => {
  898. try {
  899. const response = await fetch('/send_home', {
  900. method: 'POST',
  901. headers: {
  902. 'Content-Type': 'application/json'
  903. }
  904. });
  905. const data = await response.json();
  906. if (data.success) {
  907. updateStatus('Moving to home position...');
  908. }
  909. } catch (error) {
  910. console.error('Error sending home command:', error);
  911. updateStatus('Error: Failed to move to home position');
  912. }
  913. });
  914. }
  915. // Stop button
  916. const stopButton = document.getElementById('stopButton');
  917. if (stopButton) {
  918. stopButton.addEventListener('click', async () => {
  919. try {
  920. const response = await fetch('/stop_execution', {
  921. method: 'POST',
  922. headers: {
  923. 'Content-Type': 'application/json'
  924. }
  925. });
  926. const data = await response.json();
  927. if (data.success) {
  928. updateStatus('Execution stopped');
  929. }
  930. } catch (error) {
  931. console.error('Error stopping execution:', error);
  932. updateStatus('Error: Failed to stop execution');
  933. }
  934. });
  935. }
  936. // Move to Center button
  937. const centerButton = document.getElementById('centerButton');
  938. if (centerButton) {
  939. centerButton.addEventListener('click', async () => {
  940. try {
  941. const response = await fetch('/move_to_center', {
  942. method: 'POST',
  943. headers: {
  944. 'Content-Type': 'application/json'
  945. }
  946. });
  947. const data = await response.json();
  948. if (data.success) {
  949. updateStatus('Moving to center position...');
  950. }
  951. } catch (error) {
  952. console.error('Error moving to center:', error);
  953. updateStatus('Error: Failed to move to center');
  954. }
  955. });
  956. }
  957. // Move to Perimeter button
  958. const perimeterButton = document.getElementById('perimeterButton');
  959. if (perimeterButton) {
  960. perimeterButton.addEventListener('click', async () => {
  961. try {
  962. const response = await fetch('/move_to_perimeter', {
  963. method: 'POST',
  964. headers: {
  965. 'Content-Type': 'application/json'
  966. }
  967. });
  968. const data = await response.json();
  969. if (data.success) {
  970. updateStatus('Moving to perimeter position...');
  971. }
  972. } catch (error) {
  973. console.error('Error moving to perimeter:', error);
  974. updateStatus('Error: Failed to move to perimeter');
  975. }
  976. });
  977. }
  978. });
  979. // Function to update status
  980. function updateStatus(message) {
  981. const statusElement = document.querySelector('.text-slate-800.text-base.font-medium.leading-normal');
  982. if (statusElement) {
  983. statusElement.textContent = message;
  984. // Reset status after 3 seconds if it's a temporary message
  985. if (message.includes('Moving') || message.includes('Execution')) {
  986. setTimeout(() => {
  987. statusElement.textContent = 'Status';
  988. }, 3000);
  989. }
  990. }
  991. }
  992. // Function to show status messages (using existing base.js showStatusMessage if available)
  993. function showStatusMessage(message, type) {
  994. if (typeof window.showStatusMessage === 'function') {
  995. window.showStatusMessage(message, type);
  996. } else {
  997. // Fallback to console logging
  998. console.log(`[${type}] ${message}`);
  999. }
  1000. }
  1001. // Function to show update instructions modal
  1002. function showUpdateInstructionsModal(data) {
  1003. // Create modal HTML
  1004. const modal = document.createElement('div');
  1005. modal.id = 'updateInstructionsModal';
  1006. modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4';
  1007. modal.innerHTML = `
  1008. <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md">
  1009. <div class="p-6">
  1010. <div class="text-center mb-4">
  1011. <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-200 mb-2">Manual Update Required</h2>
  1012. <p class="text-gray-600 dark:text-gray-400 text-sm">
  1013. ${data.message}
  1014. </p>
  1015. </div>
  1016. <div class="text-gray-700 dark:text-gray-300 text-sm mb-6">
  1017. <p class="mb-3">${data.instructions}</p>
  1018. </div>
  1019. <div class="flex gap-3 justify-center">
  1020. <button id="openGitHubRelease" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">
  1021. View Update Instructions
  1022. </button>
  1023. <button id="closeUpdateModal" class="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition-colors">
  1024. Close
  1025. </button>
  1026. </div>
  1027. </div>
  1028. </div>
  1029. `;
  1030. document.body.appendChild(modal);
  1031. // Add event listeners
  1032. const openGitHubButton = modal.querySelector('#openGitHubRelease');
  1033. const closeButton = modal.querySelector('#closeUpdateModal');
  1034. openGitHubButton.addEventListener('click', () => {
  1035. window.open(data.manual_update_url, '_blank');
  1036. document.body.removeChild(modal);
  1037. });
  1038. closeButton.addEventListener('click', () => {
  1039. document.body.removeChild(modal);
  1040. });
  1041. // Close on outside click
  1042. modal.addEventListener('click', (e) => {
  1043. if (e.target === modal) {
  1044. document.body.removeChild(modal);
  1045. }
  1046. });
  1047. }
  1048. // Autocomplete functionality
  1049. function initializeAutocomplete(inputId, suggestionsId, clearButtonId, patterns) {
  1050. const input = document.getElementById(inputId);
  1051. const suggestionsDiv = document.getElementById(suggestionsId);
  1052. const clearButton = document.getElementById(clearButtonId);
  1053. let selectedIndex = -1;
  1054. if (!input || !suggestionsDiv) return;
  1055. // Function to update clear button visibility
  1056. function updateClearButton() {
  1057. if (clearButton) {
  1058. if (input.value.trim()) {
  1059. clearButton.classList.remove('hidden');
  1060. } else {
  1061. clearButton.classList.add('hidden');
  1062. }
  1063. }
  1064. }
  1065. // Format pattern name for display
  1066. function formatPatternName(pattern) {
  1067. return pattern.replace('.thr', '').replace(/_/g, ' ');
  1068. }
  1069. // Filter patterns based on input
  1070. function filterPatterns(searchTerm) {
  1071. if (!searchTerm) return patterns.slice(0, 20); // Show first 20 when empty
  1072. const term = searchTerm.toLowerCase();
  1073. return patterns.filter(pattern => {
  1074. const name = pattern.toLowerCase();
  1075. return name.includes(term);
  1076. }).sort((a, b) => {
  1077. // Prioritize patterns that start with the search term
  1078. const aStarts = a.toLowerCase().startsWith(term);
  1079. const bStarts = b.toLowerCase().startsWith(term);
  1080. if (aStarts && !bStarts) return -1;
  1081. if (!aStarts && bStarts) return 1;
  1082. return a.localeCompare(b);
  1083. }).slice(0, 20); // Limit to 20 results
  1084. }
  1085. // Highlight matching text
  1086. function highlightMatch(text, searchTerm) {
  1087. if (!searchTerm) return text;
  1088. const regex = new RegExp(`(${searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
  1089. return text.replace(regex, '<mark>$1</mark>');
  1090. }
  1091. // Show suggestions
  1092. function showSuggestions(searchTerm) {
  1093. const filtered = filterPatterns(searchTerm);
  1094. if (filtered.length === 0 && searchTerm) {
  1095. suggestionsDiv.innerHTML = '<div class="suggestion-item" style="cursor: default; color: #9ca3af;">No patterns found</div>';
  1096. suggestionsDiv.classList.remove('hidden');
  1097. return;
  1098. }
  1099. suggestionsDiv.innerHTML = filtered.map((pattern, index) => {
  1100. const displayName = formatPatternName(pattern);
  1101. const highlighted = highlightMatch(displayName, searchTerm);
  1102. return `<div class="suggestion-item" data-value="${pattern}" data-index="${index}">${highlighted}</div>`;
  1103. }).join('');
  1104. suggestionsDiv.classList.remove('hidden');
  1105. selectedIndex = -1;
  1106. }
  1107. // Hide suggestions
  1108. function hideSuggestions() {
  1109. setTimeout(() => {
  1110. suggestionsDiv.classList.add('hidden');
  1111. selectedIndex = -1;
  1112. }, 200);
  1113. }
  1114. // Select suggestion
  1115. function selectSuggestion(value) {
  1116. input.value = value;
  1117. hideSuggestions();
  1118. updateClearButton();
  1119. }
  1120. // Handle keyboard navigation
  1121. function handleKeyboard(e) {
  1122. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  1123. if (e.key === 'ArrowDown') {
  1124. e.preventDefault();
  1125. selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
  1126. updateSelection(items);
  1127. } else if (e.key === 'ArrowUp') {
  1128. e.preventDefault();
  1129. selectedIndex = Math.max(selectedIndex - 1, -1);
  1130. updateSelection(items);
  1131. } else if (e.key === 'Enter') {
  1132. e.preventDefault();
  1133. if (selectedIndex >= 0 && items[selectedIndex]) {
  1134. selectSuggestion(items[selectedIndex].dataset.value);
  1135. } else if (items.length === 1) {
  1136. selectSuggestion(items[0].dataset.value);
  1137. }
  1138. } else if (e.key === 'Escape') {
  1139. hideSuggestions();
  1140. }
  1141. }
  1142. // Update visual selection
  1143. function updateSelection(items) {
  1144. items.forEach((item, index) => {
  1145. if (index === selectedIndex) {
  1146. item.classList.add('selected');
  1147. item.scrollIntoView({ block: 'nearest' });
  1148. } else {
  1149. item.classList.remove('selected');
  1150. }
  1151. });
  1152. }
  1153. // Event listeners
  1154. input.addEventListener('input', (e) => {
  1155. const value = e.target.value.trim();
  1156. updateClearButton();
  1157. if (value.length > 0 || e.target === document.activeElement) {
  1158. showSuggestions(value);
  1159. } else {
  1160. hideSuggestions();
  1161. }
  1162. });
  1163. input.addEventListener('focus', () => {
  1164. const value = input.value.trim();
  1165. showSuggestions(value);
  1166. });
  1167. input.addEventListener('blur', hideSuggestions);
  1168. input.addEventListener('keydown', handleKeyboard);
  1169. // Click handler for suggestions
  1170. suggestionsDiv.addEventListener('click', (e) => {
  1171. const item = e.target.closest('.suggestion-item[data-value]');
  1172. if (item) {
  1173. selectSuggestion(item.dataset.value);
  1174. }
  1175. });
  1176. // Mouse hover handler
  1177. suggestionsDiv.addEventListener('mouseover', (e) => {
  1178. const item = e.target.closest('.suggestion-item[data-value]');
  1179. if (item) {
  1180. selectedIndex = parseInt(item.dataset.index);
  1181. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  1182. updateSelection(items);
  1183. }
  1184. });
  1185. // Clear button handler
  1186. if (clearButton) {
  1187. clearButton.addEventListener('click', () => {
  1188. input.value = '';
  1189. updateClearButton();
  1190. hideSuggestions();
  1191. input.focus();
  1192. });
  1193. }
  1194. // Initialize clear button visibility
  1195. updateClearButton();
  1196. }
  1197. // auto_play Mode Functions
  1198. async function initializeauto_playMode() {
  1199. const auto_playToggle = document.getElementById('auto_playModeToggle');
  1200. const auto_playSettings = document.getElementById('auto_playSettings');
  1201. const auto_playPlaylistSelect = document.getElementById('auto_playPlaylistSelect');
  1202. const auto_playRunModeSelect = document.getElementById('auto_playRunModeSelect');
  1203. const auto_playPauseTimeInput = document.getElementById('auto_playPauseTimeInput');
  1204. const auto_playClearPatternSelect = document.getElementById('auto_playClearPatternSelect');
  1205. const auto_playShuffleToggle = document.getElementById('auto_playShuffleToggle');
  1206. // Load current auto_play settings
  1207. try {
  1208. const response = await fetch('/api/auto_play-mode');
  1209. const data = await response.json();
  1210. auto_playToggle.checked = data.enabled;
  1211. if (data.enabled) {
  1212. auto_playSettings.style.display = 'block';
  1213. }
  1214. // Set current values
  1215. auto_playRunModeSelect.value = data.run_mode || 'loop';
  1216. auto_playPauseTimeInput.value = data.pause_time || 5.0;
  1217. auto_playClearPatternSelect.value = data.clear_pattern || 'adaptive';
  1218. auto_playShuffleToggle.checked = data.shuffle || false;
  1219. // Load playlists for selection
  1220. const playlistsResponse = await fetch('/list_all_playlists');
  1221. const playlists = await playlistsResponse.json();
  1222. // Clear and populate playlist select
  1223. auto_playPlaylistSelect.innerHTML = '<option value="">Select a playlist...</option>';
  1224. playlists.forEach(playlist => {
  1225. const option = document.createElement('option');
  1226. option.value = playlist;
  1227. option.textContent = playlist;
  1228. if (playlist === data.playlist) {
  1229. option.selected = true;
  1230. }
  1231. auto_playPlaylistSelect.appendChild(option);
  1232. });
  1233. } catch (error) {
  1234. logMessage(`Error loading auto_play settings: ${error.message}`, LOG_TYPE.ERROR);
  1235. }
  1236. // Get save button
  1237. const saveAutoPlayButton = document.getElementById('saveAutoPlaySettings');
  1238. // Function to save settings
  1239. async function saveSettings(showFeedback = false) {
  1240. const originalButtonHTML = saveAutoPlayButton ? saveAutoPlayButton.innerHTML : '';
  1241. if (showFeedback && saveAutoPlayButton) {
  1242. saveAutoPlayButton.disabled = true;
  1243. saveAutoPlayButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1244. }
  1245. try {
  1246. const response = await fetch('/api/auto_play-mode', {
  1247. method: 'POST',
  1248. headers: { 'Content-Type': 'application/json' },
  1249. body: JSON.stringify({
  1250. enabled: auto_playToggle.checked,
  1251. playlist: auto_playPlaylistSelect.value || null,
  1252. run_mode: auto_playRunModeSelect.value,
  1253. pause_time: parseFloat(auto_playPauseTimeInput.value) || 0,
  1254. clear_pattern: auto_playClearPatternSelect.value,
  1255. shuffle: auto_playShuffleToggle.checked
  1256. })
  1257. });
  1258. if (!response.ok) {
  1259. throw new Error('Failed to save settings');
  1260. }
  1261. if (showFeedback && saveAutoPlayButton) {
  1262. saveAutoPlayButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1263. showStatusMessage('Auto-play settings saved successfully', 'success');
  1264. setTimeout(() => {
  1265. saveAutoPlayButton.innerHTML = originalButtonHTML;
  1266. saveAutoPlayButton.disabled = false;
  1267. }, 2000);
  1268. }
  1269. } catch (error) {
  1270. logMessage(`Error saving auto_play settings: ${error.message}`, LOG_TYPE.ERROR);
  1271. if (showFeedback && saveAutoPlayButton) {
  1272. showStatusMessage(`Failed to save settings: ${error.message}`, 'error');
  1273. saveAutoPlayButton.innerHTML = originalButtonHTML;
  1274. saveAutoPlayButton.disabled = false;
  1275. }
  1276. }
  1277. }
  1278. // Toggle auto_play settings visibility and save
  1279. auto_playToggle.addEventListener('change', async () => {
  1280. auto_playSettings.style.display = auto_playToggle.checked ? 'block' : 'none';
  1281. await saveSettings(false); // Auto-save toggle state without full feedback
  1282. const statusText = auto_playToggle.checked ? 'enabled' : 'disabled';
  1283. showStatusMessage(`Auto-play ${statusText}`, 'success');
  1284. });
  1285. // Save button click handler
  1286. if (saveAutoPlayButton) {
  1287. saveAutoPlayButton.addEventListener('click', () => saveSettings(true));
  1288. }
  1289. }
  1290. // Initialize auto_play mode when DOM is ready
  1291. document.addEventListener('DOMContentLoaded', function() {
  1292. initializeauto_playMode();
  1293. initializeStillSandsMode();
  1294. initializeHomingConfig();
  1295. });
  1296. // Still Sands Mode Functions
  1297. async function initializeStillSandsMode() {
  1298. logMessage('Initializing Still Sands mode', LOG_TYPE.INFO);
  1299. const stillSandsToggle = document.getElementById('scheduledPauseToggle');
  1300. const stillSandsSettings = document.getElementById('scheduledPauseSettings');
  1301. const addTimeSlotButton = document.getElementById('addTimeSlotButton');
  1302. const saveStillSandsButton = document.getElementById('savePauseSettings');
  1303. const timeSlotsContainer = document.getElementById('timeSlotsContainer');
  1304. const wledControlToggle = document.getElementById('stillSandsWledControl');
  1305. const finishPatternToggle = document.getElementById('stillSandsFinishPattern');
  1306. const timezoneSelect = document.getElementById('stillSandsTimezone');
  1307. // Check if elements exist
  1308. if (!stillSandsToggle || !stillSandsSettings || !addTimeSlotButton || !saveStillSandsButton || !timeSlotsContainer) {
  1309. logMessage('Still Sands elements not found, skipping initialization', LOG_TYPE.WARNING);
  1310. logMessage(`Found elements: toggle=${!!stillSandsToggle}, settings=${!!stillSandsSettings}, addBtn=${!!addTimeSlotButton}, saveBtn=${!!saveStillSandsButton}, container=${!!timeSlotsContainer}`, LOG_TYPE.WARNING);
  1311. return;
  1312. }
  1313. logMessage('All Still Sands elements found successfully', LOG_TYPE.INFO);
  1314. // Track time slots
  1315. let timeSlots = [];
  1316. let slotIdCounter = 0;
  1317. // Load current Still Sands settings from initial data
  1318. try {
  1319. // Use the data loaded during page initialization, fallback to API if not available
  1320. let data;
  1321. if (window.initialStillSandsData) {
  1322. data = window.initialStillSandsData;
  1323. // Clear the global variable after use
  1324. delete window.initialStillSandsData;
  1325. } else {
  1326. // Fallback to API call if initial data not available
  1327. const response = await fetch('/api/scheduled-pause');
  1328. data = await response.json();
  1329. }
  1330. stillSandsToggle.checked = data.enabled || false;
  1331. if (data.enabled) {
  1332. stillSandsSettings.style.display = 'block';
  1333. }
  1334. // Load WLED control setting
  1335. if (wledControlToggle) {
  1336. wledControlToggle.checked = data.control_wled || false;
  1337. }
  1338. // Load finish pattern setting
  1339. if (finishPatternToggle) {
  1340. finishPatternToggle.checked = data.finish_pattern || false;
  1341. }
  1342. // Load timezone setting
  1343. if (timezoneSelect) {
  1344. timezoneSelect.value = data.timezone || '';
  1345. }
  1346. // Load existing time slots
  1347. timeSlots = data.time_slots || [];
  1348. // Assign IDs to loaded slots BEFORE rendering
  1349. if (timeSlots.length > 0) {
  1350. slotIdCounter = 0;
  1351. timeSlots.forEach(slot => {
  1352. slot.id = ++slotIdCounter;
  1353. });
  1354. }
  1355. renderTimeSlots();
  1356. } catch (error) {
  1357. logMessage(`Error loading Still Sands settings: ${error.message}`, LOG_TYPE.ERROR);
  1358. // Initialize with empty settings if load fails
  1359. timeSlots = [];
  1360. renderTimeSlots();
  1361. }
  1362. // Function to validate time format (HH:MM)
  1363. function isValidTime(timeString) {
  1364. const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
  1365. return timeRegex.test(timeString);
  1366. }
  1367. // Function to create a new time slot element
  1368. function createTimeSlotElement(slot) {
  1369. const slotDiv = document.createElement('div');
  1370. slotDiv.className = 'time-slot-item';
  1371. slotDiv.dataset.slotId = slot.id;
  1372. slotDiv.innerHTML = `
  1373. <div class="flex items-center gap-3">
  1374. <div class="flex-1 grid grid-cols-1 md:grid-cols-2 gap-3">
  1375. <div class="flex flex-col gap-1">
  1376. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">Start Time</label>
  1377. <input
  1378. type="time"
  1379. 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"
  1380. value="${slot.start_time || ''}"
  1381. required
  1382. />
  1383. </div>
  1384. <div class="flex flex-col gap-1">
  1385. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">End Time</label>
  1386. <input
  1387. type="time"
  1388. 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"
  1389. value="${slot.end_time || ''}"
  1390. required
  1391. />
  1392. </div>
  1393. </div>
  1394. <div class="flex flex-col gap-1">
  1395. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">Days</label>
  1396. <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">
  1397. <option value="daily" ${slot.days === 'daily' ? 'selected' : ''}>Daily</option>
  1398. <option value="weekdays" ${slot.days === 'weekdays' ? 'selected' : ''}>Weekdays</option>
  1399. <option value="weekends" ${slot.days === 'weekends' ? 'selected' : ''}>Weekends</option>
  1400. <option value="custom" ${slot.days === 'custom' ? 'selected' : ''}>Custom</option>
  1401. </select>
  1402. </div>
  1403. <button
  1404. type="button"
  1405. 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"
  1406. title="Remove time slot"
  1407. >
  1408. <span class="material-icons text-base">delete</span>
  1409. </button>
  1410. </div>
  1411. <div class="custom-days-container mt-2" style="display: ${slot.days === 'custom' ? 'block' : 'none'};">
  1412. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium mb-1 block">Select Days</label>
  1413. <div class="flex flex-wrap gap-2">
  1414. ${['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'].map(day => `
  1415. <label class="flex items-center gap-1 text-xs">
  1416. <input
  1417. type="checkbox"
  1418. name="custom-days-${slot.id}"
  1419. value="${day}"
  1420. ${slot.custom_days && slot.custom_days.includes(day) ? 'checked' : ''}
  1421. class="rounded border-slate-300 text-sky-600 focus:ring-sky-500"
  1422. />
  1423. <span class="text-slate-700 dark:text-slate-300 capitalize">${day.substring(0, 3)}</span>
  1424. </label>
  1425. `).join('')}
  1426. </div>
  1427. </div>
  1428. `;
  1429. // Add event listeners for this slot
  1430. const startTimeInput = slotDiv.querySelector('.start-time');
  1431. const endTimeInput = slotDiv.querySelector('.end-time');
  1432. const daysSelect = slotDiv.querySelector('.days-select');
  1433. const customDaysContainer = slotDiv.querySelector('.custom-days-container');
  1434. const removeButton = slotDiv.querySelector('.remove-slot-btn');
  1435. // Show/hide custom days based on selection
  1436. daysSelect.addEventListener('change', () => {
  1437. customDaysContainer.style.display = daysSelect.value === 'custom' ? 'block' : 'none';
  1438. updateTimeSlot(slot.id);
  1439. });
  1440. // Update slot data when inputs change
  1441. startTimeInput.addEventListener('change', () => updateTimeSlot(slot.id));
  1442. endTimeInput.addEventListener('change', () => updateTimeSlot(slot.id));
  1443. // Handle custom day checkboxes
  1444. customDaysContainer.addEventListener('change', () => updateTimeSlot(slot.id));
  1445. // Remove slot button
  1446. removeButton.addEventListener('click', () => {
  1447. removeTimeSlot(slot.id);
  1448. });
  1449. return slotDiv;
  1450. }
  1451. // Function to render all time slots
  1452. function renderTimeSlots() {
  1453. timeSlotsContainer.innerHTML = '';
  1454. if (timeSlots.length === 0) {
  1455. timeSlotsContainer.innerHTML = `
  1456. <div class="text-center py-8 text-slate-500 dark:text-slate-400">
  1457. <span class="material-icons text-4xl mb-2 block">schedule</span>
  1458. <p>No time slots configured</p>
  1459. <p class="text-xs mt-1">Click "Add Time Slot" to create a pause schedule</p>
  1460. </div>
  1461. `;
  1462. return;
  1463. }
  1464. timeSlots.forEach(slot => {
  1465. const slotElement = createTimeSlotElement(slot);
  1466. timeSlotsContainer.appendChild(slotElement);
  1467. });
  1468. }
  1469. // Function to add a new time slot
  1470. function addTimeSlot() {
  1471. const newSlot = {
  1472. id: ++slotIdCounter,
  1473. start_time: '22:00',
  1474. end_time: '08:00',
  1475. days: 'daily',
  1476. custom_days: []
  1477. };
  1478. timeSlots.push(newSlot);
  1479. renderTimeSlots();
  1480. }
  1481. // Function to remove a time slot
  1482. function removeTimeSlot(slotId) {
  1483. timeSlots = timeSlots.filter(slot => slot.id !== slotId);
  1484. renderTimeSlots();
  1485. }
  1486. // Function to update a time slot's data
  1487. function updateTimeSlot(slotId) {
  1488. const slotElement = timeSlotsContainer.querySelector(`[data-slot-id="${slotId}"]`);
  1489. if (!slotElement) return;
  1490. const slot = timeSlots.find(s => s.id === slotId);
  1491. if (!slot) return;
  1492. // Update slot data from inputs
  1493. slot.start_time = slotElement.querySelector('.start-time').value;
  1494. slot.end_time = slotElement.querySelector('.end-time').value;
  1495. slot.days = slotElement.querySelector('.days-select').value;
  1496. // Update custom days if applicable
  1497. if (slot.days === 'custom') {
  1498. const checkedDays = Array.from(slotElement.querySelectorAll(`input[name="custom-days-${slotId}"]:checked`))
  1499. .map(cb => cb.value);
  1500. slot.custom_days = checkedDays;
  1501. } else {
  1502. slot.custom_days = [];
  1503. }
  1504. }
  1505. // Function to validate all time slots
  1506. function validateTimeSlots() {
  1507. const errors = [];
  1508. timeSlots.forEach((slot, index) => {
  1509. if (!slot.start_time || !isValidTime(slot.start_time)) {
  1510. errors.push(`Time slot ${index + 1}: Invalid start time`);
  1511. }
  1512. if (!slot.end_time || !isValidTime(slot.end_time)) {
  1513. errors.push(`Time slot ${index + 1}: Invalid end time`);
  1514. }
  1515. if (slot.days === 'custom' && (!slot.custom_days || slot.custom_days.length === 0)) {
  1516. errors.push(`Time slot ${index + 1}: Please select at least one day for custom schedule`);
  1517. }
  1518. });
  1519. return errors;
  1520. }
  1521. // Function to save settings
  1522. async function saveStillSandsSettings() {
  1523. // Update all slots from current form values
  1524. timeSlots.forEach(slot => updateTimeSlot(slot.id));
  1525. // Validate time slots
  1526. const validationErrors = validateTimeSlots();
  1527. if (validationErrors.length > 0) {
  1528. showStatusMessage(`Validation errors: ${validationErrors.join(', ')}`, 'error');
  1529. return;
  1530. }
  1531. // Update button UI to show loading state
  1532. const originalButtonHTML = saveStillSandsButton.innerHTML;
  1533. saveStillSandsButton.disabled = true;
  1534. saveStillSandsButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1535. try {
  1536. const response = await fetch('/api/scheduled-pause', {
  1537. method: 'POST',
  1538. headers: { 'Content-Type': 'application/json' },
  1539. body: JSON.stringify({
  1540. enabled: stillSandsToggle.checked,
  1541. control_wled: wledControlToggle ? wledControlToggle.checked : false,
  1542. finish_pattern: finishPatternToggle ? finishPatternToggle.checked : false,
  1543. timezone: timezoneSelect ? (timezoneSelect.value || null) : null,
  1544. time_slots: timeSlots.map(slot => ({
  1545. start_time: slot.start_time,
  1546. end_time: slot.end_time,
  1547. days: slot.days,
  1548. custom_days: slot.custom_days
  1549. }))
  1550. })
  1551. });
  1552. if (!response.ok) {
  1553. const errorData = await response.json();
  1554. throw new Error(errorData.detail || 'Failed to save Still Sands settings');
  1555. }
  1556. // Show success state temporarily
  1557. saveStillSandsButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1558. showStatusMessage('Still Sands settings saved successfully', 'success');
  1559. // Restore button after 2 seconds
  1560. setTimeout(() => {
  1561. saveStillSandsButton.innerHTML = originalButtonHTML;
  1562. saveStillSandsButton.disabled = false;
  1563. }, 2000);
  1564. } catch (error) {
  1565. logMessage(`Error saving Still Sands settings: ${error.message}`, LOG_TYPE.ERROR);
  1566. showStatusMessage(`Failed to save settings: ${error.message}`, 'error');
  1567. // Restore button immediately on error
  1568. saveStillSandsButton.innerHTML = originalButtonHTML;
  1569. saveStillSandsButton.disabled = false;
  1570. }
  1571. }
  1572. // Note: Slot IDs are now assigned during initialization above, before first render
  1573. // Event listeners
  1574. stillSandsToggle.addEventListener('change', async () => {
  1575. logMessage(`Still Sands toggle changed: ${stillSandsToggle.checked}`, LOG_TYPE.INFO);
  1576. stillSandsSettings.style.display = stillSandsToggle.checked ? 'block' : 'none';
  1577. logMessage(`Settings display set to: ${stillSandsSettings.style.display}`, LOG_TYPE.INFO);
  1578. // Auto-save when toggle changes
  1579. try {
  1580. await saveStillSandsSettings();
  1581. const statusText = stillSandsToggle.checked ? 'enabled' : 'disabled';
  1582. showStatusMessage(`Still Sands ${statusText} successfully`, 'success');
  1583. } catch (error) {
  1584. logMessage(`Error saving Still Sands toggle: ${error.message}`, LOG_TYPE.ERROR);
  1585. showStatusMessage(`Failed to save Still Sands setting: ${error.message}`, 'error');
  1586. }
  1587. });
  1588. addTimeSlotButton.addEventListener('click', addTimeSlot);
  1589. saveStillSandsButton.addEventListener('click', saveStillSandsSettings);
  1590. // Add listener for WLED control toggle
  1591. if (wledControlToggle) {
  1592. wledControlToggle.addEventListener('change', async () => {
  1593. logMessage(`WLED control toggle changed: ${wledControlToggle.checked}`, LOG_TYPE.INFO);
  1594. // Auto-save when WLED control changes
  1595. await saveStillSandsSettings();
  1596. });
  1597. }
  1598. // Add listener for finish pattern toggle
  1599. if (finishPatternToggle) {
  1600. finishPatternToggle.addEventListener('change', async () => {
  1601. logMessage(`Finish pattern toggle changed: ${finishPatternToggle.checked}`, LOG_TYPE.INFO);
  1602. // Auto-save when finish pattern setting changes
  1603. await saveStillSandsSettings();
  1604. });
  1605. }
  1606. // Add listener for timezone select
  1607. if (timezoneSelect) {
  1608. timezoneSelect.addEventListener('change', async () => {
  1609. logMessage(`Timezone changed: ${timezoneSelect.value || 'System Default'}`, LOG_TYPE.INFO);
  1610. // Auto-save when timezone changes
  1611. await saveStillSandsSettings();
  1612. });
  1613. }
  1614. }
  1615. // Homing Configuration
  1616. async function initializeHomingConfig() {
  1617. logMessage('Initializing homing configuration', LOG_TYPE.INFO);
  1618. const homingModeCrash = document.getElementById('homingModeCrash');
  1619. const homingModeSensor = document.getElementById('homingModeSensor');
  1620. const angularOffsetInput = document.getElementById('angularOffsetInput');
  1621. const compassOffsetContainer = document.getElementById('compassOffsetContainer');
  1622. const saveHomingConfigButton = document.getElementById('saveHomingConfig');
  1623. const homingInfoContent = document.getElementById('homingInfoContent');
  1624. const autoHomeEnabledToggle = document.getElementById('autoHomeEnabledToggle');
  1625. const autoHomeSettings = document.getElementById('autoHomeSettings');
  1626. const autoHomeAfterPatternsInput = document.getElementById('autoHomeAfterPatternsInput');
  1627. // Check if elements exist
  1628. if (!homingModeCrash || !homingModeSensor || !angularOffsetInput || !saveHomingConfigButton || !homingInfoContent || !compassOffsetContainer) {
  1629. logMessage('Homing configuration elements not found, skipping initialization', LOG_TYPE.WARNING);
  1630. return;
  1631. }
  1632. logMessage('Homing configuration elements found successfully', LOG_TYPE.INFO);
  1633. // Function to get selected homing mode
  1634. function getSelectedMode() {
  1635. return homingModeCrash.checked ? 0 : 1;
  1636. }
  1637. // Function to update info box and visibility based on selected mode
  1638. function updateHomingInfo() {
  1639. const mode = getSelectedMode();
  1640. // Show/hide compass offset based on mode
  1641. if (mode === 0) {
  1642. compassOffsetContainer.style.display = 'none';
  1643. homingInfoContent.innerHTML = `
  1644. <p class="font-medium text-blue-800">Crash Homing Mode:</p>
  1645. <ul class="mt-1 space-y-1 text-blue-700">
  1646. <li>• Y axis moves -22mm (or -30mm for mini) until physical stop</li>
  1647. <li>• Theta set to 0, rho set to 0</li>
  1648. <li>• No x0 y0 command sent</li>
  1649. <li>• No hardware sensors required</li>
  1650. </ul>
  1651. `;
  1652. } else {
  1653. compassOffsetContainer.style.display = 'block';
  1654. homingInfoContent.innerHTML = `
  1655. <p class="font-medium text-blue-800">Sensor Homing Mode:</p>
  1656. <ul class="mt-1 space-y-1 text-blue-700">
  1657. <li>• Requires hardware limit switches</li>
  1658. <li>• Requires additional configuration</li>
  1659. </ul>
  1660. `;
  1661. }
  1662. }
  1663. // Load current homing configuration
  1664. try {
  1665. const response = await fetch('/api/homing-config');
  1666. const data = await response.json();
  1667. // Set radio button based on mode
  1668. if (data.homing_mode === 1) {
  1669. homingModeSensor.checked = true;
  1670. } else {
  1671. homingModeCrash.checked = true;
  1672. }
  1673. angularOffsetInput.value = data.angular_homing_offset_degrees || 0;
  1674. // Load auto-home settings
  1675. if (autoHomeEnabledToggle) {
  1676. autoHomeEnabledToggle.checked = data.auto_home_enabled || false;
  1677. if (autoHomeSettings) {
  1678. autoHomeSettings.style.display = data.auto_home_enabled ? 'block' : 'none';
  1679. }
  1680. }
  1681. if (autoHomeAfterPatternsInput) {
  1682. autoHomeAfterPatternsInput.value = data.auto_home_after_patterns || 5;
  1683. }
  1684. updateHomingInfo();
  1685. logMessage(`Loaded homing config: mode=${data.homing_mode}, offset=${data.angular_homing_offset_degrees}°, auto_home=${data.auto_home_enabled}, after=${data.auto_home_after_patterns}`, LOG_TYPE.INFO);
  1686. } catch (error) {
  1687. logMessage(`Error loading homing configuration: ${error.message}`, LOG_TYPE.ERROR);
  1688. // Initialize with defaults if load fails
  1689. homingModeCrash.checked = true;
  1690. angularOffsetInput.value = 0;
  1691. if (autoHomeEnabledToggle) autoHomeEnabledToggle.checked = false;
  1692. if (autoHomeAfterPatternsInput) autoHomeAfterPatternsInput.value = 5;
  1693. updateHomingInfo();
  1694. }
  1695. // Function to save homing configuration
  1696. async function saveHomingConfig() {
  1697. // Update button UI to show loading state
  1698. const originalButtonHTML = saveHomingConfigButton.innerHTML;
  1699. saveHomingConfigButton.disabled = true;
  1700. saveHomingConfigButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1701. try {
  1702. const requestBody = {
  1703. homing_mode: getSelectedMode(),
  1704. angular_homing_offset_degrees: parseFloat(angularOffsetInput.value) || 0
  1705. };
  1706. // Include auto-home settings if elements exist
  1707. if (autoHomeEnabledToggle) {
  1708. requestBody.auto_home_enabled = autoHomeEnabledToggle.checked;
  1709. }
  1710. if (autoHomeAfterPatternsInput) {
  1711. const afterPatterns = parseInt(autoHomeAfterPatternsInput.value);
  1712. if (!isNaN(afterPatterns) && afterPatterns >= 1) {
  1713. requestBody.auto_home_after_patterns = afterPatterns;
  1714. }
  1715. }
  1716. const response = await fetch('/api/homing-config', {
  1717. method: 'POST',
  1718. headers: { 'Content-Type': 'application/json' },
  1719. body: JSON.stringify(requestBody)
  1720. });
  1721. if (!response.ok) {
  1722. const errorData = await response.json();
  1723. throw new Error(errorData.detail || 'Failed to save homing configuration');
  1724. }
  1725. // Show success state temporarily
  1726. saveHomingConfigButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1727. showStatusMessage('Homing configuration saved successfully', 'success');
  1728. // Restore button after 2 seconds
  1729. setTimeout(() => {
  1730. saveHomingConfigButton.innerHTML = originalButtonHTML;
  1731. saveHomingConfigButton.disabled = false;
  1732. }, 2000);
  1733. } catch (error) {
  1734. logMessage(`Error saving homing configuration: ${error.message}`, LOG_TYPE.ERROR);
  1735. showStatusMessage(`Failed to save homing configuration: ${error.message}`, 'error');
  1736. // Restore button immediately on error
  1737. saveHomingConfigButton.innerHTML = originalButtonHTML;
  1738. saveHomingConfigButton.disabled = false;
  1739. }
  1740. }
  1741. // Event listeners
  1742. homingModeCrash.addEventListener('change', updateHomingInfo);
  1743. homingModeSensor.addEventListener('change', updateHomingInfo);
  1744. saveHomingConfigButton.addEventListener('click', saveHomingConfig);
  1745. // Auto-home toggle event listener
  1746. if (autoHomeEnabledToggle && autoHomeSettings) {
  1747. autoHomeEnabledToggle.addEventListener('change', () => {
  1748. autoHomeSettings.style.display = autoHomeEnabledToggle.checked ? 'block' : 'none';
  1749. });
  1750. }
  1751. }
  1752. // Toggle password visibility helper
  1753. function togglePasswordVisibility(inputId, button) {
  1754. const input = document.getElementById(inputId);
  1755. if (!input || !button) return;
  1756. const icon = button.querySelector('.material-icons');
  1757. if (input.type === 'password') {
  1758. input.type = 'text';
  1759. if (icon) icon.textContent = 'visibility';
  1760. } else {
  1761. input.type = 'password';
  1762. if (icon) icon.textContent = 'visibility_off';
  1763. }
  1764. }
  1765. // MQTT Configuration
  1766. async function initializeMqttConfig() {
  1767. logMessage('Initializing MQTT configuration', LOG_TYPE.INFO);
  1768. const mqttEnableToggle = document.getElementById('mqttEnableToggle');
  1769. const mqttSettings = document.getElementById('mqttSettings');
  1770. const mqttStatusBanner = document.getElementById('mqttStatusBanner');
  1771. const mqttConnectedBanner = document.getElementById('mqttConnectedBanner');
  1772. const mqttDisconnectedBanner = document.getElementById('mqttDisconnectedBanner');
  1773. const mqttBrokerInput = document.getElementById('mqttBrokerInput');
  1774. const mqttPortInput = document.getElementById('mqttPortInput');
  1775. const mqttUsernameInput = document.getElementById('mqttUsernameInput');
  1776. const mqttPasswordInput = document.getElementById('mqttPasswordInput');
  1777. const mqttDeviceNameInput = document.getElementById('mqttDeviceNameInput');
  1778. const mqttDeviceIdInput = document.getElementById('mqttDeviceIdInput');
  1779. const mqttClientIdInput = document.getElementById('mqttClientIdInput');
  1780. const mqttDiscoveryPrefixInput = document.getElementById('mqttDiscoveryPrefixInput');
  1781. const testMqttButton = document.getElementById('testMqttConnection');
  1782. const mqttTestResult = document.getElementById('mqttTestResult');
  1783. const saveMqttButton = document.getElementById('saveMqttConfig');
  1784. const mqttRestartNotice = document.getElementById('mqttRestartNotice');
  1785. // Check if elements exist
  1786. if (!mqttEnableToggle || !mqttSettings || !saveMqttButton) {
  1787. logMessage('MQTT configuration elements not found, skipping initialization', LOG_TYPE.WARNING);
  1788. return;
  1789. }
  1790. logMessage('MQTT configuration elements found successfully', LOG_TYPE.INFO);
  1791. // Track if settings have changed (to show restart notice)
  1792. let originalConfig = null;
  1793. let configChanged = false;
  1794. // Function to update UI based on enabled state
  1795. function updateMqttSettingsVisibility() {
  1796. mqttSettings.style.display = mqttEnableToggle.checked ? 'block' : 'none';
  1797. if (mqttStatusBanner) {
  1798. mqttStatusBanner.classList.toggle('hidden', !mqttEnableToggle.checked);
  1799. }
  1800. }
  1801. // Function to update connection status banners
  1802. function updateConnectionStatus(connected) {
  1803. if (mqttConnectedBanner && mqttDisconnectedBanner) {
  1804. if (connected) {
  1805. mqttConnectedBanner.classList.remove('hidden');
  1806. mqttDisconnectedBanner.classList.add('hidden');
  1807. } else {
  1808. mqttConnectedBanner.classList.add('hidden');
  1809. mqttDisconnectedBanner.classList.remove('hidden');
  1810. }
  1811. }
  1812. }
  1813. // Function to check if config has changed
  1814. function checkConfigChanged() {
  1815. if (!originalConfig) return false;
  1816. const currentConfig = {
  1817. enabled: mqttEnableToggle.checked,
  1818. broker: mqttBrokerInput.value,
  1819. port: parseInt(mqttPortInput.value) || 1883,
  1820. username: mqttUsernameInput.value,
  1821. password: mqttPasswordInput.value,
  1822. device_name: mqttDeviceNameInput.value,
  1823. device_id: mqttDeviceIdInput.value,
  1824. client_id: mqttClientIdInput.value,
  1825. discovery_prefix: mqttDiscoveryPrefixInput.value
  1826. };
  1827. return JSON.stringify(currentConfig) !== JSON.stringify(originalConfig);
  1828. }
  1829. // Function to show/hide restart notice
  1830. function updateRestartNotice() {
  1831. configChanged = checkConfigChanged();
  1832. if (mqttRestartNotice) {
  1833. mqttRestartNotice.classList.toggle('hidden', !configChanged);
  1834. }
  1835. }
  1836. // Load current MQTT configuration
  1837. try {
  1838. const response = await fetch('/api/mqtt-config');
  1839. const data = await response.json();
  1840. mqttEnableToggle.checked = data.enabled || false;
  1841. mqttBrokerInput.value = data.broker || '';
  1842. mqttPortInput.value = data.port || 1883;
  1843. mqttUsernameInput.value = data.username || '';
  1844. // Note: Password is not returned from API for security
  1845. mqttDeviceNameInput.value = data.device_name || 'Dune Weaver';
  1846. mqttDeviceIdInput.value = data.device_id || 'dune_weaver';
  1847. mqttClientIdInput.value = data.client_id || 'dune_weaver';
  1848. mqttDiscoveryPrefixInput.value = data.discovery_prefix || 'homeassistant';
  1849. // Store original config for change detection
  1850. originalConfig = {
  1851. enabled: data.enabled || false,
  1852. broker: data.broker || '',
  1853. port: data.port || 1883,
  1854. username: data.username || '',
  1855. password: '', // We don't have the original password
  1856. device_name: data.device_name || 'Dune Weaver',
  1857. device_id: data.device_id || 'dune_weaver',
  1858. client_id: data.client_id || 'dune_weaver',
  1859. discovery_prefix: data.discovery_prefix || 'homeassistant'
  1860. };
  1861. updateMqttSettingsVisibility();
  1862. // Update connection status if MQTT is enabled
  1863. if (data.enabled) {
  1864. updateConnectionStatus(data.connected || false);
  1865. }
  1866. logMessage(`Loaded MQTT config: enabled=${data.enabled}, broker=${data.broker}`, LOG_TYPE.INFO);
  1867. } catch (error) {
  1868. logMessage(`Error loading MQTT configuration: ${error.message}`, LOG_TYPE.ERROR);
  1869. // Initialize with defaults if load fails
  1870. mqttEnableToggle.checked = false;
  1871. updateMqttSettingsVisibility();
  1872. }
  1873. // Function to save MQTT configuration
  1874. async function saveMqttConfig() {
  1875. // Validate required fields if MQTT is enabled
  1876. if (mqttEnableToggle.checked && !mqttBrokerInput.value.trim()) {
  1877. showStatusMessage('MQTT broker address is required when MQTT is enabled', 'error');
  1878. mqttBrokerInput.focus();
  1879. return;
  1880. }
  1881. // Update button UI to show loading state
  1882. const originalButtonHTML = saveMqttButton.innerHTML;
  1883. saveMqttButton.disabled = true;
  1884. saveMqttButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1885. try {
  1886. const requestBody = {
  1887. enabled: mqttEnableToggle.checked,
  1888. broker: mqttBrokerInput.value.trim(),
  1889. port: parseInt(mqttPortInput.value) || 1883,
  1890. username: mqttUsernameInput.value.trim() || null,
  1891. device_name: mqttDeviceNameInput.value.trim() || 'Dune Weaver',
  1892. device_id: mqttDeviceIdInput.value.trim() || 'dune_weaver',
  1893. client_id: mqttClientIdInput.value.trim() || 'dune_weaver',
  1894. discovery_prefix: mqttDiscoveryPrefixInput.value.trim() || 'homeassistant'
  1895. };
  1896. // Only include password if it was changed (not empty)
  1897. if (mqttPasswordInput.value) {
  1898. requestBody.password = mqttPasswordInput.value;
  1899. }
  1900. const response = await fetch('/api/mqtt-config', {
  1901. method: 'POST',
  1902. headers: { 'Content-Type': 'application/json' },
  1903. body: JSON.stringify(requestBody)
  1904. });
  1905. if (!response.ok) {
  1906. const errorData = await response.json();
  1907. throw new Error(errorData.detail || 'Failed to save MQTT configuration');
  1908. }
  1909. const data = await response.json();
  1910. // Update original config for change detection
  1911. originalConfig = {
  1912. enabled: requestBody.enabled,
  1913. broker: requestBody.broker,
  1914. port: requestBody.port,
  1915. username: requestBody.username || '',
  1916. password: '', // Reset password tracking
  1917. device_name: requestBody.device_name,
  1918. device_id: requestBody.device_id,
  1919. client_id: requestBody.client_id,
  1920. discovery_prefix: requestBody.discovery_prefix
  1921. };
  1922. // Clear password field after save
  1923. mqttPasswordInput.value = '';
  1924. // Show success state temporarily
  1925. saveMqttButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1926. showStatusMessage('MQTT configuration saved successfully. Restart the application to apply changes.', 'success');
  1927. // Show restart notice
  1928. if (mqttRestartNotice) {
  1929. mqttRestartNotice.classList.remove('hidden');
  1930. }
  1931. // Restore button after 2 seconds
  1932. setTimeout(() => {
  1933. saveMqttButton.innerHTML = originalButtonHTML;
  1934. saveMqttButton.disabled = false;
  1935. }, 2000);
  1936. } catch (error) {
  1937. logMessage(`Error saving MQTT configuration: ${error.message}`, LOG_TYPE.ERROR);
  1938. showStatusMessage(`Failed to save MQTT configuration: ${error.message}`, 'error');
  1939. // Restore button immediately on error
  1940. saveMqttButton.innerHTML = originalButtonHTML;
  1941. saveMqttButton.disabled = false;
  1942. }
  1943. }
  1944. // Function to test MQTT connection
  1945. async function testMqttConnection() {
  1946. // Validate broker address
  1947. if (!mqttBrokerInput.value.trim()) {
  1948. showStatusMessage('Please enter a broker address to test', 'error');
  1949. mqttBrokerInput.focus();
  1950. return;
  1951. }
  1952. // Update button UI to show loading state
  1953. const originalButtonHTML = testMqttButton.innerHTML;
  1954. testMqttButton.disabled = true;
  1955. testMqttButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Testing...</span>';
  1956. // Clear previous result
  1957. if (mqttTestResult) {
  1958. mqttTestResult.innerHTML = '';
  1959. }
  1960. try {
  1961. const requestBody = {
  1962. broker: mqttBrokerInput.value.trim(),
  1963. port: parseInt(mqttPortInput.value) || 1883,
  1964. username: mqttUsernameInput.value.trim() || null,
  1965. password: mqttPasswordInput.value || null
  1966. };
  1967. const response = await fetch('/api/mqtt-test', {
  1968. method: 'POST',
  1969. headers: { 'Content-Type': 'application/json' },
  1970. body: JSON.stringify(requestBody)
  1971. });
  1972. const data = await response.json();
  1973. if (data.success) {
  1974. if (mqttTestResult) {
  1975. mqttTestResult.innerHTML = '<span class="material-icons text-green-600 mr-1">check_circle</span><span class="text-green-600">Connection successful!</span>';
  1976. }
  1977. showStatusMessage('MQTT connection test successful', 'success');
  1978. } else {
  1979. if (mqttTestResult) {
  1980. mqttTestResult.innerHTML = `<span class="material-icons text-red-600 mr-1">error</span><span class="text-red-600">${data.error || 'Connection failed'}</span>`;
  1981. }
  1982. showStatusMessage(`MQTT test failed: ${data.error || 'Connection failed'}`, 'error');
  1983. }
  1984. } catch (error) {
  1985. logMessage(`Error testing MQTT connection: ${error.message}`, LOG_TYPE.ERROR);
  1986. if (mqttTestResult) {
  1987. mqttTestResult.innerHTML = `<span class="material-icons text-red-600 mr-1">error</span><span class="text-red-600">Test failed: ${error.message}</span>`;
  1988. }
  1989. showStatusMessage(`MQTT test failed: ${error.message}`, 'error');
  1990. } finally {
  1991. // Restore button
  1992. testMqttButton.innerHTML = originalButtonHTML;
  1993. testMqttButton.disabled = false;
  1994. }
  1995. }
  1996. // Event listeners
  1997. mqttEnableToggle.addEventListener('change', () => {
  1998. updateMqttSettingsVisibility();
  1999. updateRestartNotice();
  2000. });
  2001. // Track changes to show restart notice
  2002. [mqttBrokerInput, mqttPortInput, mqttUsernameInput, mqttPasswordInput,
  2003. mqttDeviceNameInput, mqttDeviceIdInput, mqttClientIdInput, mqttDiscoveryPrefixInput].forEach(input => {
  2004. if (input) {
  2005. input.addEventListener('input', updateRestartNotice);
  2006. }
  2007. });
  2008. testMqttButton.addEventListener('click', testMqttConnection);
  2009. saveMqttButton.addEventListener('click', saveMqttConfig);
  2010. }
  2011. // Initialize MQTT config when DOM is ready
  2012. document.addEventListener('DOMContentLoaded', function() {
  2013. initializeMqttConfig();
  2014. initializeTableTypeConfig();
  2015. });
  2016. // ============================================================================
  2017. // Table Type Configuration
  2018. // ============================================================================
  2019. function initializeTableTypeConfig() {
  2020. const tableTypeSelect = document.getElementById('tableTypeSelect');
  2021. const saveTableTypeButton = document.getElementById('saveTableType');
  2022. const detectedTableType = document.getElementById('detectedTableType');
  2023. if (!tableTypeSelect || !saveTableTypeButton) {
  2024. logMessage('Table type elements not found', LOG_TYPE.WARNING);
  2025. return;
  2026. }
  2027. // Load current settings
  2028. loadTableTypeSettings();
  2029. // Save button click handler
  2030. saveTableTypeButton.addEventListener('click', saveTableTypeConfig);
  2031. async function loadTableTypeSettings() {
  2032. try {
  2033. const response = await fetch('/api/settings');
  2034. if (!response.ok) throw new Error('Failed to fetch settings');
  2035. const settings = await response.json();
  2036. const machine = settings.machine || {};
  2037. // Populate dropdown with available table types
  2038. tableTypeSelect.innerHTML = '<option value="">Auto-detect (use detected type)</option>';
  2039. if (machine.available_table_types) {
  2040. machine.available_table_types.forEach(type => {
  2041. const option = document.createElement('option');
  2042. option.value = type.value;
  2043. option.textContent = type.label;
  2044. tableTypeSelect.appendChild(option);
  2045. });
  2046. }
  2047. // Set current override value
  2048. if (machine.table_type_override) {
  2049. tableTypeSelect.value = machine.table_type_override;
  2050. } else {
  2051. tableTypeSelect.value = '';
  2052. }
  2053. // Update detected type display
  2054. if (detectedTableType) {
  2055. const detected = machine.detected_table_type;
  2056. if (detected) {
  2057. // Find the label for the detected type
  2058. const typeInfo = machine.available_table_types?.find(t => t.value === detected);
  2059. detectedTableType.textContent = typeInfo ? typeInfo.label : detected;
  2060. } else {
  2061. detectedTableType.textContent = 'Not connected';
  2062. }
  2063. }
  2064. logMessage('Table type settings loaded', LOG_TYPE.DEBUG);
  2065. } catch (error) {
  2066. logMessage(`Error loading table type settings: ${error.message}`, LOG_TYPE.ERROR);
  2067. }
  2068. }
  2069. async function saveTableTypeConfig() {
  2070. const originalButtonHTML = saveTableTypeButton.innerHTML;
  2071. saveTableTypeButton.disabled = true;
  2072. saveTableTypeButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  2073. try {
  2074. const response = await fetch('/api/settings', {
  2075. method: 'PATCH',
  2076. headers: { 'Content-Type': 'application/json' },
  2077. body: JSON.stringify({
  2078. machine: {
  2079. table_type_override: tableTypeSelect.value || ''
  2080. }
  2081. })
  2082. });
  2083. if (!response.ok) throw new Error('Failed to save settings');
  2084. const result = await response.json();
  2085. if (result.success) {
  2086. showStatusMessage('Table type settings saved. Changes will take effect on next connection.', 'success');
  2087. // Reload to show updated effective type
  2088. await loadTableTypeSettings();
  2089. } else {
  2090. throw new Error('Save failed');
  2091. }
  2092. } catch (error) {
  2093. logMessage(`Error saving table type: ${error.message}`, LOG_TYPE.ERROR);
  2094. showStatusMessage(`Failed to save table type: ${error.message}`, 'error');
  2095. } finally {
  2096. saveTableTypeButton.innerHTML = originalButtonHTML;
  2097. saveTableTypeButton.disabled = false;
  2098. }
  2099. }
  2100. }
  2101. // ============================================================================
  2102. // Application Logs Modal
  2103. // ============================================================================
  2104. let logsWebSocket = null;
  2105. let logsEntries = [];
  2106. const MAX_LOG_ENTRIES = 500;
  2107. // Color classes for different log levels
  2108. const LOG_LEVEL_COLORS = {
  2109. DEBUG: 'text-gray-500 dark:text-gray-400',
  2110. INFO: 'text-blue-600 dark:text-blue-400',
  2111. WARNING: 'text-amber-600 dark:text-amber-400',
  2112. ERROR: 'text-red-600 dark:text-red-400',
  2113. CRITICAL: 'text-red-700 dark:text-red-300 font-bold'
  2114. };
  2115. const LOG_LEVEL_BG = {
  2116. DEBUG: 'bg-gray-100 dark:bg-gray-700',
  2117. INFO: 'bg-blue-50 dark:bg-blue-900/30',
  2118. WARNING: 'bg-amber-50 dark:bg-amber-900/30',
  2119. ERROR: 'bg-red-50 dark:bg-red-900/30',
  2120. CRITICAL: 'bg-red-100 dark:bg-red-900/50'
  2121. };
  2122. function openLogsModal() {
  2123. const modal = document.getElementById('logsModal');
  2124. modal.classList.remove('hidden');
  2125. // Load initial logs
  2126. loadInitialLogs();
  2127. // Connect to WebSocket for real-time updates
  2128. connectLogsWebSocket();
  2129. // Close on overlay click
  2130. modal.addEventListener('click', (e) => {
  2131. if (e.target === modal) {
  2132. closeLogsModal();
  2133. }
  2134. });
  2135. // Close on Escape key
  2136. document.addEventListener('keydown', handleLogsEscapeKey);
  2137. }
  2138. function closeLogsModal() {
  2139. const modal = document.getElementById('logsModal');
  2140. modal.classList.add('hidden');
  2141. // Disconnect WebSocket
  2142. if (logsWebSocket) {
  2143. logsWebSocket.close();
  2144. logsWebSocket = null;
  2145. }
  2146. // Remove event listener
  2147. document.removeEventListener('keydown', handleLogsEscapeKey);
  2148. }
  2149. function handleLogsEscapeKey(e) {
  2150. if (e.key === 'Escape') {
  2151. closeLogsModal();
  2152. }
  2153. }
  2154. async function loadInitialLogs() {
  2155. const logsContent = document.getElementById('logsContent');
  2156. logsContent.innerHTML = '<div class="text-gray-500 dark:text-gray-400">Loading logs...</div>';
  2157. try {
  2158. const response = await fetch('/api/logs?limit=500');
  2159. const data = await response.json();
  2160. logsEntries = data.logs || [];
  2161. renderLogs();
  2162. updateLogsCount();
  2163. // Scroll to bottom
  2164. const container = document.getElementById('logsContainer');
  2165. container.scrollTop = container.scrollHeight;
  2166. } catch (error) {
  2167. console.error('Failed to load logs:', error);
  2168. logsContent.innerHTML = '<div class="text-red-500">Failed to load logs</div>';
  2169. }
  2170. }
  2171. function connectLogsWebSocket() {
  2172. const statusEl = document.getElementById('logsConnectionStatus');
  2173. const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  2174. const wsUrl = `${protocol}//${window.location.host}/ws/logs`;
  2175. try {
  2176. logsWebSocket = new WebSocket(wsUrl);
  2177. logsWebSocket.onopen = () => {
  2178. statusEl.textContent = 'Live';
  2179. statusEl.className = 'text-xs px-2 py-1 rounded-full bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300';
  2180. };
  2181. logsWebSocket.onmessage = (event) => {
  2182. const message = JSON.parse(event.data);
  2183. if (message.type === 'log_entry') {
  2184. addLogEntry(message.data);
  2185. }
  2186. // Ignore heartbeat messages
  2187. };
  2188. logsWebSocket.onclose = () => {
  2189. statusEl.textContent = 'Disconnected';
  2190. statusEl.className = 'text-xs px-2 py-1 rounded-full bg-gray-200 dark:bg-gray-600 text-gray-600 dark:text-gray-300';
  2191. };
  2192. logsWebSocket.onerror = (error) => {
  2193. console.error('Logs WebSocket error:', error);
  2194. statusEl.textContent = 'Error';
  2195. statusEl.className = 'text-xs px-2 py-1 rounded-full bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-300';
  2196. };
  2197. } catch (error) {
  2198. console.error('Failed to connect to logs WebSocket:', error);
  2199. statusEl.textContent = 'Failed';
  2200. statusEl.className = 'text-xs px-2 py-1 rounded-full bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-300';
  2201. }
  2202. }
  2203. function addLogEntry(entry) {
  2204. // Add to beginning (newest first in memory, but we render oldest first in UI)
  2205. logsEntries.unshift(entry);
  2206. // Trim if exceeds max
  2207. if (logsEntries.length > MAX_LOG_ENTRIES) {
  2208. logsEntries.pop();
  2209. }
  2210. // Add to UI
  2211. const logsContent = document.getElementById('logsContent');
  2212. const entryEl = createLogEntryElement(entry);
  2213. // Insert at the end (bottom) for newest
  2214. logsContent.appendChild(entryEl);
  2215. // Auto-scroll if enabled
  2216. const autoScroll = document.getElementById('logsAutoScroll').checked;
  2217. if (autoScroll) {
  2218. const container = document.getElementById('logsContainer');
  2219. container.scrollTop = container.scrollHeight;
  2220. }
  2221. // Apply filter if active
  2222. const levelFilter = document.getElementById('logLevelFilter').value;
  2223. if (levelFilter && entry.level !== levelFilter) {
  2224. entryEl.classList.add('hidden');
  2225. }
  2226. updateLogsCount();
  2227. }
  2228. function createLogEntryElement(entry) {
  2229. const div = document.createElement('div');
  2230. div.className = `log-entry flex gap-2 py-1 px-2 rounded ${LOG_LEVEL_BG[entry.level] || 'bg-gray-50 dark:bg-gray-800'}`;
  2231. div.dataset.level = entry.level;
  2232. // Format timestamp (show only time part for brevity)
  2233. const timestamp = new Date(entry.timestamp);
  2234. const timeStr = timestamp.toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' });
  2235. const msStr = timestamp.getMilliseconds().toString().padStart(3, '0');
  2236. div.innerHTML = `
  2237. <span class="text-gray-400 dark:text-gray-500 shrink-0">${timeStr}.${msStr}</span>
  2238. <span class="${LOG_LEVEL_COLORS[entry.level] || 'text-gray-600'} shrink-0 w-16">${entry.level}</span>
  2239. <span class="text-purple-600 dark:text-purple-400 shrink-0 truncate max-w-32" title="${entry.logger}:${entry.line}">${entry.module}:${entry.line}</span>
  2240. <span class="text-slate-700 dark:text-gray-200 break-all">${escapeHtml(entry.message)}</span>
  2241. `;
  2242. return div;
  2243. }
  2244. function escapeHtml(text) {
  2245. const div = document.createElement('div');
  2246. div.textContent = text;
  2247. return div.innerHTML;
  2248. }
  2249. function renderLogs() {
  2250. const logsContent = document.getElementById('logsContent');
  2251. logsContent.innerHTML = '';
  2252. // Render in reverse order (oldest first, newest at bottom)
  2253. const reversedLogs = [...logsEntries].reverse();
  2254. const levelFilter = document.getElementById('logLevelFilter').value;
  2255. for (const entry of reversedLogs) {
  2256. const entryEl = createLogEntryElement(entry);
  2257. if (levelFilter && entry.level !== levelFilter) {
  2258. entryEl.classList.add('hidden');
  2259. }
  2260. logsContent.appendChild(entryEl);
  2261. }
  2262. }
  2263. function filterLogs() {
  2264. const levelFilter = document.getElementById('logLevelFilter').value;
  2265. const entries = document.querySelectorAll('#logsContent .log-entry');
  2266. let visibleCount = 0;
  2267. entries.forEach(entry => {
  2268. if (!levelFilter || entry.dataset.level === levelFilter) {
  2269. entry.classList.remove('hidden');
  2270. visibleCount++;
  2271. } else {
  2272. entry.classList.add('hidden');
  2273. }
  2274. });
  2275. // Update count to show filtered amount
  2276. const countEl = document.getElementById('logsCount');
  2277. if (levelFilter) {
  2278. countEl.textContent = `${visibleCount} of ${logsEntries.length} entries (filtered)`;
  2279. } else {
  2280. countEl.textContent = `${logsEntries.length} entries`;
  2281. }
  2282. }
  2283. function updateLogsCount() {
  2284. const countEl = document.getElementById('logsCount');
  2285. const levelFilter = document.getElementById('logLevelFilter').value;
  2286. if (levelFilter) {
  2287. const filteredCount = logsEntries.filter(e => e.level === levelFilter).length;
  2288. countEl.textContent = `${filteredCount} of ${logsEntries.length} entries (filtered)`;
  2289. } else {
  2290. countEl.textContent = `${logsEntries.length} entries`;
  2291. }
  2292. }
  2293. async function clearLogs() {
  2294. try {
  2295. await fetch('/api/logs', { method: 'DELETE' });
  2296. logsEntries = [];
  2297. document.getElementById('logsContent').innerHTML = '<div class="text-gray-500 dark:text-gray-400 text-center py-4">Logs cleared</div>';
  2298. updateLogsCount();
  2299. } catch (error) {
  2300. console.error('Failed to clear logs:', error);
  2301. }
  2302. }