main.js 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810
  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. const response = await fetch('/run_theta_rho', {
  215. method: 'POST',
  216. headers: { 'Content-Type': 'application/json' },
  217. body: JSON.stringify({ file_name: selectedFile, pre_execution: preExecutionAction })
  218. });
  219. const result = await response.json();
  220. if (result.success) {
  221. logMessage(`Pattern running: ${selectedFile}`, LOG_TYPE.SUCCESS);
  222. } else {
  223. logMessage(`Failed to run file: ${selectedFile}`,LOG_TYPE.ERROR);
  224. }
  225. }
  226. async function stopExecution() {
  227. logMessage('Stopping execution...');
  228. const response = await fetch('/stop_execution', { method: 'POST' });
  229. const result = await response.json();
  230. if (result.success) {
  231. logMessage('Execution stopped.',LOG_TYPE.SUCCESS);
  232. } else {
  233. logMessage('Failed to stop execution.',LOG_TYPE.ERROR);
  234. }
  235. }
  236. let isPaused = false;
  237. function togglePausePlay() {
  238. const button = document.getElementById("pausePlayCurrent");
  239. if (isPaused) {
  240. // Resume execution
  241. fetch('/resume_execution', { method: 'POST' })
  242. .then(response => response.json())
  243. .then(data => {
  244. if (data.success) {
  245. isPaused = false;
  246. button.innerHTML = "<i class=\"fa-solid fa-pause\"></i>"; // Change to pause icon
  247. }
  248. })
  249. .catch(error => console.error("Error resuming execution:", error));
  250. } else {
  251. // Pause execution
  252. fetch('/pause_execution', { method: 'POST' })
  253. .then(response => response.json())
  254. .then(data => {
  255. if (data.success) {
  256. isPaused = true;
  257. button.innerHTML = "<i class=\"fa-solid fa-play\"></i>"; // Change to play icon
  258. }
  259. })
  260. .catch(error => console.error("Error pausing execution:", error));
  261. }
  262. }
  263. function removeCurrentPattern() {
  264. if (!selectedFile) {
  265. logMessage('No file selected to remove.', LOG_TYPE.ERROR);
  266. return;
  267. }
  268. if (!selectedFile.startsWith('custom_patterns/')) {
  269. logMessage('Only custom patterns can be removed.', LOG_TYPE.WARNING);
  270. return;
  271. }
  272. removeCustomPattern(selectedFile);
  273. }
  274. // Delete the selected file
  275. async function removeCustomPattern(fileName) {
  276. const userConfirmed = confirm(`Are you sure you want to delete the pattern "${fileName}"?`);
  277. if (!userConfirmed) return;
  278. try {
  279. logMessage(`Deleting pattern: ${fileName}...`);
  280. const response = await fetch('/delete_theta_rho_file', {
  281. method: 'POST',
  282. headers: { 'Content-Type': 'application/json' },
  283. body: JSON.stringify({ file_name: fileName })
  284. });
  285. const result = await response.json();
  286. if (result.success) {
  287. logMessage(`File deleted successfully: ${selectedFile}`, LOG_TYPE.SUCCESS);
  288. // Close the preview container
  289. const previewContainer = document.getElementById('pattern-preview-container');
  290. if (previewContainer) {
  291. previewContainer.classList.add('hidden');
  292. previewContainer.classList.remove('visible');
  293. }
  294. // Clear the selected file and refresh the file list
  295. selectedFile = null;
  296. await loadThetaRhoFiles(); // Refresh the file list
  297. } else {
  298. logMessage(`Failed to delete pattern "${fileName}": ${result.error}`, LOG_TYPE.ERROR);
  299. }
  300. } catch (error) {
  301. logMessage(`Error deleting pattern: ${error.message}`);
  302. }
  303. }
  304. // Preview a Theta-Rho file
  305. async function previewPattern(fileName, containerId = 'pattern-preview-container') {
  306. try {
  307. logMessage(`Fetching data to preview file: ${fileName}...`);
  308. const response = await fetch('/preview_thr', {
  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. const coordinates = result.coordinates;
  316. // Render the pattern in the specified container
  317. const canvasId = containerId === 'currently-playing-container'
  318. ? 'currentlyPlayingCanvas'
  319. : 'patternPreviewCanvas';
  320. renderPattern(coordinates, canvasId);
  321. // Update coordinate display
  322. const firstCoordElement = document.getElementById('first_coordinate');
  323. const lastCoordElement = document.getElementById('last_coordinate');
  324. if (firstCoordElement) {
  325. const firstCoord = coordinates[0];
  326. firstCoordElement.textContent = `First Coordinate: θ=${firstCoord[0]}, ρ=${firstCoord[1]}`;
  327. } else {
  328. logMessage('First coordinate element not found.', LOG_TYPE.WARNING);
  329. }
  330. if (lastCoordElement) {
  331. const lastCoord = coordinates[coordinates.length - 1];
  332. lastCoordElement.textContent = `Last Coordinate: θ=${lastCoord[0]}, ρ=${lastCoord[1]}`;
  333. } else {
  334. logMessage('Last coordinate element not found.', LOG_TYPE.WARNING);
  335. }
  336. // Show the preview container
  337. const previewContainer = document.getElementById(containerId);
  338. if (previewContainer) {
  339. previewContainer.classList.remove('hidden');
  340. previewContainer.classList.add('visible');
  341. } else {
  342. logMessage(`Preview container not found: ${containerId}`, LOG_TYPE.ERROR);
  343. }
  344. } else {
  345. logMessage(`Failed to fetch preview for file: ${fileName}`, LOG_TYPE.WARNING);
  346. }
  347. } catch (error) {
  348. logMessage(`Error previewing pattern: ${error.message}`, LOG_TYPE.ERROR);
  349. }
  350. }
  351. // Render the pattern on a canvas
  352. function renderPattern(coordinates, canvasId) {
  353. const canvas = document.getElementById(canvasId);
  354. if (!canvas) {
  355. logMessage(`Canvas element not found: ${canvasId}`, LOG_TYPE.ERROR);
  356. return;
  357. }
  358. if (!(canvas instanceof HTMLCanvasElement)) {
  359. logMessage(`Element with ID "${canvasId}" is not a canvas.`, LOG_TYPE.ERROR);
  360. return;
  361. }
  362. const ctx = canvas.getContext('2d');
  363. if (!ctx) {
  364. logMessage(`Could not get 2D context for canvas: ${canvasId}`, LOG_TYPE.ERROR);
  365. return;
  366. }
  367. // Account for device pixel ratio
  368. const dpr = window.devicePixelRatio || 1;
  369. const rect = canvas.getBoundingClientRect();
  370. canvas.width = rect.width * dpr; // Scale canvas width for high DPI
  371. canvas.height = rect.height * dpr; // Scale canvas height for high DPI
  372. ctx.scale(dpr, dpr); // Scale drawing context
  373. ctx.clearRect(0, 0, canvas.width, canvas.height);
  374. const centerX = rect.width / 2; // Use bounding client rect dimensions
  375. const centerY = rect.height / 2;
  376. const maxRho = Math.max(...coordinates.map(coord => coord[1]));
  377. const scale = Math.min(rect.width, rect.height) / (2 * maxRho); // Scale to fit
  378. ctx.beginPath();
  379. ctx.strokeStyle = 'white';
  380. coordinates.forEach(([theta, rho], index) => {
  381. const x = centerX + rho * Math.cos(theta) * scale;
  382. const y = centerY - rho * Math.sin(theta) * scale;
  383. if (index === 0) ctx.moveTo(x, y);
  384. else ctx.lineTo(x, y);
  385. });
  386. ctx.stroke();
  387. }
  388. async function moveToCenter() {
  389. logMessage('Moving to center...', LOG_TYPE.INFO);
  390. const response = await fetch('/move_to_center', { method: 'POST' });
  391. const result = await response.json();
  392. if (result.success) {
  393. logMessage('Moved to center successfully.', LOG_TYPE.SUCCESS);
  394. } else {
  395. logMessage(`Failed to move to center: ${result.error}`, LOG_TYPE.ERROR);
  396. }
  397. }
  398. async function moveToPerimeter() {
  399. logMessage('Moving to perimeter...', LOG_TYPE.INFO);
  400. const response = await fetch('/move_to_perimeter', { method: 'POST' });
  401. const result = await response.json();
  402. if (result.success) {
  403. logMessage('Moved to perimeter successfully.', LOG_TYPE.SUCCESS);
  404. } else {
  405. logMessage(`Failed to move to perimeter: ${result.error}`, LOG_TYPE.ERROR);
  406. }
  407. }
  408. async function sendCoordinate() {
  409. const theta = parseFloat(document.getElementById('theta_input').value);
  410. const rho = parseFloat(document.getElementById('rho_input').value);
  411. if (isNaN(theta) || isNaN(rho)) {
  412. logMessage('Invalid input: θ and ρ must be numbers.', LOG_TYPE.ERROR);
  413. return;
  414. }
  415. logMessage(`Sending coordinate: θ=${theta}, ρ=${rho}...`);
  416. const response = await fetch('/send_coordinate', {
  417. method: 'POST',
  418. headers: { 'Content-Type': 'application/json' },
  419. body: JSON.stringify({ theta, rho })
  420. });
  421. const result = await response.json();
  422. if (result.success) {
  423. logMessage(`Coordinate executed successfully: θ=${theta}, ρ=${rho}`, LOG_TYPE.SUCCESS);
  424. } else {
  425. logMessage(`Failed to execute coordinate: ${result.error}`, LOG_TYPE.ERROR);
  426. }
  427. }
  428. async function sendHomeCommand() {
  429. const response = await fetch('/send_home', { method: 'POST' });
  430. const result = await response.json();
  431. if (result.success) {
  432. logMessage('HOME command sent successfully.', LOG_TYPE.SUCCESS);
  433. } else {
  434. logMessage('Failed to send HOME command.', LOG_TYPE.ERROR);
  435. }
  436. }
  437. async function runClearIn() {
  438. await runFile('clear_from_in.thr');
  439. }
  440. async function runClearOut() {
  441. await runFile('clear_from_out.thr');
  442. }
  443. async function runClearSide() {
  444. await runFile('side_wiper.thr');
  445. }
  446. let scrollPosition = 0;
  447. function scrollSelection(direction) {
  448. const container = document.getElementById('clear_selection');
  449. const itemHeight = 50; // Adjust based on CSS height
  450. const maxScroll = container.children.length - 1;
  451. // Update scroll position
  452. scrollPosition += direction;
  453. scrollPosition = Math.max(0, Math.min(scrollPosition, maxScroll));
  454. // Update the transform to scroll items
  455. container.style.transform = `translateY(-${scrollPosition * itemHeight}px)`;
  456. setCookie('clear_action_index', scrollPosition, 365);
  457. }
  458. function executeClearAction(actionFunction) {
  459. // Save the new action to a cookie (optional)
  460. setCookie('clear_action', actionFunction, 365);
  461. if (actionFunction && typeof window[actionFunction] === 'function') {
  462. window[actionFunction](); // Execute the selected clear action
  463. } else {
  464. logMessage('No clear action selected or function not found.', LOG_TYPE.ERROR);
  465. }
  466. }
  467. async function runFile(fileName) {
  468. const response = await fetch(`/run_theta_rho_file/${fileName}`, { method: 'POST' });
  469. const result = await response.json();
  470. if (result.success) {
  471. logMessage(`Running file: ${fileName}`, LOG_TYPE.SUCCESS);
  472. } else {
  473. logMessage(`Failed to run file: ${fileName}`, LOG_TYPE.ERROR);
  474. }
  475. }
  476. // Serial Connection Status
  477. async function checkSerialStatus() {
  478. const response = await fetch('/serial_status');
  479. const status = await response.json();
  480. const statusElement = document.getElementById('serial_status');
  481. const statusHeaderElement = document.getElementById('serial_status_header');
  482. const serialPortsContainer = document.getElementById('serial_ports_container');
  483. const selectElement = document.getElementById('serial_ports');
  484. const connectButton = document.querySelector('button[onclick="connectSerial()"]');
  485. const disconnectButton = document.querySelector('button[onclick="disconnectSerial()"]');
  486. const restartButton = document.querySelector('button[onclick="restartSerial()"]');
  487. if (status.connected) {
  488. const port = status.port || 'Unknown'; // Fallback if port is undefined
  489. statusElement.textContent = `Connected to ${port}`;
  490. statusElement.classList.add('connected');
  491. statusElement.classList.remove('not-connected');
  492. logMessage(`Reconnected to serial port: ${port}`);
  493. // Update header status
  494. statusHeaderElement.classList.add('connected');
  495. statusHeaderElement.classList.remove('not-connected');
  496. // Hide Available Ports and show disconnect/restart buttons
  497. serialPortsContainer.style.display = 'none';
  498. connectButton.style.display = 'none';
  499. disconnectButton.style.display = 'flex';
  500. restartButton.style.display = 'flex';
  501. // Preselect the connected port in the dropdown
  502. const newOption = document.createElement('option');
  503. newOption.value = port;
  504. newOption.textContent = port;
  505. selectElement.appendChild(newOption);
  506. selectElement.value = port;
  507. } else {
  508. statusElement.textContent = 'Not connected';
  509. statusElement.classList.add('not-connected');
  510. statusElement.classList.remove('connected');
  511. logMessage('No active serial connection.');
  512. // Update header status
  513. statusHeaderElement.classList.add('not-connected');
  514. statusHeaderElement.classList.remove('connected');
  515. // Show Available Ports and the connect button
  516. serialPortsContainer.style.display = 'block';
  517. connectButton.style.display = 'flex';
  518. disconnectButton.style.display = 'none';
  519. restartButton.style.display = 'none';
  520. // Attempt to auto-load available ports
  521. await loadSerialPorts();
  522. }
  523. }
  524. async function loadSerialPorts() {
  525. const response = await fetch('/list_serial_ports');
  526. const ports = await response.json();
  527. const select = document.getElementById('serial_ports');
  528. select.innerHTML = '';
  529. ports.forEach(port => {
  530. const option = document.createElement('option');
  531. option.value = port;
  532. option.textContent = port;
  533. select.appendChild(option);
  534. });
  535. logMessage('Serial ports loaded.');
  536. }
  537. async function connectSerial() {
  538. const port = document.getElementById('serial_ports').value;
  539. const response = await fetch('/connect_serial', {
  540. method: 'POST',
  541. headers: { 'Content-Type': 'application/json' },
  542. body: JSON.stringify({ port })
  543. });
  544. const result = await response.json();
  545. if (result.success) {
  546. logMessage(`Connected to serial port: ${port}`, LOG_TYPE.SUCCESS);
  547. // Refresh the status
  548. await checkSerialStatus();
  549. } else {
  550. logMessage(`Error connecting to serial port: ${result.error}`, LOG_TYPE.ERROR);
  551. }
  552. }
  553. async function disconnectSerial() {
  554. const response = await fetch('/disconnect_serial', { method: 'POST' });
  555. const result = await response.json();
  556. if (result.success) {
  557. logMessage('Serial port disconnected.', LOG_TYPE.SUCCESS);
  558. // Refresh the status
  559. await checkSerialStatus();
  560. } else {
  561. logMessage(`Error disconnecting: ${result.error}`, LOG_TYPE.ERROR);
  562. }
  563. }
  564. async function restartSerial() {
  565. const port = document.getElementById('serial_ports').value;
  566. const response = await fetch('/restart_serial', {
  567. method: 'POST',
  568. headers: { 'Content-Type': 'application/json' },
  569. body: JSON.stringify({ port })
  570. });
  571. const result = await response.json();
  572. if (result.success) {
  573. document.getElementById('serial_status').textContent = `Restarted connection to ${port}`;
  574. logMessage('Serial connection restarted.', LOG_TYPE.SUCCESS);
  575. // No need to change visibility for restart
  576. } else {
  577. logMessage(`Error restarting serial connection: ${result.error}`, LOG_TYPE.ERROR);
  578. }
  579. }
  580. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  581. // Firmware / Software Updater
  582. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  583. async function fetchFirmwareInfo(motorType = null) {
  584. const checkButton = document.getElementById("check_updates_button");
  585. const motorTypeElement = document.getElementById("motor_type");
  586. const currentVersionElement = document.getElementById("current_firmware_version");
  587. const newVersionElement = document.getElementById("new_firmware_version");
  588. const motorSelectionDiv = document.getElementById("motor_selection");
  589. const updateButtonElement = document.getElementById("update_firmware_button");
  590. try {
  591. // Disable the button while fetching
  592. checkButton.disabled = true;
  593. checkButton.textContent = "Checking...";
  594. // Prepare fetch options
  595. const options = motorType
  596. ? {
  597. method: "POST",
  598. headers: { "Content-Type": "application/json" },
  599. body: JSON.stringify({ motorType }),
  600. }
  601. : { method: "GET" };
  602. const response = await fetch("/get_firmware_info", options);
  603. const data = await response.json();
  604. if (data.success) {
  605. const { installedVersion, installedType, inoVersion, updateAvailable } = data;
  606. // Handle unknown motor type
  607. if (!installedType || installedType === "Unknown") {
  608. motorSelectionDiv.style.display = "flex"; // Show the dropdown
  609. updateButtonElement.style.display = "none"; // Hide update button
  610. checkButton.style.display = "none";
  611. } else {
  612. // Display motor type
  613. motorTypeElement.textContent = `Type: ${installedType || "Unknown"}`;
  614. // Pre-select the correct motor type in the dropdown
  615. const motorSelect = document.getElementById("manual_motor_type");
  616. if (motorSelect) {
  617. Array.from(motorSelect.options).forEach(option => {
  618. option.selected = option.value === installedType;
  619. });
  620. }
  621. // Display firmware versions
  622. currentVersionElement.textContent = `Current version: ${installedVersion || "Unknown"}`;
  623. if (updateAvailable) {
  624. newVersionElement.textContent = `Latest version: ${inoVersion}`;
  625. updateButtonElement.style.display = "block";
  626. checkButton.style.display = "none";
  627. } else {
  628. newVersionElement.textContent = "You are up to date!";
  629. updateButtonElement.style.display = "none";
  630. checkButton.style.display = "none";
  631. }
  632. }
  633. } else {
  634. logMessage("Could not fetch firmware info.", LOG_TYPE.WARNING);
  635. logMessage(data.error, LOG_TYPE.DEBUG);
  636. }
  637. } catch (error) {
  638. logMessage("Could not fetch firmware info.", LOG_TYPE.WARNING);
  639. logMessage(error.message, LOG_TYPE.DEBUG);
  640. } finally {
  641. // Re-enable the button after fetching
  642. checkButton.disabled = false;
  643. checkButton.textContent = "Check for Updates";
  644. }
  645. }
  646. function setMotorType() {
  647. const selectElement = document.getElementById("manual_motor_type");
  648. const selectedMotorType = selectElement.value;
  649. if (!selectedMotorType) {
  650. logMessage("Please select a motor type before proceeding.", LOG_TYPE.WARNING);
  651. return;
  652. }
  653. const motorSelectionDiv = document.getElementById("motor_selection");
  654. motorSelectionDiv.style.display = "none";
  655. // Call fetchFirmwareInfo with the selected motor type
  656. fetchFirmwareInfo(selectedMotorType);
  657. }
  658. async function updateFirmware() {
  659. const button = document.getElementById("update_firmware_button");
  660. const motorTypeDropdown = document.getElementById("manual_motor_type");
  661. const motorType = motorTypeDropdown ? motorTypeDropdown.value : null;
  662. if (!motorType) {
  663. logMessage("Motor type is not set. Please select a motor type.", LOG_TYPE.WARNING);
  664. return;
  665. }
  666. button.disabled = true;
  667. button.textContent = "Updating...";
  668. try {
  669. logMessage("Firmware update started...", LOG_TYPE.INFO);
  670. const response = await fetch("/flash_firmware", {
  671. method: "POST",
  672. headers: { "Content-Type": "application/json" },
  673. body: JSON.stringify({ motorType }),
  674. });
  675. const data = await response.json();
  676. if (data.success) {
  677. logMessage("Firmware updated successfully!", LOG_TYPE.SUCCESS);
  678. // Refresh the firmware info to update current version
  679. logMessage("Refreshing firmware info...");
  680. await fetchFirmwareInfo();
  681. // Display "You're up to date" message if versions match
  682. const newVersionElement = document.getElementById("new_firmware_version");
  683. const currentVersionElement = document.getElementById("current_firmware_version");
  684. currentVersionElement.textContent = newVersionElement.innerHTML
  685. newVersionElement.textContent = "You are up to date!";
  686. const motorSelectionDiv = document.getElementById("motor_selection");
  687. motorSelectionDiv.style.display = "none";
  688. } else {
  689. logMessage(`Firmware update failed: ${data.error}`, LOG_TYPE.ERROR);
  690. }
  691. } catch (error) {
  692. logMessage(`Error during firmware update: ${error.message}`, LOG_TYPE.ERROR);
  693. } finally {
  694. button.disabled = false; // Re-enable button
  695. button.textContent = "Update Firmware";
  696. }
  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 to run.");
  820. return;
  821. }
  822. const pauseTimeInput = document.getElementById('pause_time').value;
  823. const clearPatternSelect = 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. const startTimeInput = document.getElementById('start_time').value.trim();
  827. const endTimeInput = document.getElementById('end_time').value.trim();
  828. const pauseTime = parseFloat(pauseTimeInput);
  829. if (isNaN(pauseTime) || pauseTime < 0) {
  830. logMessage("Invalid pause time. Please enter a non-negative number.", LOG_TYPE.WARNING);
  831. return;
  832. }
  833. // Validate start and end time format and logic
  834. let startTime = startTimeInput || null;
  835. let endTime = endTimeInput || null;
  836. // Ensure that if one time is filled, the other must be as well
  837. if ((startTime && !endTime) || (!startTime && endTime)) {
  838. logMessage("Both start and end times must be provided together or left blank.", LOG_TYPE.WARNING);
  839. return;
  840. }
  841. // If both are provided, validate format and ensure start_time < end_time
  842. if (startTime && endTime) {
  843. try {
  844. const startDateTime = new Date(`1970-01-01T${startTime}:00`);
  845. const endDateTime = new Date(`1970-01-01T${endTime}:00`);
  846. if (isNaN(startDateTime.getTime()) || isNaN(endDateTime.getTime())) {
  847. logMessage("Invalid time format. Please use HH:MM format (e.g., 09:30).", LOG_TYPE.WARNING);
  848. return;
  849. }
  850. if (startDateTime >= endDateTime) {
  851. logMessage("Start time must be earlier than end time.", LOG_TYPE.WARNING);
  852. return;
  853. }
  854. } catch (error) {
  855. logMessage("Error parsing start or end time. Ensure correct HH:MM format.", LOG_TYPE.ERROR);
  856. return;
  857. }
  858. }
  859. logMessage(`Running playlist: ${playlistName} with pause_time=${pauseTime}, clear_pattern=${clearPatternSelect}, run_mode=${runMode}, shuffle=${shuffle}.`);
  860. try {
  861. const response = await fetch('/run_playlist', {
  862. method: 'POST',
  863. headers: { 'Content-Type': 'application/json' },
  864. body: JSON.stringify({
  865. playlist_name: playlistName,
  866. pause_time: pauseTime,
  867. clear_pattern: clearPatternSelect,
  868. run_mode: runMode,
  869. shuffle: shuffle,
  870. start_time: startTimeInput,
  871. end_time: endTimeInput
  872. })
  873. });
  874. const result = await response.json();
  875. if (result.success) {
  876. logMessage(`Playlist "${playlistName}" is now running.`, LOG_TYPE.SUCCESS);
  877. } else {
  878. logMessage(`Failed to run playlist "${playlistName}": ${result.error}`, LOG_TYPE.ERROR);
  879. }
  880. } catch (error) {
  881. logMessage(`Error running playlist "${playlistName}": ${error.message}`, LOG_TYPE.ERROR);
  882. }
  883. }
  884. // Track changes in the playlist
  885. let originalPlaylist = [];
  886. let isPlaylistChanged = false;
  887. // Load playlist and set the original state
  888. async function loadPlaylist(playlistName) {
  889. try {
  890. logMessage(`Loading playlist: ${playlistName}`);
  891. const response = await fetch(`/get_playlist?name=${encodeURIComponent(playlistName)}`);
  892. const data = await response.json();
  893. if (!data.name) {
  894. throw new Error('Playlist name is missing in the response.');
  895. }
  896. // Populate playlist items and set original state
  897. playlist = data.files || [];
  898. originalPlaylist = [...playlist]; // Clone the playlist as the original
  899. isPlaylistChanged = false; // Reset change tracking
  900. toggleSaveCancelButtons(false); // Hide the save and cancel buttons initially
  901. refreshPlaylistUI();
  902. logMessage(`Loaded playlist: "${playlistName}" with ${playlist.length} file(s).`);
  903. } catch (err) {
  904. logMessage(`Error loading playlist: ${err.message}`, LOG_TYPE.ERROR);
  905. console.error('Error details:', err);
  906. }
  907. }
  908. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  909. // PART B: Creating or Saving (Overwriting) a Playlist
  910. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  911. // Instead of separate create/modify functions, we’ll unify them:
  912. async function savePlaylist() {
  913. const name = document.getElementById('playlist_name_display').textContent
  914. if (!name) {
  915. logMessage("Please enter a playlist name.");
  916. return;
  917. }
  918. if (playlist.length === 0) {
  919. logMessage("No files in this playlist. Add files first.");
  920. return;
  921. }
  922. logMessage(`Saving playlist "${name}" with ${playlist.length} file(s)...`);
  923. try {
  924. // We can use /create_playlist or /modify_playlist. They do roughly the same in our single-file approach.
  925. // Let's use /create_playlist to always overwrite or create anew.
  926. const response = await fetch('/create_playlist', {
  927. method: 'POST',
  928. headers: { 'Content-Type': 'application/json' },
  929. body: JSON.stringify({
  930. name: name,
  931. files: playlist
  932. })
  933. });
  934. const result = await response.json();
  935. if (result.success) {
  936. logMessage(`Playlist "${name}" with ${playlist.length} patterns saved`, LOG_TYPE.SUCCESS);
  937. // Reload the entire list of playlists to reflect changes
  938. // Check for changes and refresh the UI
  939. detectPlaylistChanges();
  940. refreshPlaylistUI();
  941. // Restore default action buttons
  942. toggleSaveCancelButtons(false);
  943. } else {
  944. logMessage(`Failed to save playlist: ${result.error}`, LOG_TYPE.ERROR);
  945. }
  946. } catch (err) {
  947. logMessage(`Error saving playlist: ${err}`);
  948. }
  949. }
  950. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  951. // PART C: Renaming and Deleting a playlist
  952. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  953. // Toggle the rename playlist input
  954. function populatePlaylistDropdown() {
  955. return fetch('/list_all_playlists')
  956. .then(response => response.json())
  957. .then(playlists => {
  958. const select = document.getElementById('select-playlist');
  959. select.innerHTML = ''; // Clear existing options
  960. // Retrieve the saved playlist from the cookie
  961. const savedPlaylist = getCookie('selected_playlist');
  962. // Check if there are playlists available
  963. if (playlists.length === 0) {
  964. // Add a placeholder option if no playlists are available
  965. const placeholderOption = document.createElement('option');
  966. placeholderOption.value = '';
  967. placeholderOption.textContent = 'No playlists available';
  968. placeholderOption.disabled = true; // Prevent selection
  969. placeholderOption.selected = true; // Set as default
  970. select.appendChild(placeholderOption);
  971. return;
  972. }
  973. playlists.forEach(playlist => {
  974. const option = document.createElement('option');
  975. option.value = playlist;
  976. option.textContent = playlist;
  977. // Mark the saved playlist as selected
  978. if (playlist === savedPlaylist) {
  979. option.selected = true;
  980. }
  981. select.appendChild(option);
  982. });
  983. // Attach the onchange event listener after populating the dropdown
  984. select.addEventListener('change', function () {
  985. const selectedPlaylist = this.value;
  986. setCookie('selected_playlist', selectedPlaylist, 365); // Save to cookie
  987. logMessage(`Selected playlist saved: ${selectedPlaylist}`);
  988. });
  989. logMessage('Playlist dropdown populated, event listener attached, and saved playlist restored.');
  990. })
  991. .catch(error => logMessage(`Error fetching playlists: ${error.message}`));
  992. }
  993. populatePlaylistDropdown().then(() => {
  994. loadSettingsFromCookies(); // Restore selected playlist after populating the dropdown
  995. });
  996. // Confirm and save the renamed playlist
  997. async function confirmAddPlaylist() {
  998. const playlistNameInput = document.getElementById('new_playlist_name');
  999. const playlistName = playlistNameInput.value.trim();
  1000. if (!playlistName) {
  1001. logMessage('Playlist name cannot be empty.', LOG_TYPE.ERROR);
  1002. return;
  1003. }
  1004. try {
  1005. logMessage(`Adding new playlist: "${playlistName}"...`);
  1006. const response = await fetch('/create_playlist', {
  1007. method: 'POST',
  1008. headers: { 'Content-Type': 'application/json' },
  1009. body: JSON.stringify({
  1010. name: playlistName,
  1011. files: [] // New playlist starts empty
  1012. })
  1013. });
  1014. const result = await response.json();
  1015. if (result.success) {
  1016. logMessage(`Playlist "${playlistName}" created successfully.`, LOG_TYPE.SUCCESS);
  1017. // Clear the input field
  1018. playlistNameInput.value = '';
  1019. // Refresh the playlist list
  1020. loadAllPlaylists();
  1021. populatePlaylistDropdown();
  1022. // Hide the add playlist container
  1023. toggleSecondaryButtons('add-playlist-container');
  1024. } else {
  1025. logMessage(`Failed to create playlist: ${result.error}`, LOG_TYPE.ERROR);
  1026. }
  1027. } catch (error) {
  1028. logMessage(`Error creating playlist: ${error.message}`);
  1029. }
  1030. }
  1031. async function confirmRenamePlaylist() {
  1032. const newName = document.getElementById('playlist_name_input').value.trim();
  1033. const currentName = document.getElementById('playlist_name_display').textContent;
  1034. if (!newName) {
  1035. logMessage("New playlist name cannot be empty.", LOG_TYPE.ERROR);
  1036. return;
  1037. }
  1038. if (newName === currentName) {
  1039. logMessage("New playlist name is the same as the current name. No changes made.", LOG_TYPE.WARNING);
  1040. toggleSecondaryButtons('rename-playlist-container'); // Close the rename container
  1041. return;
  1042. }
  1043. try {
  1044. // Step 1: Create/Modify the playlist with the new name
  1045. const createResponse = await fetch('/modify_playlist', {
  1046. method: 'POST',
  1047. headers: { 'Content-Type': 'application/json' },
  1048. body: JSON.stringify({
  1049. name: newName,
  1050. files: playlist // Ensure `playlist` contains the current list of files
  1051. })
  1052. });
  1053. const createResult = await createResponse.json();
  1054. if (createResult.success) {
  1055. logMessage(createResult.message, LOG_TYPE.SUCCESS);
  1056. // Step 2: Delete the old playlist
  1057. const deleteResponse = await fetch('/delete_playlist', {
  1058. method: 'DELETE',
  1059. headers: { 'Content-Type': 'application/json' },
  1060. body: JSON.stringify({ name: currentName })
  1061. });
  1062. const deleteResult = await deleteResponse.json();
  1063. if (deleteResult.success) {
  1064. logMessage(deleteResult.message);
  1065. // Update the UI with the new name
  1066. document.getElementById('playlist_name_display').textContent = newName;
  1067. // Refresh playlists list
  1068. loadAllPlaylists();
  1069. // Close the rename container and restore original action buttons
  1070. toggleSecondaryButtons('rename-playlist-container');
  1071. } else {
  1072. logMessage(`Failed to delete old playlist: ${deleteResult.error}`, LOG_TYPE.ERROR);
  1073. }
  1074. } else {
  1075. logMessage(`Failed to rename playlist: ${createResult.error}`, LOG_TYPE.ERROR);
  1076. }
  1077. } catch (error) {
  1078. logMessage(`Error renaming playlist: ${error.message}`);
  1079. }
  1080. }
  1081. // Delete the currently opened playlist
  1082. async function deleteCurrentPlaylist() {
  1083. const playlistName = document.getElementById('playlist_name_display').textContent;
  1084. if (!confirm(`Are you sure you want to delete the playlist "${playlistName}"? This action cannot be undone.`)) {
  1085. return;
  1086. }
  1087. try {
  1088. const response = await fetch('/delete_playlist', {
  1089. method: 'DELETE',
  1090. headers: { 'Content-Type': 'application/json' },
  1091. body: JSON.stringify({ name: playlistName })
  1092. });
  1093. const result = await response.json();
  1094. if (result.success) {
  1095. logMessage(`Playlist "${playlistName}" deleted.`, LOG_TYPE.INFO);
  1096. closeStickySection('playlist-editor');
  1097. loadAllPlaylists();
  1098. populatePlaylistDropdown();
  1099. } else {
  1100. logMessage(`Failed to delete playlist: ${result.error}`, LOG_TYPE.ERROR);
  1101. }
  1102. } catch (error) {
  1103. logMessage(`Error deleting playlist: ${error.message}`);
  1104. }
  1105. }
  1106. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1107. // PART D: Local playlist array UI
  1108. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1109. // Refresh the playlist UI and detect changes
  1110. function refreshPlaylistUI() {
  1111. const ul = document.getElementById('playlist_items');
  1112. if (!ul) {
  1113. logMessage('Error: Playlist container not found');
  1114. return;
  1115. }
  1116. ul.innerHTML = ''; // Clear existing items
  1117. if (playlist.length === 0) {
  1118. // Add a placeholder if the playlist is empty
  1119. const emptyLi = document.createElement('li');
  1120. emptyLi.textContent = 'No items in the playlist.';
  1121. emptyLi.classList.add('empty-placeholder'); // Optional: Add a class for styling
  1122. ul.appendChild(emptyLi);
  1123. return;
  1124. }
  1125. playlist.forEach((file, index) => {
  1126. const li = document.createElement('li');
  1127. // Add filename in a span
  1128. const filenameSpan = document.createElement('span');
  1129. filenameSpan.textContent = file;
  1130. filenameSpan.classList.add('filename'); // Add a class for styling
  1131. li.appendChild(filenameSpan);
  1132. // Move Up button
  1133. const moveUpBtn = document.createElement('button');
  1134. moveUpBtn.innerHTML = '<i class="fa-solid fa-turn-up"></i>'; // Up arrow symbol
  1135. moveUpBtn.classList.add('move-button');
  1136. moveUpBtn.onclick = () => {
  1137. if (index > 0) {
  1138. const temp = playlist[index - 1];
  1139. playlist[index - 1] = playlist[index];
  1140. playlist[index] = temp;
  1141. detectPlaylistChanges(); // Check for changes
  1142. refreshPlaylistUI();
  1143. }
  1144. };
  1145. li.appendChild(moveUpBtn);
  1146. // Move Down button
  1147. const moveDownBtn = document.createElement('button');
  1148. moveDownBtn.innerHTML = '<i class="fa-solid fa-turn-down"></i>'; // Down arrow symbol
  1149. moveDownBtn.classList.add('move-button');
  1150. moveDownBtn.onclick = () => {
  1151. if (index < playlist.length - 1) {
  1152. const temp = playlist[index + 1];
  1153. playlist[index + 1] = playlist[index];
  1154. playlist[index] = temp;
  1155. detectPlaylistChanges(); // Check for changes
  1156. refreshPlaylistUI();
  1157. }
  1158. };
  1159. li.appendChild(moveDownBtn);
  1160. // Remove button
  1161. const removeBtn = document.createElement('button');
  1162. removeBtn.innerHTML = '<i class="fa-solid fa-trash"></i>';
  1163. removeBtn.classList.add('remove-button');
  1164. removeBtn.onclick = () => {
  1165. playlist.splice(index, 1);
  1166. detectPlaylistChanges(); // Check for changes
  1167. refreshPlaylistUI();
  1168. };
  1169. li.appendChild(removeBtn);
  1170. ul.appendChild(li);
  1171. });
  1172. }
  1173. // Toggle the visibility of the save and cancel buttons
  1174. function toggleSaveCancelButtons(show) {
  1175. const actionButtons = document.querySelector('#playlist-editor .action-buttons');
  1176. if (actionButtons) {
  1177. // Show/hide all buttons except Save and Cancel
  1178. actionButtons.querySelectorAll('button:not(.save-cancel)').forEach(button => {
  1179. button.style.display = show ? 'none' : 'flex';
  1180. });
  1181. // Show/hide Save and Cancel buttons
  1182. actionButtons.querySelectorAll('.save-cancel').forEach(button => {
  1183. button.style.display = show ? 'flex' : 'none';
  1184. });
  1185. } else {
  1186. logMessage('Error: Action buttons container not found.', LOG_TYPE.ERROR);
  1187. }
  1188. }
  1189. // Detect changes in the playlist
  1190. function detectPlaylistChanges() {
  1191. isPlaylistChanged = JSON.stringify(originalPlaylist) !== JSON.stringify(playlist);
  1192. toggleSaveCancelButtons(isPlaylistChanged);
  1193. }
  1194. // Toggle the "Add to Playlist" section
  1195. function toggleSecondaryButtons(containerId, onShowCallback = null) {
  1196. const container = document.getElementById(containerId);
  1197. if (!container) {
  1198. logMessage(`Error: Element with ID "${containerId}" not found`);
  1199. return;
  1200. }
  1201. // Find the .action-buttons element preceding the container
  1202. const previousActionButtons = container.previousElementSibling?.classList.contains('action-buttons')
  1203. ? container.previousElementSibling
  1204. : null;
  1205. if (container.classList.contains('hidden')) {
  1206. // Show the container
  1207. container.classList.remove('hidden');
  1208. // Hide the previous .action-buttons element
  1209. if (previousActionButtons) {
  1210. previousActionButtons.style.display = 'none';
  1211. }
  1212. // Optional callback for custom logic when showing the container
  1213. if (onShowCallback) {
  1214. onShowCallback();
  1215. }
  1216. } else {
  1217. // Hide the container
  1218. container.classList.add('hidden');
  1219. // Restore the previous .action-buttons element
  1220. if (previousActionButtons) {
  1221. previousActionButtons.style.display = 'flex';
  1222. }
  1223. }
  1224. }
  1225. // Add the selected pattern to the selected playlist
  1226. async function saveToPlaylist() {
  1227. const playlist = document.getElementById('select-playlist').value;
  1228. if (!playlist) {
  1229. logMessage('No playlist selected.', LOG_TYPE.ERROR);
  1230. return;
  1231. }
  1232. if (!selectedFile) {
  1233. logMessage('No pattern selected to add.', LOG_TYPE.ERROR);
  1234. return;
  1235. }
  1236. try {
  1237. logMessage(`Adding pattern "${selectedFile}" to playlist "${playlist}"...`);
  1238. const response = await fetch('/add_to_playlist', {
  1239. method: 'POST',
  1240. headers: { 'Content-Type': 'application/json' },
  1241. body: JSON.stringify({ playlist_name: playlist, pattern: selectedFile })
  1242. });
  1243. const result = await response.json();
  1244. if (result.success) {
  1245. logMessage(`Pattern "${selectedFile}" successfully added to playlist "${playlist}".`, LOG_TYPE.SUCCESS);
  1246. // Reset the UI state via toggleSecondaryButtons
  1247. toggleSecondaryButtons('add-to-playlist-container', () => {
  1248. const selectPlaylist = document.getElementById('select-playlist');
  1249. selectPlaylist.value = ''; // Clear the selection
  1250. });
  1251. } else {
  1252. logMessage(`Failed to add pattern to playlist: ${result.error}`, LOG_TYPE.ERROR);
  1253. }
  1254. } catch (error) {
  1255. logMessage(`Error adding pattern to playlist: ${error.message}`);
  1256. }
  1257. }
  1258. async function changeSpeed() {
  1259. const speedInput = document.getElementById('speed_input');
  1260. const speed = parseFloat(speedInput.value);
  1261. if (isNaN(speed) || speed <= 0) {
  1262. logMessage('Invalid speed. Please enter a positive number.');
  1263. return;
  1264. }
  1265. logMessage(`Setting speed to: ${speed}...`);
  1266. const response = await fetch('/set_speed', {
  1267. method: 'POST',
  1268. headers: { 'Content-Type': 'application/json' },
  1269. body: JSON.stringify({ speed })
  1270. });
  1271. const result = await response.json();
  1272. if (result.success) {
  1273. document.getElementById('speed_status').textContent = `Current Speed: ${speed}`;
  1274. logMessage(`Speed set to: ${speed}`, LOG_TYPE.SUCCESS);
  1275. } else {
  1276. logMessage(`Failed to set speed: ${result.error}`, LOG_TYPE.ERROR);
  1277. }
  1278. }
  1279. // Function to close any sticky section
  1280. function closeStickySection(sectionId) {
  1281. const section = document.getElementById(sectionId);
  1282. if (section) {
  1283. section.classList.remove('visible');
  1284. section.classList.remove('fullscreen');
  1285. section.classList.add('hidden');
  1286. // Reset the fullscreen button text if it exists
  1287. const fullscreenButton = section.querySelector('.fullscreen-button');
  1288. if (fullscreenButton) {
  1289. fullscreenButton.innerHtml = '<i class="fa-solid fa-compress"></i>'; // Reset to enter fullscreen icon/text
  1290. }
  1291. logMessage(`Closed section: ${sectionId}`);
  1292. if(sectionId === 'playlist-editor') {
  1293. document.querySelectorAll('#all_playlists .playlist-item').forEach(item => {
  1294. item.classList.remove('selected');
  1295. });
  1296. }
  1297. if(sectionId === 'pattern-preview-container') {
  1298. document.querySelectorAll('#theta_rho_files .file-item').forEach(item => {
  1299. item.classList.remove('selected');
  1300. });
  1301. }
  1302. } else {
  1303. logMessage(`Error: Section with ID "${sectionId}" not found`);
  1304. }
  1305. }
  1306. // Function to open any sticky section
  1307. function openStickySection(sectionId) {
  1308. const section = document.getElementById(sectionId);
  1309. if (section) {
  1310. // Toggle the 'open' class
  1311. section.classList.toggle('open');
  1312. } else {
  1313. logMessage(`Error: Section with ID "${sectionId}" not found`);
  1314. }
  1315. }
  1316. function attachFullScreenListeners() {
  1317. // Add event listener to all fullscreen buttons
  1318. document.querySelectorAll('.fullscreen-button').forEach(button => {
  1319. button.addEventListener('click', function () {
  1320. const stickySection = this.closest('.sticky'); // Find the closest sticky section
  1321. if (stickySection) {
  1322. // Close all other sections
  1323. document.querySelectorAll('.sticky:not(#currently-playing-container)').forEach(section => {
  1324. if (section !== stickySection) {
  1325. section.classList.remove('fullscreen');
  1326. section.classList.remove('visible');
  1327. section.classList.add('hidden');
  1328. // Reset the fullscreen button text for other sections
  1329. const otherFullscreenButton = section.querySelector('.fullscreen-button');
  1330. if (otherFullscreenButton) {
  1331. otherFullscreenButton.innerHTML = '<i class="fa-solid fa-expand"></i>'; // Enter fullscreen icon/text
  1332. }
  1333. }
  1334. });
  1335. stickySection.classList.toggle('fullscreen'); // Toggle fullscreen class
  1336. // Update button icon or text
  1337. if (stickySection.classList.contains('fullscreen')) {
  1338. this.innerHTML = '<i class="fa-solid fa-compress"></i>'; // Exit fullscreen icon/text
  1339. } else {
  1340. this.innerHTML = '<i class="fa-solid fa-expand"></i>'; // Enter fullscreen icon/text
  1341. }
  1342. } else {
  1343. console.error('Error: Fullscreen button is not inside a sticky section.');
  1344. }
  1345. });
  1346. });
  1347. }
  1348. let lastPreviewedFile = null; // Track the last previewed file
  1349. async function updateCurrentlyPlaying() {
  1350. try {
  1351. const response = await fetch('/status');
  1352. const data = await response.json();
  1353. const currentlyPlayingSection = document.getElementById('currently-playing-container');
  1354. if (!currentlyPlayingSection) {
  1355. logMessage('Currently Playing section not found.', LOG_TYPE.ERROR);
  1356. return;
  1357. }
  1358. if (data.current_playing_file && !data.stop_requested) {
  1359. const { current_playing_file, execution_progress, pause_requested } = data;
  1360. // Strip './patterns/' prefix from the file name
  1361. const fileName = current_playing_file.replace('./patterns/', '');
  1362. if (!document.body.classList.contains('playing')) {
  1363. closeStickySection('pattern-preview-container')
  1364. }
  1365. // Show "Currently Playing" section
  1366. document.body.classList.add('playing');
  1367. // Update pattern preview only if the file is different
  1368. if (current_playing_file !== lastPreviewedFile) {
  1369. previewPattern(fileName, 'currently-playing-container');
  1370. lastPreviewedFile = current_playing_file; // Update the last previewed file
  1371. }
  1372. // Update the filename display
  1373. const fileNameDisplay = document.getElementById('currently-playing-file');
  1374. if (fileNameDisplay) fileNameDisplay.textContent = fileName;
  1375. // Update progress bar
  1376. const progressBar = document.getElementById('play_progress');
  1377. const progressText = document.getElementById('play_progress_text');
  1378. if (execution_progress) {
  1379. const progressPercentage =
  1380. (execution_progress[0] / execution_progress[1]) * 100;
  1381. progressBar.value = progressPercentage;
  1382. progressText.textContent = `${Math.round(progressPercentage)}%`;
  1383. } else {
  1384. progressBar.value = 0;
  1385. progressText.textContent = '0%';
  1386. }
  1387. // Update play/pause button
  1388. const pausePlayButton = document.getElementById('pausePlayCurrent');
  1389. if (pausePlayButton) pausePlayButton.innerHTML = pause_requested ? '<i class="fa-solid fa-play"></i>' : '<i class="fa-solid fa-pause"></i>';
  1390. } else {
  1391. document.body.classList.remove('playing');
  1392. }
  1393. } catch (error) {
  1394. logMessage(`Error updating "Currently Playing" section: ${error.message}`);
  1395. }
  1396. }
  1397. function toggleSettings() {
  1398. const settingsContainer = document.getElementById('settings-container');
  1399. if (settingsContainer) {
  1400. settingsContainer.classList.toggle('open');
  1401. }
  1402. }
  1403. // Utility function to manage cookies
  1404. function setCookie(name, value, days) {
  1405. const date = new Date();
  1406. date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  1407. document.cookie = `${name}=${value};expires=${date.toUTCString()};path=/`;
  1408. }
  1409. function getCookie(name) {
  1410. const nameEQ = `${name}=`;
  1411. const cookies = document.cookie.split(';');
  1412. for (let i = 0; i < cookies.length; i++) {
  1413. let cookie = cookies[i].trim();
  1414. if (cookie.startsWith(nameEQ)) {
  1415. return cookie.substring(nameEQ.length);
  1416. }
  1417. }
  1418. return null;
  1419. }
  1420. // Save settings to cookies
  1421. function saveSettingsToCookies() {
  1422. // Save the pause time
  1423. const pauseTime = document.getElementById('pause_time').value;
  1424. setCookie('pause_time', pauseTime, 365);
  1425. // Save the clear pattern
  1426. const clearPattern = document.getElementById('clear_pattern').value;
  1427. setCookie('clear_pattern', clearPattern, 365);
  1428. // Save the run mode
  1429. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  1430. setCookie('run_mode', runMode, 365);
  1431. // Save shuffle playlist checkbox state
  1432. const shufflePlaylist = document.getElementById('shuffle_playlist').checked;
  1433. setCookie('shuffle_playlist', shufflePlaylist, 365);
  1434. // Save pre-execution action
  1435. const preExecution = document.getElementById('pre_execution').value;
  1436. setCookie('pre_execution', preExecution, 365);
  1437. // Save start and end times
  1438. const startTime = document.getElementById('start_time').value;
  1439. const endTime = document.getElementById('end_time').value;
  1440. setCookie('start_time', startTime, 365);
  1441. setCookie('end_time', endTime, 365);
  1442. logMessage('Settings saved.');
  1443. }
  1444. // Load settings from cookies
  1445. function loadSettingsFromCookies() {
  1446. // Load the pause time
  1447. const pauseTime = getCookie('pause_time');
  1448. if (pauseTime !== null) {
  1449. document.getElementById('pause_time').value = pauseTime;
  1450. }
  1451. // Load the clear pattern
  1452. const clearPattern = getCookie('clear_pattern');
  1453. if (clearPattern !== null) {
  1454. document.getElementById('clear_pattern').value = clearPattern;
  1455. }
  1456. // Load the run mode
  1457. const runMode = getCookie('run_mode');
  1458. if (runMode !== null) {
  1459. document.querySelector(`input[name="run_mode"][value="${runMode}"]`).checked = true;
  1460. }
  1461. // Load the shuffle playlist checkbox state
  1462. const shufflePlaylist = getCookie('shuffle_playlist');
  1463. if (shufflePlaylist !== null) {
  1464. document.getElementById('shuffle_playlist').checked = shufflePlaylist === 'true';
  1465. }
  1466. // Load the pre-execution action
  1467. const preExecution = getCookie('pre_execution');
  1468. if (preExecution !== null) {
  1469. document.getElementById('pre_execution').value = preExecution;
  1470. }
  1471. // Load start and end times
  1472. const startTime = getCookie('start_time');
  1473. if (startTime !== null) {
  1474. document.getElementById('start_time').value = startTime;
  1475. }
  1476. const endTime = getCookie('end_time');
  1477. if (endTime !== null) {
  1478. document.getElementById('end_time').value = endTime;
  1479. }
  1480. if (startTime && endTime ) {
  1481. document.getElementById('clear_time').style.display = 'block';
  1482. }
  1483. logMessage('Settings loaded from cookies.');
  1484. }
  1485. // Call this function to save settings when a value is changed
  1486. function attachSettingsSaveListeners() {
  1487. // Add event listeners to inputs
  1488. document.getElementById('pause_time').addEventListener('input', saveSettingsToCookies);
  1489. document.getElementById('clear_pattern').addEventListener('change', saveSettingsToCookies);
  1490. document.querySelectorAll('input[name="run_mode"]').forEach(input => {
  1491. input.addEventListener('change', saveSettingsToCookies);
  1492. });
  1493. document.getElementById('shuffle_playlist').addEventListener('change', saveSettingsToCookies);
  1494. document.getElementById('pre_execution').addEventListener('change', saveSettingsToCookies);
  1495. document.getElementById('start_time').addEventListener('change', saveSettingsToCookies);
  1496. document.getElementById('end_time').addEventListener('change', saveSettingsToCookies);
  1497. }
  1498. // Tab switching logic with cookie storage
  1499. function switchTab(tabName) {
  1500. // Store the active tab in a cookie
  1501. setCookie('activeTab', tabName, 365); // Store for 7 days
  1502. // Deactivate all tab content
  1503. document.querySelectorAll('.tab-content').forEach(tab => {
  1504. tab.classList.remove('active');
  1505. });
  1506. // Activate the selected tab content
  1507. const activeTab = document.getElementById(`${tabName}-tab`);
  1508. if (activeTab) {
  1509. activeTab.classList.add('active');
  1510. } else {
  1511. console.error(`Error: Tab "${tabName}" not found.`);
  1512. }
  1513. // Deactivate all nav buttons
  1514. document.querySelectorAll('.bottom-nav .tab-button').forEach(button => {
  1515. button.classList.remove('active');
  1516. });
  1517. // Activate the selected nav button
  1518. const activeNavButton = document.getElementById(`nav-${tabName}`);
  1519. if (activeNavButton) {
  1520. activeNavButton.classList.add('active');
  1521. } else {
  1522. console.error(`Error: Nav button for "${tabName}" not found.`);
  1523. }
  1524. }
  1525. // Initialization
  1526. document.addEventListener('DOMContentLoaded', () => {
  1527. const activeTab = getCookie('activeTab') || 'patterns'; // Default to 'patterns' tab
  1528. switchTab(activeTab); // Load the active tab
  1529. checkSerialStatus(); // Check serial connection status
  1530. loadThetaRhoFiles(); // Load files on page load
  1531. loadAllPlaylists(); // Load all playlists on page load
  1532. attachSettingsSaveListeners(); // Attach event listeners to save changes
  1533. attachFullScreenListeners();
  1534. fetchFirmwareInfo();
  1535. checkForUpdates();
  1536. // Periodically check for currently playing status
  1537. setInterval(updateCurrentlyPlaying, 3000);
  1538. });