main.js 73 KB

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