main.js 64 KB

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