main.js 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074
  1. // Global variables
  2. let selectedFile = null;
  3. let playlist = [];
  4. let selectedPlaylistIndex = null;
  5. let allFiles = [];
  6. // Define constants for log message types
  7. const LOG_TYPE = {
  8. SUCCESS: 'success',
  9. WARNING: 'warning',
  10. ERROR: 'error',
  11. INFO: 'info',
  12. DEBUG: 'debug'
  13. };
  14. // Enhanced logMessage with notification system
  15. function logMessage(message, type = LOG_TYPE.DEBUG, clickTargetId = null) {
  16. const log = document.getElementById('status_log');
  17. const header = document.querySelector('header');
  18. if (!header) {
  19. console.error('Error: <header> element not found');
  20. return;
  21. }
  22. // Debug messages only go to the status log
  23. if (type === LOG_TYPE.DEBUG) {
  24. if (!log) {
  25. console.error('Error: #status_log element not found');
  26. return;
  27. }
  28. const entry = document.createElement('p');
  29. entry.textContent = message;
  30. log.appendChild(entry);
  31. log.scrollTop = log.scrollHeight; // Scroll to the bottom of the log
  32. return;
  33. }
  34. // Clear any existing notifications
  35. const existingNotification = header.querySelector('.notification');
  36. if (existingNotification) {
  37. existingNotification.remove();
  38. }
  39. // Create a notification for other message types
  40. const notification = document.createElement('div');
  41. notification.className = `notification ${type}`;
  42. notification.textContent = message;
  43. // Add a close button
  44. const closeButton = document.createElement('button');
  45. closeButton.innerHTML = '<i class="fa-solid fa-xmark"></i>';
  46. closeButton.className = 'close-button no-bg';
  47. closeButton.onclick = (e) => {
  48. e.stopPropagation(); // Prevent triggering the clickTarget when the close button is clicked
  49. notification.classList.remove('show');
  50. setTimeout(() => notification.remove(), 250); // Match transition duration
  51. };
  52. notification.appendChild(closeButton);
  53. // Attach click event to the notification if a clickTargetId is provided
  54. if (clickTargetId) {
  55. notification.onclick = () => {
  56. const target = document.getElementById(clickTargetId);
  57. if (target) {
  58. // Find the closest <main> parent
  59. const parentMain = target.closest('main');
  60. if (parentMain) {
  61. // Remove 'active' class from all <main> elements
  62. document.querySelectorAll('main').forEach((main) => {
  63. main.classList.remove('active');
  64. });
  65. // Add 'active' class to the parent <main>
  66. parentMain.classList.add('active');
  67. target.click();
  68. // Update tab buttons based on the parent <main> ID
  69. const parentId = parentMain.id; // e.g., "patterns-tab"
  70. const tabId = `nav-${parentId.replace('-tab', '')}`; // e.g., "nav-patterns"
  71. document.querySelectorAll('.tab-button').forEach((button) => {
  72. button.classList.remove('active');
  73. });
  74. const tabButton = document.getElementById(tabId);
  75. if (tabButton) {
  76. tabButton.classList.add('active');
  77. }
  78. }
  79. }
  80. };
  81. }
  82. // Append the notification to the header
  83. header.appendChild(notification);
  84. // Trigger the transition
  85. requestAnimationFrame(() => {
  86. notification.classList.add('show');
  87. });
  88. // Auto-remove the notification after 5 seconds
  89. setTimeout(() => {
  90. if (notification.parentNode) {
  91. notification.classList.remove('show');
  92. setTimeout(() => notification.remove(), 250); // Match transition duration
  93. }
  94. }, 5000);
  95. // Also log the message to the status log if available
  96. if (log) {
  97. const entry = document.createElement('p');
  98. entry.textContent = message;
  99. log.appendChild(entry);
  100. log.scrollTop = log.scrollHeight; // Scroll to the bottom of the log
  101. }
  102. }
  103. function toggleDebugLog() {
  104. const statusLog = document.getElementById('status_log');
  105. const debugButton = document.getElementById('debug_button');
  106. if (statusLog.style.display === 'block') {
  107. statusLog.style.display = 'none';
  108. debugButton.classList.remove('active');
  109. } else {
  110. statusLog.style.display = 'block';
  111. debugButton.classList.add( 'active');
  112. statusLog.scrollIntoView({ behavior: 'smooth', block: 'start' }); // Smooth scrolling to the log
  113. }
  114. }
  115. // File selection logic
  116. async function selectFile(file, listItem) {
  117. selectedFile = file;
  118. // Highlight the selected file
  119. document.querySelectorAll('#theta_rho_files li').forEach(li => li.classList.remove('selected'));
  120. listItem.classList.add('selected');
  121. // Update the Remove button visibility
  122. const removeButton = document.querySelector('#pattern-preview-container .remove-button');
  123. if (file.startsWith('custom_patterns/')) {
  124. removeButton.classList.remove('hidden');
  125. } else {
  126. removeButton.classList.add('hidden');
  127. }
  128. logMessage(`Selected file: ${file}`);
  129. // Show the preview container
  130. const previewContainer = document.getElementById('pattern-preview-container');
  131. if (previewContainer) {
  132. previewContainer.classList.remove('hidden');
  133. previewContainer.classList.add('visible');
  134. }
  135. // Update the preview
  136. await previewPattern(file);
  137. // Populate the playlist dropdown after selecting a pattern
  138. await populatePlaylistDropdown();
  139. }
  140. // Fetch and display Theta-Rho files
  141. async function loadThetaRhoFiles() {
  142. try {
  143. logMessage('Loading Theta-Rho files...');
  144. const response = await fetch('/list_theta_rho_files');
  145. let files = await response.json();
  146. files = files.filter(file => file.endsWith('.thr'));
  147. // Sort files with custom_patterns on top and all alphabetically sorted
  148. const sortedFiles = files.sort((a, b) => {
  149. const isCustomA = a.startsWith('custom_patterns/');
  150. const isCustomB = b.startsWith('custom_patterns/');
  151. if (isCustomA && !isCustomB) return -1; // a comes first
  152. if (!isCustomA && isCustomB) return 1; // b comes first
  153. return a.localeCompare(b); // Alphabetical comparison
  154. });
  155. allFiles = sortedFiles; // Update global files
  156. displayFiles(sortedFiles); // Display sorted files
  157. logMessage('Theta-Rho files loaded and sorted successfully.');
  158. } catch (error) {
  159. logMessage(`Error loading Theta-Rho files: ${error.message}`, 'error');
  160. }
  161. }
  162. // Display files in the UI
  163. function displayFiles(files) {
  164. const ul = document.getElementById('theta_rho_files');
  165. if (!ul) {
  166. logMessage('Error: File list container not found');
  167. return;
  168. }
  169. ul.innerHTML = ''; // Clear existing list
  170. files.forEach(file => {
  171. const li = document.createElement('li');
  172. li.textContent = file;
  173. li.classList.add('file-item');
  174. // Attach file selection handler
  175. li.onclick = () => selectFile(file, li);
  176. ul.appendChild(li);
  177. });
  178. }
  179. // Filter files by search input
  180. function searchPatternFiles() {
  181. const searchInput = document.getElementById('search_pattern').value.toLowerCase();
  182. const filteredFiles = allFiles.filter(file => file.toLowerCase().includes(searchInput));
  183. displayFiles(filteredFiles);
  184. }
  185. // Upload a new Theta-Rho file
  186. async function uploadThetaRho() {
  187. const fileInput = document.getElementById('upload_file');
  188. const file = fileInput.files[0];
  189. if (!file) {
  190. logMessage('No file selected for upload.', LOG_TYPE.ERROR);
  191. return;
  192. }
  193. try {
  194. logMessage(`Uploading file: ${file.name}...`);
  195. const formData = new FormData();
  196. formData.append('file', file);
  197. const response = await fetch('/upload_theta_rho', {
  198. method: 'POST',
  199. body: formData
  200. });
  201. const result = await response.json();
  202. if (result.success) {
  203. logMessage(`File uploaded successfully: ${file.name}`, LOG_TYPE.SUCCESS);
  204. fileInput.value = '';
  205. await loadThetaRhoFiles();
  206. } else {
  207. logMessage(`Failed to upload file: ${file.name}`, LOG_TYPE.ERROR);
  208. }
  209. } catch (error) {
  210. logMessage(`Error uploading file: ${error.message}`);
  211. }
  212. }
  213. async function runThetaRho() {
  214. if (!selectedFile) {
  215. logMessage("No file selected to run.");
  216. return;
  217. }
  218. // Get the selected pre-execution action
  219. const preExecutionAction = document.getElementById('pre_execution').value;
  220. logMessage(`Running file: ${selectedFile} with pre-execution action: ${preExecutionAction}...`);
  221. try {
  222. const response = await fetch('/run_theta_rho', {
  223. method: 'POST',
  224. headers: { 'Content-Type': 'application/json' },
  225. body: JSON.stringify({
  226. file_name: selectedFile,
  227. pre_execution: preExecutionAction
  228. })
  229. });
  230. const result = await response.json();
  231. if (response.ok) {
  232. // Connect WebSocket when starting a pattern
  233. connectStatusWebSocket();
  234. // Show the currently playing UI immediately
  235. document.body.classList.add('playing');
  236. const currentlyPlayingFile = document.getElementById('currently-playing-file');
  237. if (currentlyPlayingFile) {
  238. currentlyPlayingFile.textContent = selectedFile.replace('./patterns/', '');
  239. }
  240. // Show initial preview
  241. previewPattern(selectedFile.replace('./patterns/', ''), 'currently-playing-container');
  242. logMessage(`Pattern running: ${selectedFile}`, LOG_TYPE.SUCCESS);
  243. } else {
  244. if (response.status === 409) {
  245. logMessage("Cannot start pattern: Another pattern is already running", LOG_TYPE.WARNING);
  246. } else {
  247. logMessage(`Failed to run file: ${result.detail || 'Unknown error'}`, LOG_TYPE.ERROR);
  248. }
  249. }
  250. } catch (error) {
  251. logMessage(`Error running pattern: ${error.message}`, LOG_TYPE.ERROR);
  252. }
  253. }
  254. async function stopExecution() {
  255. logMessage('Stopping execution...');
  256. const response = await fetch('/stop_execution', { method: 'POST' });
  257. const result = await response.json();
  258. if (result.success) {
  259. logMessage('Execution stopped.',LOG_TYPE.SUCCESS);
  260. } else {
  261. logMessage('Failed to stop execution.',LOG_TYPE.ERROR);
  262. }
  263. }
  264. let isPaused = false;
  265. function togglePausePlay() {
  266. const button = document.getElementById("pausePlayCurrent");
  267. if (isPaused) {
  268. // Resume execution
  269. fetch('/resume_execution', { method: 'POST' })
  270. .then(response => response.json())
  271. .then(data => {
  272. if (data.success) {
  273. isPaused = false;
  274. button.innerHTML = "<i class=\"fa-solid fa-pause\"></i>"; // Change to pause icon
  275. }
  276. })
  277. .catch(error => console.error("Error resuming execution:", error));
  278. } else {
  279. // Pause execution
  280. fetch('/pause_execution', { method: 'POST' })
  281. .then(response => response.json())
  282. .then(data => {
  283. if (data.success) {
  284. isPaused = true;
  285. button.innerHTML = "<i class=\"fa-solid fa-play\"></i>"; // Change to play icon
  286. }
  287. })
  288. .catch(error => console.error("Error pausing execution:", error));
  289. }
  290. }
  291. function removeCurrentPattern() {
  292. if (!selectedFile) {
  293. logMessage('No file selected to remove.', LOG_TYPE.ERROR);
  294. return;
  295. }
  296. if (!selectedFile.startsWith('custom_patterns/')) {
  297. logMessage('Only custom patterns can be removed.', LOG_TYPE.WARNING);
  298. return;
  299. }
  300. removeCustomPattern(selectedFile);
  301. }
  302. // Delete the selected file
  303. async function removeCustomPattern(fileName) {
  304. const userConfirmed = confirm(`Are you sure you want to delete the pattern "${fileName}"?`);
  305. if (!userConfirmed) return;
  306. try {
  307. logMessage(`Deleting pattern: ${fileName}...`);
  308. const response = await fetch('/delete_theta_rho_file', {
  309. method: 'POST',
  310. headers: { 'Content-Type': 'application/json' },
  311. body: JSON.stringify({ file_name: fileName })
  312. });
  313. const result = await response.json();
  314. if (result.success) {
  315. logMessage(`File deleted successfully: ${selectedFile}`, LOG_TYPE.SUCCESS);
  316. // Close the preview container
  317. const previewContainer = document.getElementById('pattern-preview-container');
  318. if (previewContainer) {
  319. previewContainer.classList.add('hidden');
  320. previewContainer.classList.remove('visible');
  321. }
  322. // Clear the selected file and refresh the file list
  323. selectedFile = null;
  324. await loadThetaRhoFiles(); // Refresh the file list
  325. } else {
  326. logMessage(`Failed to delete pattern "${fileName}": ${result.error}`, LOG_TYPE.ERROR);
  327. }
  328. } catch (error) {
  329. logMessage(`Error deleting pattern: ${error.message}`);
  330. }
  331. }
  332. // Preview a Theta-Rho file
  333. async function previewPattern(fileName, containerId = 'pattern-preview-container') {
  334. try {
  335. logMessage(`Fetching data to preview file: ${fileName}...`);
  336. const response = await fetch('/preview_thr', {
  337. method: 'POST',
  338. headers: { 'Content-Type': 'application/json' },
  339. body: JSON.stringify({ file_name: fileName })
  340. });
  341. if (!response.ok) {
  342. throw new Error(`HTTP error! status: ${response.status}`);
  343. }
  344. const data = await response.json();
  345. // Get the preview container
  346. const previewContainer = document.getElementById(containerId);
  347. if (!previewContainer) {
  348. logMessage(`Preview container not found: ${containerId}`, LOG_TYPE.ERROR);
  349. return;
  350. }
  351. // Get the pattern preview section
  352. const patternPreview = previewContainer.querySelector('#pattern-preview');
  353. if (!patternPreview) {
  354. logMessage('Pattern preview section not found', LOG_TYPE.ERROR);
  355. return;
  356. }
  357. // Clear existing content
  358. patternPreview.innerHTML = '';
  359. // Create SVG container
  360. const svgContainer = document.createElement('div');
  361. svgContainer.className = 'svg-container';
  362. svgContainer.innerHTML = data.svg;
  363. // Create coordinate display
  364. const coordDisplay = document.createElement('div');
  365. coordDisplay.className = 'coordinate-display';
  366. // Update coordinate text
  367. if (data.first_coordinate && data.last_coordinate) {
  368. coordDisplay.innerHTML = `
  369. <div>First Coordinate: θ=${data.first_coordinate[0].toFixed(2)}, ρ=${data.first_coordinate[1].toFixed(2)}</div>
  370. <div>Last Coordinate: θ=${data.last_coordinate[0].toFixed(2)}, ρ=${data.last_coordinate[1].toFixed(2)}</div>
  371. `;
  372. } else {
  373. coordDisplay.innerHTML = 'No coordinates available';
  374. }
  375. // Add elements to the preview
  376. patternPreview.appendChild(svgContainer);
  377. patternPreview.appendChild(coordDisplay);
  378. // Show the preview container
  379. previewContainer.classList.remove('hidden');
  380. previewContainer.classList.add('visible');
  381. } catch (error) {
  382. logMessage(`Error previewing pattern: ${error.message}`, LOG_TYPE.ERROR);
  383. }
  384. }
  385. // Render the pattern on a canvas
  386. function renderPattern(coordinates, canvasId) {
  387. const canvas = document.getElementById(canvasId);
  388. if (!canvas) {
  389. logMessage(`Canvas element not found: ${canvasId}`, LOG_TYPE.ERROR);
  390. return;
  391. }
  392. if (!(canvas instanceof HTMLCanvasElement)) {
  393. logMessage(`Element with ID "${canvasId}" is not a canvas.`, LOG_TYPE.ERROR);
  394. return;
  395. }
  396. const ctx = canvas.getContext('2d');
  397. if (!ctx) {
  398. logMessage(`Could not get 2D context for canvas: ${canvasId}`, LOG_TYPE.ERROR);
  399. return;
  400. }
  401. // Account for device pixel ratio
  402. const dpr = window.devicePixelRatio || 1;
  403. const rect = canvas.getBoundingClientRect();
  404. canvas.width = rect.width * dpr; // Scale canvas width for high DPI
  405. canvas.height = rect.height * dpr; // Scale canvas height for high DPI
  406. ctx.scale(dpr, dpr); // Scale drawing context
  407. ctx.clearRect(0, 0, canvas.width, canvas.height);
  408. const centerX = rect.width / 2; // Use bounding client rect dimensions
  409. const centerY = rect.height / 2;
  410. const maxRho = Math.max(...coordinates.map(coord => coord[1]));
  411. const scale = Math.min(rect.width, rect.height) / (2 * maxRho); // Scale to fit
  412. ctx.beginPath();
  413. ctx.strokeStyle = 'white';
  414. coordinates.forEach(([theta, rho], index) => {
  415. const x = centerX + rho * Math.cos(theta) * scale;
  416. const y = centerY - rho * Math.sin(theta) * scale;
  417. if (index === 0) ctx.moveTo(x, y);
  418. else ctx.lineTo(x, y);
  419. });
  420. ctx.stroke();
  421. }
  422. async function moveToCenter() {
  423. logMessage('Moving to center...', LOG_TYPE.INFO);
  424. const response = await fetch('/move_to_center', { method: 'POST' });
  425. const result = await response.json();
  426. if (result.success) {
  427. logMessage('Moved to center successfully.', LOG_TYPE.SUCCESS);
  428. } else {
  429. logMessage(`Failed to move to center: ${result.error}`, LOG_TYPE.ERROR);
  430. }
  431. }
  432. async function moveToPerimeter() {
  433. logMessage('Moving to perimeter...', LOG_TYPE.INFO);
  434. const response = await fetch('/move_to_perimeter', { method: 'POST' });
  435. const result = await response.json();
  436. if (result.success) {
  437. logMessage('Moved to perimeter successfully.', LOG_TYPE.SUCCESS);
  438. } else {
  439. logMessage(`Failed to move to perimeter: ${result.error}`, LOG_TYPE.ERROR);
  440. }
  441. }
  442. async function sendCoordinate() {
  443. const theta = parseFloat(document.getElementById('theta_input').value);
  444. const rho = parseFloat(document.getElementById('rho_input').value);
  445. if (isNaN(theta) || isNaN(rho)) {
  446. logMessage('Invalid input: θ and ρ must be numbers.', LOG_TYPE.ERROR);
  447. return;
  448. }
  449. logMessage(`Sending coordinate: θ=${theta}, ρ=${rho}...`);
  450. const response = await fetch('/send_coordinate', {
  451. method: 'POST',
  452. headers: { 'Content-Type': 'application/json' },
  453. body: JSON.stringify({ theta, rho })
  454. });
  455. const result = await response.json();
  456. if (result.success) {
  457. logMessage(`Coordinate executed successfully: θ=${theta}, ρ=${rho}`, LOG_TYPE.SUCCESS);
  458. } else {
  459. logMessage(`Failed to execute coordinate: ${result.error}`, LOG_TYPE.ERROR);
  460. }
  461. }
  462. async function sendHomeCommand() {
  463. const response = await fetch('/send_home', { method: 'POST' });
  464. const result = await response.json();
  465. if (result.success) {
  466. logMessage('HOME command sent successfully.', LOG_TYPE.SUCCESS);
  467. } else {
  468. logMessage('Failed to send HOME command.', LOG_TYPE.ERROR);
  469. }
  470. }
  471. async function runClearIn() {
  472. logMessage('Running clear from center pattern...', LOG_TYPE.INFO);
  473. try {
  474. const response = await fetch('/run_theta_rho', {
  475. method: 'POST',
  476. headers: { 'Content-Type': 'application/json' },
  477. body: JSON.stringify({
  478. file_name: 'clear_from_in.thr',
  479. pre_execution: 'none'
  480. })
  481. });
  482. if (!response.ok) {
  483. if (response.status === 409) {
  484. logMessage('Cannot start pattern: Another pattern is already running', LOG_TYPE.WARNING);
  485. return;
  486. }
  487. throw new Error(`HTTP error! status: ${response.status}`);
  488. }
  489. const result = await response.json();
  490. if (result.success) {
  491. connectStatusWebSocket();
  492. document.body.classList.add('playing');
  493. logMessage('Clear from center pattern started', LOG_TYPE.SUCCESS);
  494. } else {
  495. logMessage('Failed to run clear pattern', LOG_TYPE.ERROR);
  496. }
  497. } catch (error) {
  498. logMessage(`Error running clear pattern: ${error}`, LOG_TYPE.ERROR);
  499. }
  500. }
  501. async function runClearOut() {
  502. logMessage('Running clear from perimeter pattern...', LOG_TYPE.INFO);
  503. try {
  504. const response = await fetch('/run_theta_rho', {
  505. method: 'POST',
  506. headers: { 'Content-Type': 'application/json' },
  507. body: JSON.stringify({
  508. file_name: 'clear_from_out.thr',
  509. pre_execution: 'none'
  510. })
  511. });
  512. if (!response.ok) {
  513. if (response.status === 409) {
  514. logMessage('Cannot start pattern: Another pattern is already running', LOG_TYPE.WARNING);
  515. return;
  516. }
  517. throw new Error(`HTTP error! status: ${response.status}`);
  518. }
  519. const result = await response.json();
  520. if (result.success) {
  521. connectStatusWebSocket();
  522. document.body.classList.add('playing');
  523. logMessage('Clear from perimeter pattern started', LOG_TYPE.SUCCESS);
  524. } else {
  525. logMessage('Failed to run clear pattern', LOG_TYPE.ERROR);
  526. }
  527. } catch (error) {
  528. logMessage(`Error running clear pattern: ${error}`, LOG_TYPE.ERROR);
  529. }
  530. }
  531. async function runClearSide() {
  532. logMessage('Running clear sideways pattern...', LOG_TYPE.INFO);
  533. try {
  534. const response = await fetch('/run_theta_rho', {
  535. method: 'POST',
  536. headers: { 'Content-Type': 'application/json' },
  537. body: JSON.stringify({
  538. file_name: 'clear_sideway.thr',
  539. pre_execution: 'none'
  540. })
  541. });
  542. if (!response.ok) {
  543. if (response.status === 409) {
  544. logMessage('Cannot start pattern: Another pattern is already running', LOG_TYPE.WARNING);
  545. return;
  546. }
  547. throw new Error(`HTTP error! status: ${response.status}`);
  548. }
  549. const result = await response.json();
  550. if (result.success) {
  551. connectStatusWebSocket();
  552. document.body.classList.add('playing');
  553. logMessage('Clear sideways pattern started', LOG_TYPE.SUCCESS);
  554. } else {
  555. logMessage('Failed to run clear pattern', LOG_TYPE.ERROR);
  556. }
  557. } catch (error) {
  558. logMessage(`Error running clear pattern: ${error}`, LOG_TYPE.ERROR);
  559. }
  560. }
  561. let scrollPosition = 0;
  562. function scrollSelection(direction) {
  563. const container = document.getElementById('clear_selection');
  564. const itemHeight = 50; // Adjust based on CSS height
  565. const maxScroll = container.children.length - 1;
  566. // Update scroll position
  567. scrollPosition += direction;
  568. scrollPosition = Math.max(0, Math.min(scrollPosition, maxScroll));
  569. // Update the transform to scroll items
  570. container.style.transform = `translateY(-${scrollPosition * itemHeight}px)`;
  571. setCookie('clear_action_index', scrollPosition, 365);
  572. }
  573. function executeClearAction(actionFunction) {
  574. // Save the new action to a cookie (optional)
  575. setCookie('clear_action', actionFunction, 365);
  576. if (actionFunction && typeof window[actionFunction] === 'function') {
  577. window[actionFunction](); // Execute the selected clear action
  578. } else {
  579. logMessage('No clear action selected or function not found.', LOG_TYPE.ERROR);
  580. }
  581. }
  582. async function runFile(fileName) {
  583. const response = await fetch(`/run_theta_rho_file/${fileName}`, { method: 'POST' });
  584. const result = await response.json();
  585. if (result.success) {
  586. logMessage(`Running file: ${fileName}`, LOG_TYPE.SUCCESS);
  587. } else {
  588. logMessage(`Failed to run file: ${fileName}`, LOG_TYPE.ERROR);
  589. }
  590. }
  591. // Connection Status
  592. async function checkSerialStatus() {
  593. const response = await fetch('/serial_status');
  594. const status = await response.json();
  595. const statusElement = document.getElementById('serial_status');
  596. const statusHeaderElement = document.getElementById('connection_status_header');
  597. const serialPortsContainer = document.getElementById('serial_ports_container');
  598. const selectElement = document.getElementById('serial_ports');
  599. const connectButton = document.querySelector('button[onclick="connectSerial()"]');
  600. const disconnectButton = document.querySelector('button[onclick="disconnectSerial()"]');
  601. const restartButton = document.querySelector('button[onclick="restartSerial()"]');
  602. if (status.connected) {
  603. const port = status.port || 'Unknown'; // Fallback if port is undefined
  604. statusElement.textContent = `Connected to ${port}`;
  605. statusElement.classList.add('connected');
  606. statusElement.classList.remove('not-connected');
  607. logMessage(`Connected to serial port: ${port}`);
  608. // Update header status
  609. statusHeaderElement.classList.add('connected');
  610. statusHeaderElement.classList.remove('not-connected');
  611. // Hide Available Ports and show disconnect/restart buttons
  612. serialPortsContainer.style.display = 'none';
  613. connectButton.style.display = 'none';
  614. disconnectButton.style.display = 'flex';
  615. restartButton.style.display = 'flex';
  616. // Preselect the connected port in the dropdown
  617. const newOption = document.createElement('option');
  618. newOption.value = port;
  619. newOption.textContent = port;
  620. selectElement.appendChild(newOption);
  621. selectElement.value = port;
  622. } else {
  623. statusElement.textContent = 'Not connected';
  624. statusElement.classList.add('not-connected');
  625. statusElement.classList.remove('connected');
  626. logMessage('No active connection.');
  627. // Update header status
  628. statusHeaderElement.classList.add('not-connected');
  629. statusHeaderElement.classList.remove('connected');
  630. // Show Available Ports and the connect button
  631. serialPortsContainer.style.display = 'block';
  632. connectButton.style.display = 'flex';
  633. disconnectButton.style.display = 'none';
  634. restartButton.style.display = 'none';
  635. // Attempt to auto-load available ports
  636. await loadSerialPorts();
  637. }
  638. }
  639. async function loadSerialPorts() {
  640. const response = await fetch('/list_serial_ports');
  641. const ports = await response.json();
  642. const select = document.getElementById('serial_ports');
  643. select.innerHTML = '';
  644. ports.forEach(port => {
  645. const option = document.createElement('option');
  646. option.value = port;
  647. option.textContent = port;
  648. select.appendChild(option);
  649. });
  650. logMessage('Serial ports loaded.');
  651. }
  652. async function connectSerial() {
  653. const port = document.getElementById('serial_ports').value;
  654. const response = await fetch('/connect', {
  655. method: 'POST',
  656. headers: { 'Content-Type': 'application/json' },
  657. body: JSON.stringify({ port })
  658. });
  659. const result = await response.json();
  660. if (result.success) {
  661. logMessage(`Connected to serial port: ${port}`, LOG_TYPE.SUCCESS);
  662. // Refresh the status
  663. await checkSerialStatus();
  664. } else {
  665. logMessage(`Error connecting to serial port: ${result.error}`, LOG_TYPE.ERROR);
  666. }
  667. }
  668. async function disconnectSerial() {
  669. const response = await fetch('/disconnect', { method: 'POST' });
  670. const result = await response.json();
  671. if (result.success) {
  672. logMessage('Serial port disconnected.', LOG_TYPE.SUCCESS);
  673. // Refresh the status
  674. await checkSerialStatus();
  675. } else {
  676. logMessage(`Error disconnecting: ${result.error}`, LOG_TYPE.ERROR);
  677. }
  678. }
  679. async function restartSerial() {
  680. const port = document.getElementById('serial_ports').value;
  681. const response = await fetch('/restart_connection', {
  682. method: 'POST',
  683. headers: { 'Content-Type': 'application/json' },
  684. body: JSON.stringify({ port })
  685. });
  686. const result = await response.json();
  687. if (result.success) {
  688. document.getElementById('serial_status').textContent = `Restarted connection to ${port}`;
  689. logMessage('Connection restarted.', LOG_TYPE.SUCCESS);
  690. // No need to change visibility for restart
  691. } else {
  692. logMessage(`Error restarting Connection: ${result.error}`, LOG_TYPE.ERROR);
  693. }
  694. }
  695. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  696. // Firmware / Software Updater
  697. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  698. async function checkForUpdates() {
  699. try {
  700. const response = await fetch('/check_software_update');
  701. const data = await response.json();
  702. // Handle updates available logic
  703. // if (data.updates_available) {
  704. // const updateButton = document.getElementById('update-software-btn');
  705. // const updateLinkElement = document.getElementById('update_link');
  706. // const tagLink = `https://github.com/tuanchris/dune-weaver/releases/tag/${data.latest_remote_tag}`;
  707. // updateButton.classList.remove('hidden'); // Show the button
  708. // logMessage("Software Update Available", LOG_TYPE.INFO, 'open-settings-button')
  709. // updateLinkElement.innerHTML = `<a href="${tagLink}" target="_blank">View Release Notes </a>`;
  710. // updateLinkElement.classList.remove('hidden'); // Show the link
  711. // }
  712. // Update current and latest version in the UI
  713. const currentVersionElem = document.getElementById('current_git_version');
  714. const latestVersionElem = document.getElementById('latest_git_version');
  715. currentVersionElem.textContent = `Current Version: ${data.latest_local_tag || 'Unknown'}`;
  716. latestVersionElem.textContent = data.updates_available
  717. ? `Latest Version: ${data.latest_remote_tag}`
  718. : 'You are up to date!';
  719. } catch (error) {
  720. console.error('Error checking for updates:', error);
  721. }
  722. }
  723. async function updateSoftware() {
  724. const updateButton = document.getElementById('update-software-btn');
  725. try {
  726. // Disable the button and update the text
  727. updateButton.disabled = true;
  728. updateButton.querySelector('span').textContent = 'Updating...';
  729. const response = await fetch('/update_software', { method: 'POST' });
  730. const data = await response.json();
  731. if (data.success) {
  732. logMessage('Software updated successfully!', LOG_TYPE.SUCCESS);
  733. window.location.reload(); // Reload the page after update
  734. } else {
  735. logMessage('Failed to update software: ' + data.error, LOG_TYPE.ERROR);
  736. }
  737. } catch (error) {
  738. console.error('Error updating software:', error);
  739. logMessage('Failed to update software', LOG_TYPE.ERROR);
  740. } finally {
  741. // Re-enable the button and reset the text
  742. updateButton.disabled = false;
  743. updateButton.textContent = 'Update Software'; // Adjust to the original text
  744. }
  745. }
  746. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  747. // PART A: Loading / listing playlists from the server
  748. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  749. async function loadAllPlaylists() {
  750. try {
  751. const response = await fetch('/list_all_playlists'); // GET
  752. const allPlaylists = await response.json(); // e.g. ["My Playlist", "Summer", ...]
  753. displayAllPlaylists(allPlaylists);
  754. } catch (err) {
  755. logMessage(`Error loading playlists: ${err}`, LOG_TYPE.ERROR);
  756. }
  757. }
  758. // Function to display all playlists with Load, Run, and Delete buttons
  759. function displayAllPlaylists(playlists) {
  760. const ul = document.getElementById('all_playlists');
  761. ul.innerHTML = ''; // Clear current list
  762. if (playlists.length === 0) {
  763. // Add a placeholder if the list is empty
  764. const emptyLi = document.createElement('li');
  765. emptyLi.textContent = "You don't have any playlists yet.";
  766. emptyLi.classList.add('empty-placeholder'); // Optional: Add a class for styling
  767. ul.appendChild(emptyLi);
  768. return;
  769. }
  770. playlists.forEach(playlistName => {
  771. const li = document.createElement('li');
  772. li.textContent = playlistName;
  773. li.classList.add('playlist-item'); // Add a class for styling
  774. // Attach click event to handle selection
  775. li.onclick = () => {
  776. // Remove 'selected' class from all items
  777. document.querySelectorAll('#all_playlists li').forEach(item => {
  778. item.classList.remove('selected');
  779. });
  780. // Add 'selected' class to the clicked item
  781. li.classList.add('selected');
  782. // Open the playlist editor for the selected playlist
  783. openPlaylistEditor(playlistName);
  784. };
  785. ul.appendChild(li);
  786. });
  787. }
  788. // Cancel changes and close the editor
  789. function cancelPlaylistChanges() {
  790. playlist = [...originalPlaylist]; // Revert to the original playlist
  791. isPlaylistChanged = false;
  792. toggleSaveCancelButtons(false); // Hide the save and cancel buttons
  793. refreshPlaylistUI(); // Refresh the UI with the original state
  794. closeStickySection('playlist-editor'); // Close the editor
  795. }
  796. // Open the playlist editor
  797. function openPlaylistEditor(playlistName) {
  798. logMessage(`Opening editor for playlist: ${playlistName}`);
  799. const editorSection = document.getElementById('playlist-editor');
  800. // Update the displayed playlist name
  801. document.getElementById('playlist_name_display').textContent = playlistName;
  802. // Store the current playlist name for renaming
  803. document.getElementById('playlist_name_input').value = playlistName;
  804. editorSection.classList.remove('hidden');
  805. editorSection.classList.add('visible');
  806. loadPlaylist(playlistName);
  807. }
  808. function clearSchedule() {
  809. document.getElementById("start_time").value = "";
  810. document.getElementById("end_time").value = "";
  811. document.getElementById('clear_time').style.display = 'none';
  812. setCookie('start_time', '', 365);
  813. setCookie('end_time', '', 365);
  814. }
  815. // Function to run the selected playlist with specified parameters
  816. async function runPlaylist() {
  817. const playlistName = document.getElementById('playlist_name_display').textContent;
  818. if (!playlistName) {
  819. logMessage('No playlist selected', 'error');
  820. return;
  821. }
  822. const pauseTime = parseFloat(document.getElementById('pause_time').value) || 0;
  823. const clearPattern = document.getElementById('clear_pattern').value;
  824. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  825. const shuffle = document.getElementById('shuffle_playlist').checked;
  826. try {
  827. const response = await fetch('/run_playlist', {
  828. method: 'POST',
  829. headers: {
  830. 'Content-Type': 'application/json',
  831. },
  832. body: JSON.stringify({
  833. playlist_name: playlistName,
  834. pause_time: pauseTime,
  835. clear_pattern: clearPattern,
  836. run_mode: runMode,
  837. shuffle: shuffle
  838. })
  839. });
  840. if (!response.ok) {
  841. if (response.status === 409) {
  842. logMessage('Another pattern is already running', 'warning');
  843. } else {
  844. const errorData = await response.json();
  845. logMessage(errorData.detail || 'Failed to run playlist', 'error');
  846. }
  847. return;
  848. }
  849. // Connect WebSocket when starting a playlist
  850. connectStatusWebSocket();
  851. logMessage(`Started playlist: ${playlistName}`, 'success');
  852. // Close the playlist editor container after successfully starting the playlist
  853. closeStickySection('playlist-editor');
  854. } catch (error) {
  855. logMessage('Error running playlist: ' + error, 'error');
  856. }
  857. }
  858. // Track changes in the playlist
  859. let originalPlaylist = [];
  860. let isPlaylistChanged = false;
  861. // Load playlist and set the original state
  862. async function loadPlaylist(playlistName) {
  863. try {
  864. logMessage(`Loading playlist: ${playlistName}`);
  865. const response = await fetch(`/get_playlist?name=${encodeURIComponent(playlistName)}`);
  866. const data = await response.json();
  867. if (!data.name) {
  868. throw new Error('Playlist name is missing in the response.');
  869. }
  870. // Populate playlist items and set original state
  871. playlist = data.files || [];
  872. originalPlaylist = [...playlist]; // Clone the playlist as the original
  873. isPlaylistChanged = false; // Reset change tracking
  874. toggleSaveCancelButtons(false); // Hide the save and cancel buttons initially
  875. refreshPlaylistUI();
  876. logMessage(`Loaded playlist: "${playlistName}" with ${playlist.length} file(s).`);
  877. } catch (err) {
  878. logMessage(`Error loading playlist: ${err.message}`, LOG_TYPE.ERROR);
  879. console.error('Error details:', err);
  880. }
  881. }
  882. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  883. // PART B: Creating or Saving (Overwriting) a Playlist
  884. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  885. // Instead of separate create/modify functions, we'll unify them:
  886. async function savePlaylist() {
  887. const name = document.getElementById('playlist_name_display').textContent
  888. if (!name) {
  889. logMessage("Please enter a playlist name.");
  890. return;
  891. }
  892. if (playlist.length === 0) {
  893. logMessage("No files in this playlist. Add files first.");
  894. return;
  895. }
  896. logMessage(`Saving playlist "${name}" with ${playlist.length} file(s)...`);
  897. try {
  898. // We can use /create_playlist or /modify_playlist. They do roughly the same in our single-file approach.
  899. // Let's use /create_playlist to always overwrite or create anew.
  900. const response = await fetch('/create_playlist', {
  901. method: 'POST',
  902. headers: { 'Content-Type': 'application/json' },
  903. body: JSON.stringify({
  904. playlist_name: name,
  905. files: playlist
  906. })
  907. });
  908. const result = await response.json();
  909. if (result.success) {
  910. logMessage(`Playlist "${name}" with ${playlist.length} patterns saved`, LOG_TYPE.SUCCESS);
  911. // Reload the entire list of playlists to reflect changes
  912. // Check for changes and refresh the UI
  913. detectPlaylistChanges();
  914. refreshPlaylistUI();
  915. // Restore default action buttons
  916. toggleSaveCancelButtons(false);
  917. } else {
  918. logMessage(`Failed to save playlist: ${result.error}`, LOG_TYPE.ERROR);
  919. }
  920. } catch (err) {
  921. logMessage(`Error saving playlist: ${err}`);
  922. }
  923. }
  924. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  925. // PART C: Renaming and Deleting a playlist
  926. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  927. // Toggle the rename playlist input
  928. function populatePlaylistDropdown() {
  929. return fetch('/list_all_playlists')
  930. .then(response => response.json())
  931. .then(playlists => {
  932. const select = document.getElementById('select-playlist');
  933. select.innerHTML = ''; // Clear existing options
  934. // Retrieve the saved playlist from the cookie
  935. const savedPlaylist = getCookie('selected_playlist');
  936. // Check if there are playlists available
  937. if (playlists.length === 0) {
  938. // Add a placeholder option if no playlists are available
  939. const placeholderOption = document.createElement('option');
  940. placeholderOption.value = '';
  941. placeholderOption.textContent = 'No playlists available';
  942. placeholderOption.disabled = true; // Prevent selection
  943. placeholderOption.selected = true; // Set as default
  944. select.appendChild(placeholderOption);
  945. return;
  946. }
  947. playlists.forEach(playlist => {
  948. const option = document.createElement('option');
  949. option.value = playlist;
  950. option.textContent = playlist;
  951. // Mark the saved playlist as selected
  952. if (playlist === savedPlaylist) {
  953. option.selected = true;
  954. }
  955. select.appendChild(option);
  956. });
  957. // Attach the onchange event listener after populating the dropdown
  958. select.addEventListener('change', function () {
  959. const selectedPlaylist = this.value;
  960. setCookie('selected_playlist', selectedPlaylist, 365); // Save to cookie
  961. logMessage(`Selected playlist saved: ${selectedPlaylist}`);
  962. });
  963. logMessage('Playlist dropdown populated, event listener attached, and saved playlist restored.');
  964. })
  965. .catch(error => logMessage(`Error fetching playlists: ${error.message}`));
  966. }
  967. populatePlaylistDropdown().then(() => {
  968. loadSettingsFromCookies(); // Restore selected playlist after populating the dropdown
  969. });
  970. // Confirm and save the renamed playlist
  971. async function confirmAddPlaylist() {
  972. const playlistNameInput = document.getElementById('new_playlist_name');
  973. const playlistName = playlistNameInput.value.trim();
  974. if (!playlistName) {
  975. logMessage('Playlist name cannot be empty.', LOG_TYPE.ERROR);
  976. return;
  977. }
  978. try {
  979. logMessage(`Adding new playlist: "${playlistName}"...`);
  980. const response = await fetch('/create_playlist', {
  981. method: 'POST',
  982. headers: { 'Content-Type': 'application/json' },
  983. body: JSON.stringify({
  984. playlist_name: playlistName,
  985. files: [] // New playlist starts empty
  986. })
  987. });
  988. const result = await response.json();
  989. if (result.success) {
  990. logMessage(`Playlist "${playlistName}" created successfully.`, LOG_TYPE.SUCCESS);
  991. // Clear the input field
  992. playlistNameInput.value = '';
  993. // Refresh the playlist list
  994. loadAllPlaylists();
  995. populatePlaylistDropdown();
  996. // Hide the add playlist container
  997. toggleSecondaryButtons('add-playlist-container');
  998. } else {
  999. logMessage(`Failed to create playlist: ${result.error}`, LOG_TYPE.ERROR);
  1000. }
  1001. } catch (error) {
  1002. logMessage(`Error creating playlist: ${error.message}`);
  1003. }
  1004. }
  1005. async function confirmRenamePlaylist() {
  1006. const newName = document.getElementById('playlist_name_input').value.trim();
  1007. const currentName = document.getElementById('playlist_name_display').textContent;
  1008. if (!newName) {
  1009. logMessage("New playlist name cannot be empty.", LOG_TYPE.ERROR);
  1010. return;
  1011. }
  1012. if (newName === currentName) {
  1013. logMessage("New playlist name is the same as the current name. No changes made.", LOG_TYPE.WARNING);
  1014. toggleSecondaryButtons('rename-playlist-container'); // Close the rename container
  1015. return;
  1016. }
  1017. try {
  1018. // Step 1: Create/Modify the playlist with the new name
  1019. const createResponse = await fetch('/modify_playlist', {
  1020. method: 'POST',
  1021. headers: { 'Content-Type': 'application/json' },
  1022. body: JSON.stringify({
  1023. playlist_name: newName,
  1024. files: playlist // Ensure `playlist` contains the current list of files
  1025. })
  1026. });
  1027. const createResult = await createResponse.json();
  1028. if (createResult.success) {
  1029. logMessage(createResult.message, LOG_TYPE.SUCCESS);
  1030. // Step 2: Delete the old playlist
  1031. const deleteResponse = await fetch('/delete_playlist', {
  1032. method: 'DELETE',
  1033. headers: { 'Content-Type': 'application/json' },
  1034. body: JSON.stringify({ playlist_name: currentName })
  1035. });
  1036. const deleteResult = await deleteResponse.json();
  1037. if (deleteResult.success) {
  1038. logMessage(deleteResult.message);
  1039. // Update the UI with the new name
  1040. document.getElementById('playlist_name_display').textContent = newName;
  1041. // Refresh playlists list
  1042. loadAllPlaylists();
  1043. // Close the rename container and restore original action buttons
  1044. toggleSecondaryButtons('rename-playlist-container');
  1045. } else {
  1046. logMessage(`Failed to delete old playlist: ${deleteResult.error}`, LOG_TYPE.ERROR);
  1047. }
  1048. } else {
  1049. logMessage(`Failed to rename playlist: ${createResult.error}`, LOG_TYPE.ERROR);
  1050. }
  1051. } catch (error) {
  1052. logMessage(`Error renaming playlist: ${error.message}`);
  1053. }
  1054. }
  1055. // Delete the currently opened playlist
  1056. async function deleteCurrentPlaylist() {
  1057. const playlistName = document.getElementById('playlist_name_display').textContent;
  1058. if (!confirm(`Are you sure you want to delete the playlist "${playlistName}"? This action cannot be undone.`)) {
  1059. return;
  1060. }
  1061. try {
  1062. const response = await fetch('/delete_playlist', {
  1063. method: 'DELETE',
  1064. headers: { 'Content-Type': 'application/json' },
  1065. body: JSON.stringify({ playlist_name: playlistName })
  1066. });
  1067. const result = await response.json();
  1068. if (result.success) {
  1069. logMessage(`Playlist "${playlistName}" deleted.`, LOG_TYPE.INFO);
  1070. closeStickySection('playlist-editor');
  1071. loadAllPlaylists();
  1072. populatePlaylistDropdown();
  1073. } else {
  1074. logMessage(`Failed to delete playlist: ${result.error}`, LOG_TYPE.ERROR);
  1075. }
  1076. } catch (error) {
  1077. logMessage(`Error deleting playlist: ${error.message}`);
  1078. }
  1079. }
  1080. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1081. // PART D: Local playlist array UI
  1082. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1083. // Refresh the playlist UI and detect changes
  1084. function refreshPlaylistUI() {
  1085. const ul = document.getElementById('playlist_items');
  1086. if (!ul) {
  1087. logMessage('Error: Playlist container not found');
  1088. return;
  1089. }
  1090. ul.innerHTML = ''; // Clear existing items
  1091. if (playlist.length === 0) {
  1092. // Add a placeholder if the playlist is empty
  1093. const emptyLi = document.createElement('li');
  1094. emptyLi.textContent = 'No items in the playlist.';
  1095. emptyLi.classList.add('empty-placeholder'); // Optional: Add a class for styling
  1096. ul.appendChild(emptyLi);
  1097. return;
  1098. }
  1099. playlist.forEach((file, index) => {
  1100. const li = document.createElement('li');
  1101. // Add filename in a span
  1102. const filenameSpan = document.createElement('span');
  1103. filenameSpan.textContent = file;
  1104. filenameSpan.classList.add('filename'); // Add a class for styling
  1105. li.appendChild(filenameSpan);
  1106. // Move Up button
  1107. const moveUpBtn = document.createElement('button');
  1108. moveUpBtn.innerHTML = '<i class="fa-solid fa-turn-up"></i>'; // Up arrow symbol
  1109. moveUpBtn.classList.add('move-button');
  1110. moveUpBtn.onclick = () => {
  1111. if (index > 0) {
  1112. const temp = playlist[index - 1];
  1113. playlist[index - 1] = playlist[index];
  1114. playlist[index] = temp;
  1115. detectPlaylistChanges(); // Check for changes
  1116. refreshPlaylistUI();
  1117. }
  1118. };
  1119. li.appendChild(moveUpBtn);
  1120. // Move Down button
  1121. const moveDownBtn = document.createElement('button');
  1122. moveDownBtn.innerHTML = '<i class="fa-solid fa-turn-down"></i>'; // Down arrow symbol
  1123. moveDownBtn.classList.add('move-button');
  1124. moveDownBtn.onclick = () => {
  1125. if (index < playlist.length - 1) {
  1126. const temp = playlist[index + 1];
  1127. playlist[index + 1] = playlist[index];
  1128. playlist[index] = temp;
  1129. detectPlaylistChanges(); // Check for changes
  1130. refreshPlaylistUI();
  1131. }
  1132. };
  1133. li.appendChild(moveDownBtn);
  1134. // Remove button
  1135. const removeBtn = document.createElement('button');
  1136. removeBtn.innerHTML = '<i class="fa-solid fa-trash"></i>';
  1137. removeBtn.classList.add('remove-button');
  1138. removeBtn.onclick = () => {
  1139. playlist.splice(index, 1);
  1140. detectPlaylistChanges(); // Check for changes
  1141. refreshPlaylistUI();
  1142. };
  1143. li.appendChild(removeBtn);
  1144. ul.appendChild(li);
  1145. });
  1146. }
  1147. // Toggle the visibility of the save and cancel buttons
  1148. function toggleSaveCancelButtons(show) {
  1149. const actionButtons = document.querySelector('#playlist-editor .action-buttons');
  1150. if (actionButtons) {
  1151. // Show/hide all buttons except Save and Cancel
  1152. actionButtons.querySelectorAll('button:not(.save-cancel)').forEach(button => {
  1153. button.style.display = show ? 'none' : 'flex';
  1154. });
  1155. // Show/hide Save and Cancel buttons
  1156. actionButtons.querySelectorAll('.save-cancel').forEach(button => {
  1157. button.style.display = show ? 'flex' : 'none';
  1158. });
  1159. } else {
  1160. logMessage('Error: Action buttons container not found.', LOG_TYPE.ERROR);
  1161. }
  1162. }
  1163. // Detect changes in the playlist
  1164. function detectPlaylistChanges() {
  1165. isPlaylistChanged = JSON.stringify(originalPlaylist) !== JSON.stringify(playlist);
  1166. toggleSaveCancelButtons(isPlaylistChanged);
  1167. }
  1168. // Toggle the "Add to Playlist" section
  1169. function toggleSecondaryButtons(containerId, onShowCallback = null) {
  1170. const container = document.getElementById(containerId);
  1171. if (!container) {
  1172. logMessage(`Error: Element with ID "${containerId}" not found`);
  1173. return;
  1174. }
  1175. // Find the .action-buttons element preceding the container
  1176. const previousActionButtons = container.previousElementSibling?.classList.contains('action-buttons')
  1177. ? container.previousElementSibling
  1178. : null;
  1179. if (container.classList.contains('hidden')) {
  1180. // Show the container
  1181. container.classList.remove('hidden');
  1182. // Hide the previous .action-buttons element
  1183. if (previousActionButtons) {
  1184. previousActionButtons.style.display = 'none';
  1185. }
  1186. // Optional callback for custom logic when showing the container
  1187. if (onShowCallback) {
  1188. onShowCallback();
  1189. }
  1190. } else {
  1191. // Hide the container
  1192. container.classList.add('hidden');
  1193. // Restore the previous .action-buttons element
  1194. if (previousActionButtons) {
  1195. previousActionButtons.style.display = 'flex';
  1196. }
  1197. }
  1198. }
  1199. // Add the selected pattern to the selected playlist
  1200. async function saveToPlaylist() {
  1201. const playlist = document.getElementById('select-playlist').value;
  1202. if (!playlist) {
  1203. logMessage('No playlist selected.', LOG_TYPE.ERROR);
  1204. return;
  1205. }
  1206. if (!selectedFile) {
  1207. logMessage('No pattern selected to add.', LOG_TYPE.ERROR);
  1208. return;
  1209. }
  1210. try {
  1211. logMessage(`Adding pattern "${selectedFile}" to playlist "${playlist}"...`);
  1212. const response = await fetch('/add_to_playlist', {
  1213. method: 'POST',
  1214. headers: { 'Content-Type': 'application/json' },
  1215. body: JSON.stringify({ playlist_name: playlist, pattern: selectedFile })
  1216. });
  1217. const result = await response.json();
  1218. if (result.success) {
  1219. logMessage(`Pattern "${selectedFile}" successfully added to playlist "${playlist}".`, LOG_TYPE.SUCCESS);
  1220. // Reset the UI state via toggleSecondaryButtons
  1221. toggleSecondaryButtons('add-to-playlist-container', () => {
  1222. const selectPlaylist = document.getElementById('select-playlist');
  1223. selectPlaylist.value = ''; // Clear the selection
  1224. });
  1225. } else {
  1226. logMessage(`Failed to add pattern to playlist: ${result.error}`, LOG_TYPE.ERROR);
  1227. }
  1228. } catch (error) {
  1229. logMessage(`Error adding pattern to playlist: ${error.message}`);
  1230. }
  1231. }
  1232. async function changeSpeed() {
  1233. const speedInput = document.getElementById('speed_input');
  1234. const speed = parseFloat(speedInput.value);
  1235. if (isNaN(speed) || speed <= 0) {
  1236. logMessage('Invalid speed. Please enter a positive number.');
  1237. return;
  1238. }
  1239. logMessage(`Setting speed to: ${speed}...`);
  1240. const response = await fetch('/set_speed', {
  1241. method: 'POST',
  1242. headers: { 'Content-Type': 'application/json' },
  1243. body: JSON.stringify({ speed })
  1244. });
  1245. const result = await response.json();
  1246. if (result.success) {
  1247. document.getElementById('current_speed_display').textContent = `Current Speed: ${speed}`;
  1248. logMessage(`Speed set to: ${speed}`, LOG_TYPE.SUCCESS);
  1249. } else {
  1250. logMessage(`Failed to set speed: ${result.error}`, LOG_TYPE.ERROR);
  1251. }
  1252. }
  1253. // Function to close any sticky section
  1254. function closeStickySection(sectionId) {
  1255. const section = document.getElementById(sectionId);
  1256. if (section) {
  1257. section.classList.remove('visible');
  1258. section.classList.remove('fullscreen');
  1259. section.classList.add('hidden');
  1260. // Reset the fullscreen button text if it exists
  1261. const fullscreenButton = section.querySelector('.fullscreen-button');
  1262. if (fullscreenButton) {
  1263. fullscreenButton.innerHtml = '<i class="fa-solid fa-compress"></i>'; // Reset to enter fullscreen icon/text
  1264. }
  1265. logMessage(`Closed section: ${sectionId}`);
  1266. if(sectionId === 'playlist-editor') {
  1267. document.querySelectorAll('#all_playlists .playlist-item').forEach(item => {
  1268. item.classList.remove('selected');
  1269. });
  1270. }
  1271. if(sectionId === 'pattern-preview-container') {
  1272. document.querySelectorAll('#theta_rho_files .file-item').forEach(item => {
  1273. item.classList.remove('selected');
  1274. });
  1275. }
  1276. } else {
  1277. logMessage(`Error: Section with ID "${sectionId}" not found`);
  1278. }
  1279. }
  1280. // Function to open any sticky section
  1281. function openStickySection(sectionId) {
  1282. const section = document.getElementById(sectionId);
  1283. if (section) {
  1284. // Toggle the 'open' class
  1285. section.classList.toggle('open');
  1286. } else {
  1287. logMessage(`Error: Section with ID "${sectionId}" not found`);
  1288. }
  1289. }
  1290. function attachFullScreenListeners() {
  1291. // Add event listener to all fullscreen buttons
  1292. document.querySelectorAll('.fullscreen-button').forEach(button => {
  1293. button.addEventListener('click', function () {
  1294. const stickySection = this.closest('.sticky'); // Find the closest sticky section
  1295. if (stickySection) {
  1296. // Close all other sections
  1297. document.querySelectorAll('.sticky:not(#currently-playing-container):not(#image-converter)').forEach(section => {
  1298. if (section !== stickySection) {
  1299. section.classList.remove('fullscreen');
  1300. section.classList.remove('visible');
  1301. section.classList.add('hidden');
  1302. // Reset the fullscreen button text for other sections
  1303. const otherFullscreenButton = section.querySelector('.fullscreen-button');
  1304. if (otherFullscreenButton) {
  1305. otherFullscreenButton.innerHTML = '<i class="fa-solid fa-expand"></i>'; // Enter fullscreen icon/text
  1306. }
  1307. }
  1308. });
  1309. stickySection.classList.toggle('fullscreen'); // Toggle fullscreen class
  1310. // Update button icon or text
  1311. if (stickySection.classList.contains('fullscreen')) {
  1312. this.innerHTML = '<i class="fa-solid fa-compress"></i>'; // Exit fullscreen icon/text
  1313. } else {
  1314. this.innerHTML = '<i class="fa-solid fa-expand"></i>'; // Enter fullscreen icon/text
  1315. }
  1316. } else {
  1317. console.error('Error: Fullscreen button is not inside a sticky section.');
  1318. }
  1319. });
  1320. });
  1321. }
  1322. let lastPreviewedFile = null; // Track the last previewed file
  1323. function formatSecondsToHMS(seconds) {
  1324. const hrs = Math.floor(seconds / 3600);
  1325. const mins = Math.floor((seconds % 3600) / 60);
  1326. const secs = Math.floor(seconds % 60);
  1327. return `${String(hrs).padStart(2, '0')}:${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
  1328. }
  1329. // Function to start or stop updates based on visibility
  1330. function toggleSettings() {
  1331. const settingsContainer = document.getElementById('settings-container');
  1332. if (settingsContainer) {
  1333. settingsContainer.classList.toggle('open');
  1334. }
  1335. }
  1336. // Utility function to manage cookies
  1337. function setCookie(name, value, days) {
  1338. const date = new Date();
  1339. date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  1340. document.cookie = `${name}=${value};expires=${date.toUTCString()};path=/`;
  1341. }
  1342. function getCookie(name) {
  1343. const nameEQ = `${name}=`;
  1344. const cookies = document.cookie.split(';');
  1345. for (let i = 0; i < cookies.length; i++) {
  1346. let cookie = cookies[i].trim();
  1347. if (cookie.startsWith(nameEQ)) {
  1348. return cookie.substring(nameEQ.length);
  1349. }
  1350. }
  1351. return null;
  1352. }
  1353. // Save settings to cookies
  1354. function saveSettingsToCookies() {
  1355. const pauseTime = document.getElementById('pause_time').value;
  1356. const clearPattern = document.getElementById('clear_pattern').value;
  1357. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  1358. const shuffle = document.getElementById('shuffle_playlist').checked;
  1359. const apiKey = document.getElementById('api-key').value;
  1360. setCookie('pause_time', pauseTime, 365);
  1361. setCookie('clear_pattern', clearPattern, 365);
  1362. setCookie('run_mode', runMode, 365);
  1363. setCookie('shuffle', shuffle, 365);
  1364. setCookie('api_key', apiKey, 365);
  1365. }
  1366. // Load settings from cookies
  1367. function loadSettingsFromCookies() {
  1368. const pauseTime = getCookie('pause_time');
  1369. if (pauseTime !== '') {
  1370. const pauseTimeElement = document.getElementById('pause_time');
  1371. if (pauseTimeElement) {
  1372. pauseTimeElement.value = pauseTime;
  1373. }
  1374. }
  1375. const clearPattern = getCookie('clear_pattern');
  1376. if (clearPattern !== '') {
  1377. const clearPatternElement = document.getElementById('clear_pattern');
  1378. if (clearPatternElement) {
  1379. clearPatternElement.value = clearPattern;
  1380. }
  1381. }
  1382. const runMode = getCookie('run_mode');
  1383. if (runMode !== '') {
  1384. const runModeElement = document.querySelector(`input[name="run_mode"][value="${runMode}"]`);
  1385. if (runModeElement) {
  1386. runModeElement.checked = true;
  1387. }
  1388. }
  1389. const shuffle = getCookie('shuffle');
  1390. if (shuffle !== '') {
  1391. const shuffleElement = document.getElementById('shuffle_playlist');
  1392. if (shuffleElement) {
  1393. shuffleElement.checked = shuffle === 'true';
  1394. }
  1395. }
  1396. const apiKey = getCookie('api_key');
  1397. if (apiKey !== '') {
  1398. const apiKeyElement = document.getElementById('api-key');
  1399. if (apiKeyElement) {
  1400. apiKeyElement.value = apiKey;
  1401. }
  1402. }
  1403. logMessage('Settings loaded from cookies.');
  1404. }
  1405. // Call this function to save settings when a value is changed
  1406. function attachSettingsSaveListeners() {
  1407. // Add event listeners to inputs
  1408. document.getElementById('pause_time').addEventListener('change', saveSettingsToCookies);
  1409. document.getElementById('clear_pattern').addEventListener('change', saveSettingsToCookies);
  1410. document.querySelectorAll('input[name="run_mode"]').forEach(input => {
  1411. input.addEventListener('change', saveSettingsToCookies);
  1412. });
  1413. document.getElementById('shuffle_playlist').addEventListener('change', saveSettingsToCookies);
  1414. document.getElementById('api-key').addEventListener('change', saveSettingsToCookies);
  1415. }
  1416. // Tab switching logic with cookie storage
  1417. function switchTab(tabName, tabGroup = 'main') {
  1418. // Store the active tab in a cookie (per tab group)
  1419. setCookie(`activeTab-${tabGroup}`, tabName, 365);
  1420. // Deactivate all tab content in the specific group
  1421. document.querySelectorAll(`.tab-content[data-group="${tabGroup}"]`).forEach(tab => {
  1422. tab.classList.remove('active');
  1423. });
  1424. // Activate the selected tab content
  1425. const activeTab = document.getElementById(`${tabName}-tab`);
  1426. if (activeTab) {
  1427. activeTab.classList.add('active');
  1428. } else {
  1429. console.error(`Error: Tab "${tabName}" not found.`);
  1430. }
  1431. // Deactivate all buttons in this group
  1432. document.querySelectorAll(`.tab-button[data-group="${tabGroup}"]`).forEach(button => {
  1433. button.classList.remove('active');
  1434. });
  1435. // Activate the selected nav button
  1436. const activeNavButton = document.getElementById(`nav-${tabName}`);
  1437. if (activeNavButton) {
  1438. activeNavButton.classList.add('active');
  1439. } else {
  1440. console.error(`Error: Nav button for "${tabName}" not found.`);
  1441. }
  1442. }
  1443. // Update the small UI segment to show the IP or hide it if none
  1444. function updateWledUI() {
  1445. const wledIp = localStorage.getItem('wled_ip');
  1446. const wledContainer = document.getElementById('wled-container');
  1447. const wledFrame = document.getElementById('wled-frame');
  1448. const wledStatus = document.getElementById('wled-status');
  1449. if (!wledIp) {
  1450. wledContainer.classList.add('hidden');
  1451. return;
  1452. }
  1453. // Show the container and load WLED UI
  1454. wledContainer.classList.remove('hidden');
  1455. wledFrame.src = `http://${wledIp}`;
  1456. }
  1457. // Save or clear the WLED IP, updating both the browser and backend
  1458. async function saveWledIp() {
  1459. const ipInput = document.getElementById('wled_ip');
  1460. const saveButton = document.querySelector('.wled-settings button.cta');
  1461. const currentIp = localStorage.getItem('wled_ip');
  1462. if (currentIp) {
  1463. // Clear the saved IP if one is already set
  1464. localStorage.removeItem('wled_ip');
  1465. ipInput.disabled = false;
  1466. ipInput.value = '';
  1467. saveButton.innerHTML = '<i class="fa-solid fa-save"></i><span>Save</span>';
  1468. logMessage('WLED IP cleared.', LOG_TYPE.INFO);
  1469. // Also clear the IP on the backend
  1470. try {
  1471. const response = await fetch('/set_wled_ip', {
  1472. method: 'POST',
  1473. headers: { 'Content-Type': 'application/json' },
  1474. body: JSON.stringify({ wled_ip: null })
  1475. });
  1476. const data = await response.json();
  1477. if (data.success) {
  1478. logMessage('Backend IP cleared successfully.', LOG_TYPE.INFO);
  1479. } else {
  1480. logMessage('Failed to clear backend IP.', LOG_TYPE.ERROR);
  1481. }
  1482. } catch (error) {
  1483. logMessage(`Error clearing backend IP: ${error.message}`, LOG_TYPE.ERROR);
  1484. }
  1485. } else {
  1486. // Validate and save the new IP
  1487. const ip = ipInput.value.trim();
  1488. if (!validateIp(ip)) {
  1489. logMessage('Invalid IP address format.', LOG_TYPE.ERROR);
  1490. return;
  1491. }
  1492. localStorage.setItem('wled_ip', ip);
  1493. ipInput.disabled = true;
  1494. saveButton.innerHTML = '<i class="fa-solid fa-xmark"></i><span>Clear</span>';
  1495. logMessage(`WLED IP saved: ${ip}`, LOG_TYPE.SUCCESS);
  1496. // Also save the IP to the backend
  1497. try {
  1498. const response = await fetch('/set_wled_ip', {
  1499. method: 'POST',
  1500. headers: { 'Content-Type': 'application/json' },
  1501. body: JSON.stringify({ wled_ip: ip })
  1502. });
  1503. const data = await response.json();
  1504. if (data.success) {
  1505. logMessage('Backend IP saved successfully.', LOG_TYPE.SUCCESS);
  1506. } else {
  1507. logMessage('Failed to save backend IP.', LOG_TYPE.ERROR);
  1508. }
  1509. } catch (error) {
  1510. logMessage(`Error saving backend IP: ${error.message}`, LOG_TYPE.ERROR);
  1511. }
  1512. }
  1513. updateWledUI(); // Refresh any UI elements that depend on the IP
  1514. }
  1515. // Load the WLED IP from localStorage; if not available, retrieve it from the backend
  1516. async function loadWledIp() {
  1517. const ipInput = document.getElementById('wled_ip');
  1518. const saveButton = document.querySelector('.wled-settings button.cta');
  1519. let savedIp = localStorage.getItem('wled_ip');
  1520. if (!savedIp) {
  1521. // Attempt to load from the backend if not found in localStorage
  1522. try {
  1523. const response = await fetch('/get_wled_ip');
  1524. const data = await response.json();
  1525. if (data.wled_ip) {
  1526. savedIp = data.wled_ip;
  1527. localStorage.setItem('wled_ip', savedIp);
  1528. }
  1529. } catch (error) {
  1530. logMessage(`Error fetching WLED IP from backend: ${error.message}`, LOG_TYPE.ERROR);
  1531. }
  1532. }
  1533. if (savedIp) {
  1534. ipInput.value = savedIp;
  1535. ipInput.disabled = true;
  1536. saveButton.innerHTML = '<i class="fa-solid fa-xmark"></i><span>Clear</span>';
  1537. } else {
  1538. ipInput.disabled = false;
  1539. saveButton.innerHTML = '<i class="fa-solid fa-save"></i><span>Save</span>';
  1540. }
  1541. updateWledUI(); // Update any dependent UI segments
  1542. }
  1543. function validateIp(ip) {
  1544. const ipRegex = /^(25[0-5]|2[0-4]\d|1\d\d|\d?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|\d?\d)){3}$/;
  1545. return ipRegex.test(ip);
  1546. }
  1547. // Theme toggle functionality
  1548. const themeToggle = document.getElementById('theme-toggle');
  1549. const themeIcon = themeToggle.querySelector('i');
  1550. themeToggle.addEventListener('click', () => {
  1551. const root = document.documentElement;
  1552. const currentTheme = root.getAttribute('data-theme');
  1553. const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
  1554. root.setAttribute('data-theme', newTheme);
  1555. localStorage.setItem('theme', newTheme);
  1556. // Toggle the icon
  1557. themeIcon.className = newTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
  1558. });
  1559. // Set initial theme and icon based on saved theme
  1560. const savedTheme = localStorage.getItem('theme') || 'light';
  1561. document.documentElement.setAttribute('data-theme', savedTheme);
  1562. themeIcon.className = savedTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
  1563. // Add WebSocket connection for status updates
  1564. let statusSocket = null;
  1565. let reconnectAttempts = 0;
  1566. const MAX_RECONNECT_ATTEMPTS = 5;
  1567. let statusUpdateInterval = null;
  1568. let wsConnected = false;
  1569. function connectStatusWebSocket() {
  1570. // Don't create a new connection if one already exists
  1571. if (wsConnected) {
  1572. console.log('WebSocket already connected');
  1573. return;
  1574. }
  1575. // Close existing connection and clear interval if any
  1576. if (statusSocket) {
  1577. statusSocket.close();
  1578. }
  1579. if (statusUpdateInterval) {
  1580. clearInterval(statusUpdateInterval);
  1581. }
  1582. // Create WebSocket connection
  1583. const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  1584. statusSocket = new WebSocket(`${protocol}//${window.location.host}/ws/status`);
  1585. statusSocket.onopen = () => {
  1586. console.log('Status WebSocket connected');
  1587. wsConnected = true;
  1588. reconnectAttempts = 0; // Reset reconnect attempts on successful connection
  1589. };
  1590. statusSocket.onmessage = (event) => {
  1591. try {
  1592. const message = JSON.parse(event.data);
  1593. if (message.type === 'status_update' && message.data) {
  1594. updateCurrentlyPlayingUI(message.data);
  1595. // Disconnect WebSocket if no pattern is running
  1596. if (!message.data.is_running) {
  1597. console.log('No pattern running, disconnecting WebSocket');
  1598. disconnectStatusWebSocket();
  1599. }
  1600. }
  1601. } catch (error) {
  1602. console.error('Error processing status update:', error);
  1603. console.error('Raw data that caused error:', event.data);
  1604. }
  1605. };
  1606. statusSocket.onclose = () => {
  1607. console.log('Status WebSocket disconnected');
  1608. wsConnected = false;
  1609. clearInterval(statusUpdateInterval);
  1610. // Only attempt to reconnect if we're supposed to be connected
  1611. if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS && document.body.classList.contains('playing')) {
  1612. reconnectAttempts++;
  1613. const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000);
  1614. console.log(`Reconnecting in ${delay/1000}s (Attempt ${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`);
  1615. setTimeout(connectStatusWebSocket, delay);
  1616. }
  1617. };
  1618. statusSocket.onerror = (error) => {
  1619. console.error('WebSocket error:', error);
  1620. };
  1621. }
  1622. function disconnectStatusWebSocket() {
  1623. if (statusSocket && wsConnected) {
  1624. wsConnected = false;
  1625. statusSocket.close();
  1626. statusSocket = null;
  1627. reconnectAttempts = 0;
  1628. }
  1629. }
  1630. // Replace the polling mechanism with WebSocket
  1631. document.addEventListener('DOMContentLoaded', () => {
  1632. const activeMainTab = getCookie('activeTab-main') || 'patterns';
  1633. switchTab(activeMainTab, 'main');
  1634. const activeImageConverterTab = getCookie('activeTab-image-converter') || 'dot';
  1635. switchTab(activeImageConverterTab, 'image-converter');
  1636. checkSerialStatus(); // Check connection status
  1637. loadThetaRhoFiles(); // Load files on page load
  1638. loadAllPlaylists(); // Load all playlists on page load
  1639. attachSettingsSaveListeners(); // Attach event listeners to save changes
  1640. attachFullScreenListeners();
  1641. loadWledIp();
  1642. updateWledUI();
  1643. // Initialize WebSocket connection for status updates
  1644. connectStatusWebSocket();
  1645. // Handle visibility change
  1646. document.addEventListener('visibilitychange', () => {
  1647. if (document.visibilityState === 'visible' && statusSocket && statusSocket.readyState !== WebSocket.OPEN) {
  1648. connectStatusWebSocket();
  1649. }
  1650. });
  1651. checkForUpdates();
  1652. });
  1653. // Track the last time we had a file playing
  1654. let lastPlayingTime = 0;
  1655. const HIDE_DELAY = 5000; // 1 second delay before hiding
  1656. // Update the updateCurrentlyPlayingUI function to handle WebSocket updates
  1657. // Track the last played file to detect when a new pattern starts
  1658. let lastPlayedFile = null;
  1659. function updateCurrentlyPlayingUI(status) {
  1660. // Get all required DOM elements once
  1661. const container = document.getElementById('currently-playing-container');
  1662. const fileNameElement = document.getElementById('currently-playing-file');
  1663. const progressBar = document.getElementById('play_progress');
  1664. const progressText = document.getElementById('play_progress_text');
  1665. const pausePlayButton = document.getElementById('pausePlayCurrent');
  1666. const speedDisplay = document.getElementById('current_speed_display');
  1667. // Check if all required elements exist
  1668. if (!container || !fileNameElement || !progressBar || !progressText) {
  1669. console.log('Required DOM elements not found:', {
  1670. container: !!container,
  1671. fileNameElement: !!fileNameElement,
  1672. progressBar: !!progressBar,
  1673. progressText: !!progressText
  1674. });
  1675. setTimeout(() => updateCurrentlyPlayingUI(status), 100);
  1676. return;
  1677. }
  1678. // Update container visibility based on status
  1679. if (status.current_file && status.is_running) {
  1680. document.body.classList.add('playing');
  1681. container.style.display = 'flex';
  1682. // Hide the preview container when a pattern is playing
  1683. const previewContainer = document.getElementById('pattern-preview-container');
  1684. if (previewContainer) {
  1685. // Clear any selected file highlights
  1686. document.querySelectorAll('#theta_rho_files .file-item').forEach(item => {
  1687. item.classList.remove('selected');
  1688. });
  1689. }
  1690. } else {
  1691. document.body.classList.remove('playing');
  1692. container.style.display = 'none';
  1693. }
  1694. // Update file name display
  1695. if (status.current_file) {
  1696. const fileName = status.current_file.replace('./patterns/', '');
  1697. fileNameElement.textContent = fileName;
  1698. } else {
  1699. fileNameElement.textContent = 'No pattern playing';
  1700. }
  1701. // Update next file display
  1702. const nextFileElement = document.getElementById('next-file');
  1703. if (nextFileElement) {
  1704. if (status.playlist && status.playlist.next_file) {
  1705. const nextFileName = status.playlist.next_file.replace('./patterns/', '');
  1706. nextFileElement.textContent = `(Next: ${nextFileName})`;
  1707. nextFileElement.style.display = 'block';
  1708. } else {
  1709. nextFileElement.style.display = 'none';
  1710. }
  1711. }
  1712. // Update speed display if it exists
  1713. if (speedDisplay && status.speed) {
  1714. speedDisplay.textContent = `Current Speed: ${status.speed}`;
  1715. }
  1716. // Update pattern preview if it's a new pattern
  1717. if (status.current_file && lastPlayedFile !== status.current_file) {
  1718. lastPlayedFile = status.current_file;
  1719. const cleanFileName = status.current_file.replace('./patterns/', '');
  1720. previewPattern(cleanFileName, 'currently-playing-container');
  1721. }
  1722. // Update progress information
  1723. if (status.progress) {
  1724. const { percentage, remaining_time, elapsed_time } = status.progress;
  1725. const formattedPercentage = percentage.toFixed(1);
  1726. const remainingText = remaining_time === null ? 'calculating...' : formatSecondsToHMS(remaining_time);
  1727. const elapsedText = formatSecondsToHMS(elapsed_time);
  1728. progressBar.value = formattedPercentage;
  1729. progressText.textContent = `${formattedPercentage}% (Elapsed: ${elapsedText} | Remaining: ${remainingText})`;
  1730. } else {
  1731. progressBar.value = 0;
  1732. progressText.textContent = '0%';
  1733. }
  1734. // Update pause/play button if it exists
  1735. if (pausePlayButton) {
  1736. pausePlayButton.innerHTML = status.is_paused ?
  1737. '<i class="fa-solid fa-play"></i>' :
  1738. '<i class="fa-solid fa-pause"></i>';
  1739. }
  1740. // Update playlist UI if the function exists
  1741. if (typeof updatePlaylistUI === 'function') {
  1742. updatePlaylistUI(status);
  1743. }
  1744. // Update skip button visibility based on playlist status
  1745. updateSkipButtonVisibility(status);
  1746. }
  1747. // Add these functions to handle the skip button
  1748. function updateSkipButtonVisibility(status) {
  1749. const skipButton = document.getElementById('skipCurrent');
  1750. if (skipButton) {
  1751. // Check if a playlist is playing using the correct status properties
  1752. console.log('status', status);
  1753. const isPlaylistPlaying = status && status.playlist && status.playlist.next_file;
  1754. if (isPlaylistPlaying) {
  1755. skipButton.classList.remove('hidden');
  1756. } else {
  1757. skipButton.classList.add('hidden');
  1758. }
  1759. }
  1760. }
  1761. async function skipPattern() {
  1762. try {
  1763. const response = await fetch('/skip_pattern', {
  1764. method: 'POST',
  1765. });
  1766. const data = await response.json();
  1767. if (data.success) {
  1768. logMessage('Skipping to next pattern', LOG_TYPE.INFO);
  1769. } else {
  1770. logMessage(data.message, LOG_TYPE.ERROR);
  1771. }
  1772. } catch (error) {
  1773. logMessage('Error skipping pattern', 'error');
  1774. }
  1775. }