main.js 63 KB

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