settings.js 81 KB

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