main.js 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723
  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 = "⏸"; // 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 = "▶"; // 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 currentClearAction = 'runClearIn';
  417. function toggleClearDropdown(event) {
  418. event.stopPropagation(); // Prevent the main button click event
  419. const dropdown = document.getElementById('clear_dropdown');
  420. dropdown.style.display = dropdown.style.display === 'none' ? 'block' : 'none';
  421. }
  422. function updateClearAction(label, actionFunction) {
  423. // Update the button label
  424. const clearActionLabel = document.getElementById('clear_action_label');
  425. clearActionLabel.textContent = label;
  426. // Update the current action function
  427. currentClearAction = actionFunction;
  428. // Save the new action to a cookie
  429. setCookie('clear_action', label, 7);
  430. // Close the dropdown
  431. const dropdown = document.getElementById('clear_dropdown');
  432. dropdown.style.display = 'none';
  433. }
  434. function executeClearAction() {
  435. if (currentClearAction && typeof window[currentClearAction] === 'function') {
  436. window[currentClearAction](); // Execute the selected clear action
  437. } else {
  438. logMessage('No clear action selected or function not found.', LOG_TYPE.ERROR);
  439. }
  440. }
  441. // Close the dropdown if clicking outside
  442. document.addEventListener('click', () => {
  443. const dropdown = document.getElementById('clear_dropdown');
  444. if (dropdown) dropdown.style.display = 'none';
  445. });
  446. // Update the clear button's onclick handler to execute the selected action
  447. document.getElementById('clear_button').onclick = () => executeClearAction();
  448. async function runFile(fileName) {
  449. const response = await fetch(`/run_theta_rho_file/${fileName}`, { method: 'POST' });
  450. const result = await response.json();
  451. if (result.success) {
  452. logMessage(`Running file: ${fileName}`, LOG_TYPE.SUCCESS);
  453. } else {
  454. logMessage(`Failed to run file: ${fileName}`, LOG_TYPE.ERROR);
  455. }
  456. }
  457. // Serial Connection Status
  458. async function checkSerialStatus() {
  459. const response = await fetch('/serial_status');
  460. const status = await response.json();
  461. const statusElement = document.getElementById('serial_status');
  462. const statusHeaderElement = document.getElementById('serial_status_header');
  463. const serialPortsContainer = document.getElementById('serial_ports_container');
  464. const selectElement = document.getElementById('serial_ports');
  465. const connectButton = document.querySelector('button[onclick="connectSerial()"]');
  466. const disconnectButton = document.querySelector('button[onclick="disconnectSerial()"]');
  467. const restartButton = document.querySelector('button[onclick="restartSerial()"]');
  468. if (status.connected) {
  469. const port = status.port || 'Unknown'; // Fallback if port is undefined
  470. statusElement.textContent = `Connected to ${port}`;
  471. statusElement.classList.add('connected');
  472. statusElement.classList.remove('not-connected');
  473. logMessage(`Reconnected to serial port: ${port}`);
  474. // Update header status
  475. statusHeaderElement.classList.add('connected');
  476. statusHeaderElement.classList.remove('not-connected');
  477. // Hide Available Ports and show disconnect/restart buttons
  478. serialPortsContainer.style.display = 'none';
  479. connectButton.style.display = 'none';
  480. disconnectButton.style.display = 'inline-block';
  481. restartButton.style.display = 'inline-block';
  482. // Preselect the connected port in the dropdown
  483. const newOption = document.createElement('option');
  484. newOption.value = port;
  485. newOption.textContent = port;
  486. selectElement.appendChild(newOption);
  487. selectElement.value = port;
  488. } else {
  489. statusElement.textContent = 'Not connected';
  490. statusElement.classList.add('not-connected');
  491. statusElement.classList.remove('connected');
  492. logMessage('No active serial connection.');
  493. // Update header status
  494. statusHeaderElement.classList.add('not-connected');
  495. statusHeaderElement.classList.remove('connected');
  496. // Show Available Ports and the connect button
  497. serialPortsContainer.style.display = 'block';
  498. connectButton.style.display = 'inline-block';
  499. disconnectButton.style.display = 'none';
  500. restartButton.style.display = 'none';
  501. // Attempt to auto-load available ports
  502. await loadSerialPorts();
  503. }
  504. }
  505. async function loadSerialPorts() {
  506. const response = await fetch('/list_serial_ports');
  507. const ports = await response.json();
  508. const select = document.getElementById('serial_ports');
  509. select.innerHTML = '';
  510. ports.forEach(port => {
  511. const option = document.createElement('option');
  512. option.value = port;
  513. option.textContent = port;
  514. select.appendChild(option);
  515. });
  516. logMessage('Serial ports loaded.');
  517. }
  518. async function connectSerial() {
  519. const port = document.getElementById('serial_ports').value;
  520. const response = await fetch('/connect_serial', {
  521. method: 'POST',
  522. headers: { 'Content-Type': 'application/json' },
  523. body: JSON.stringify({ port })
  524. });
  525. const result = await response.json();
  526. if (result.success) {
  527. logMessage(`Connected to serial port: ${port}`, LOG_TYPE.SUCCESS);
  528. // Refresh the status
  529. await checkSerialStatus();
  530. } else {
  531. logMessage(`Error connecting to serial port: ${result.error}`, LOG_TYPE.ERROR);
  532. }
  533. }
  534. async function disconnectSerial() {
  535. const response = await fetch('/disconnect_serial', { method: 'POST' });
  536. const result = await response.json();
  537. if (result.success) {
  538. logMessage('Serial port disconnected.', LOG_TYPE.SUCCESS);
  539. // Refresh the status
  540. await checkSerialStatus();
  541. } else {
  542. logMessage(`Error disconnecting: ${result.error}`, LOG_TYPE.ERROR);
  543. }
  544. }
  545. async function restartSerial() {
  546. const port = document.getElementById('serial_ports').value;
  547. const response = await fetch('/restart_serial', {
  548. method: 'POST',
  549. headers: { 'Content-Type': 'application/json' },
  550. body: JSON.stringify({ port })
  551. });
  552. const result = await response.json();
  553. if (result.success) {
  554. document.getElementById('serial_status').textContent = `Restarted connection to ${port}`;
  555. logMessage('Serial connection restarted.', LOG_TYPE.SUCCESS);
  556. // No need to change visibility for restart
  557. } else {
  558. logMessage(`Error restarting serial connection: ${result.error}`, LOG_TYPE.ERROR);
  559. }
  560. }
  561. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  562. // Firmware / Software Updater
  563. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  564. async function fetchFirmwareInfo(motorType = null) {
  565. const checkButton = document.getElementById("check_updates_button");
  566. const motorTypeElement = document.getElementById("motor_type");
  567. const currentVersionElement = document.getElementById("current_firmware_version");
  568. const newVersionElement = document.getElementById("new_firmware_version");
  569. const motorSelectionDiv = document.getElementById("motor_selection");
  570. const updateButtonElement = document.getElementById("update_firmware_button");
  571. try {
  572. // Disable the button while fetching
  573. checkButton.disabled = true;
  574. checkButton.textContent = "Checking...";
  575. // Prepare fetch options
  576. const options = motorType
  577. ? {
  578. method: "POST",
  579. headers: { "Content-Type": "application/json" },
  580. body: JSON.stringify({ motorType }),
  581. }
  582. : { method: "GET" };
  583. const response = await fetch("/get_firmware_info", options);
  584. if (!response.ok) {
  585. throw new Error(`Server responded with status ${response.status}`);
  586. }
  587. const data = await response.json();
  588. if (data.success) {
  589. const { installedVersion, installedType, inoVersion, inoType, updateAvailable } = data;
  590. // Handle unknown motor type
  591. if (!installedType || installedType === "Unknown") {
  592. motorSelectionDiv.style.display = "flex"; // Show the dropdown
  593. updateButtonElement.style.display = "none"; // Hide update button
  594. checkButton.style.display = "none";
  595. } else {
  596. // Display motor type
  597. motorTypeElement.textContent = `Type: ${installedType || "Unknown"}`;
  598. // Pre-select the correct motor type in the dropdown
  599. const motorSelect = document.getElementById("manual_motor_type");
  600. if (motorSelect) {
  601. Array.from(motorSelect.options).forEach(option => {
  602. option.selected = option.value === installedType;
  603. });
  604. }
  605. // Display firmware versions
  606. currentVersionElement.textContent = `Current version: ${installedVersion || "Unknown"}`;
  607. if (updateAvailable) {
  608. newVersionElement.textContent = `New version: ${inoVersion}`;
  609. updateButtonElement.style.display = "block";
  610. checkButton.style.display = "none";
  611. } else {
  612. newVersionElement.textContent = "You are up to date!";
  613. updateButtonElement.style.display = "none";
  614. checkButton.style.display = "none";
  615. }
  616. }
  617. } else {
  618. logMessage("Could not fetch firmware info.", LOG_TYPE.WARNING);
  619. logMessage(data.error, LOG_TYPE.DEBUG);
  620. }
  621. } catch (error) {
  622. logMessage("Could not fetch firmware info.", LOG_TYPE.WARNING);
  623. logMessage(error.message, LOG_TYPE.DEBUG);
  624. } finally {
  625. // Re-enable the button after fetching
  626. checkButton.disabled = false;
  627. checkButton.textContent = "Check for Updates";
  628. }
  629. }
  630. function setMotorType() {
  631. const selectElement = document.getElementById("manual_motor_type");
  632. const selectedMotorType = selectElement.value;
  633. if (!selectedMotorType) {
  634. logMessage("Please select a motor type before proceeding.", LOG_TYPE.WARNING);
  635. return;
  636. }
  637. const motorSelectionDiv = document.getElementById("motor_selection");
  638. motorSelectionDiv.style.display = "none";
  639. // Call fetchFirmwareInfo with the selected motor type
  640. fetchFirmwareInfo(selectedMotorType);
  641. }
  642. async function updateFirmware() {
  643. const button = document.getElementById("update_firmware_button");
  644. const motorTypeDropdown = document.getElementById("manual_motor_type");
  645. const motorType = motorTypeDropdown ? motorTypeDropdown.value : null;
  646. if (!motorType) {
  647. logMessage("Motor type is not set. Please select a motor type.", LOG_TYPE.WARNING);
  648. return;
  649. }
  650. button.disabled = true;
  651. button.textContent = "Updating...";
  652. try {
  653. logMessage("Firmware update started...", LOG_TYPE.INFO);
  654. const response = await fetch("/flash_firmware", {
  655. method: "POST",
  656. headers: { "Content-Type": "application/json" },
  657. body: JSON.stringify({ motorType }),
  658. });
  659. const data = await response.json();
  660. if (data.success) {
  661. logMessage("Firmware updated successfully!", LOG_TYPE.SUCCESS);
  662. // Refresh the firmware info to update current version
  663. logMessage("Refreshing firmware info...");
  664. await fetchFirmwareInfo();
  665. // Display "You're up to date" message if versions match
  666. const newVersionElement = document.getElementById("new_firmware_version");
  667. const currentVersionElement = document.getElementById("current_firmware_version");
  668. currentVersionElement.textContent = newVersionElement.innerHTML
  669. newVersionElement.textContent = "You are up to date!";
  670. const motorSelectionDiv = document.getElementById("motor_selection");
  671. motorSelectionDiv.style.display = "none";
  672. } else {
  673. logMessage(`Firmware update failed: ${data.error}`, LOG_TYPE.ERROR);
  674. }
  675. } catch (error) {
  676. logMessage(`Error during firmware update: ${error.message}`, LOG_TYPE.ERROR);
  677. } finally {
  678. button.disabled = false; // Re-enable button
  679. button.textContent = "Update Firmware";
  680. }
  681. }
  682. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  683. // PART A: Loading / listing playlists from the server
  684. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  685. async function loadAllPlaylists() {
  686. try {
  687. const response = await fetch('/list_all_playlists'); // GET
  688. const allPlaylists = await response.json(); // e.g. ["My Playlist", "Summer", ...]
  689. displayAllPlaylists(allPlaylists);
  690. } catch (err) {
  691. logMessage(`Error loading playlists: ${err}`, LOG_TYPE.ERROR);
  692. }
  693. }
  694. // Function to display all playlists with Load, Run, and Delete buttons
  695. function displayAllPlaylists(playlists) {
  696. const ul = document.getElementById('all_playlists');
  697. ul.innerHTML = ''; // Clear current list
  698. playlists.forEach(playlistName => {
  699. const li = document.createElement('li');
  700. li.textContent = playlistName;
  701. li.classList.add('playlist-item'); // Add a class for styling
  702. // Attach click event to handle selection
  703. li.onclick = () => {
  704. // Remove 'selected' class from all items
  705. document.querySelectorAll('#all_playlists li').forEach(item => {
  706. item.classList.remove('selected');
  707. });
  708. // Add 'selected' class to the clicked item
  709. li.classList.add('selected');
  710. // Open the playlist editor for the selected playlist
  711. openPlaylistEditor(playlistName);
  712. };
  713. ul.appendChild(li);
  714. });
  715. }
  716. // Cancel changes and close the editor
  717. function cancelPlaylistChanges() {
  718. playlist = [...originalPlaylist]; // Revert to the original playlist
  719. isPlaylistChanged = false;
  720. toggleSaveCancelButtons(false); // Hide the save and cancel buttons
  721. refreshPlaylistUI(); // Refresh the UI with the original state
  722. closeStickySection('playlist-editor'); // Close the editor
  723. }
  724. // Open the playlist editor
  725. function openPlaylistEditor(playlistName) {
  726. logMessage(`Opening editor for playlist: ${playlistName}`);
  727. const editorSection = document.getElementById('playlist-editor');
  728. // Update the displayed playlist name
  729. document.getElementById('playlist_name_display').textContent = playlistName;
  730. // Store the current playlist name for renaming
  731. document.getElementById('playlist_name_input').value = playlistName;
  732. editorSection.classList.remove('hidden');
  733. editorSection.classList.add('visible');
  734. loadPlaylist(playlistName);
  735. }
  736. function clearSchedule() {
  737. document.getElementById("start_time").value = "";
  738. document.getElementById("end_time").value = "";
  739. document.getElementById('clear_time').style.display = 'none';
  740. setCookie('start_time', '', 7);
  741. setCookie('end_time', '', 7);
  742. }
  743. // Function to run the selected playlist with specified parameters
  744. async function runPlaylist() {
  745. const playlistName = document.getElementById('playlist_name_display').textContent;
  746. if (!playlistName) {
  747. logMessage("No playlist selected to run.");
  748. return;
  749. }
  750. const pauseTimeInput = document.getElementById('pause_time').value;
  751. const clearPatternSelect = document.getElementById('clear_pattern').value;
  752. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  753. const shuffle = document.getElementById('shuffle_playlist').checked;
  754. const startTimeInput = document.getElementById('start_time').value.trim();
  755. const endTimeInput = document.getElementById('end_time').value.trim();
  756. const pauseTime = parseFloat(pauseTimeInput);
  757. if (isNaN(pauseTime) || pauseTime < 0) {
  758. logMessage("Invalid pause time. Please enter a non-negative number.", LOG_TYPE.WARNING);
  759. return;
  760. }
  761. // Validate start and end time format and logic
  762. let startTime = startTimeInput || null;
  763. let endTime = endTimeInput || null;
  764. // Ensure that if one time is filled, the other must be as well
  765. if ((startTime && !endTime) || (!startTime && endTime)) {
  766. logMessage("Both start and end times must be provided together or left blank.", LOG_TYPE.WARNING);
  767. return;
  768. }
  769. // If both are provided, validate format and ensure start_time < end_time
  770. if (startTime && endTime) {
  771. try {
  772. const startDateTime = new Date(`1970-01-01T${startTime}:00`);
  773. const endDateTime = new Date(`1970-01-01T${endTime}:00`);
  774. if (isNaN(startDateTime.getTime()) || isNaN(endDateTime.getTime())) {
  775. logMessage("Invalid time format. Please use HH:MM format (e.g., 09:30).", LOG_TYPE.WARNING);
  776. return;
  777. }
  778. if (startDateTime >= endDateTime) {
  779. logMessage("Start time must be earlier than end time.", LOG_TYPE.WARNING);
  780. return;
  781. }
  782. } catch (error) {
  783. logMessage("Error parsing start or end time. Ensure correct HH:MM format.", LOG_TYPE.ERROR);
  784. return;
  785. }
  786. }
  787. logMessage(`Running playlist: ${playlistName} with pause_time=${pauseTime}, clear_pattern=${clearPatternSelect}, run_mode=${runMode}, shuffle=${shuffle}.`);
  788. try {
  789. const response = await fetch('/run_playlist', {
  790. method: 'POST',
  791. headers: { 'Content-Type': 'application/json' },
  792. body: JSON.stringify({
  793. playlist_name: playlistName,
  794. pause_time: pauseTime,
  795. clear_pattern: clearPatternSelect,
  796. run_mode: runMode,
  797. shuffle: shuffle,
  798. start_time: startTimeInput,
  799. end_time: endTimeInput
  800. })
  801. });
  802. const result = await response.json();
  803. if (result.success) {
  804. logMessage(`Playlist "${playlistName}" is now running.`, LOG_TYPE.SUCCESS);
  805. } else {
  806. logMessage(`Failed to run playlist "${playlistName}": ${result.error}`, LOG_TYPE.ERROR);
  807. }
  808. } catch (error) {
  809. logMessage(`Error running playlist "${playlistName}": ${error.message}`, LOG_TYPE.ERROR);
  810. }
  811. }
  812. // Track changes in the playlist
  813. let originalPlaylist = [];
  814. let isPlaylistChanged = false;
  815. // Load playlist and set the original state
  816. async function loadPlaylist(playlistName) {
  817. try {
  818. logMessage(`Loading playlist: ${playlistName}`);
  819. const response = await fetch(`/get_playlist?name=${encodeURIComponent(playlistName)}`);
  820. if (!response.ok) {
  821. throw new Error(`HTTP error! Status: ${response.status}`);
  822. }
  823. const data = await response.json();
  824. if (!data.name) {
  825. throw new Error('Playlist name is missing in the response.');
  826. }
  827. // Populate playlist items and set original state
  828. playlist = data.files || [];
  829. originalPlaylist = [...playlist]; // Clone the playlist as the original
  830. isPlaylistChanged = false; // Reset change tracking
  831. toggleSaveCancelButtons(false); // Hide the save and cancel buttons initially
  832. refreshPlaylistUI();
  833. logMessage(`Loaded playlist: "${playlistName}" with ${playlist.length} file(s).`);
  834. } catch (err) {
  835. logMessage(`Error loading playlist: ${err.message}`, LOG_TYPE.ERROR);
  836. console.error('Error details:', err);
  837. }
  838. }
  839. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  840. // PART B: Creating or Saving (Overwriting) a Playlist
  841. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  842. // Instead of separate create/modify functions, we’ll unify them:
  843. async function savePlaylist() {
  844. const name = document.getElementById('playlist_name_display').textContent
  845. if (!name) {
  846. logMessage("Please enter a playlist name.");
  847. return;
  848. }
  849. if (playlist.length === 0) {
  850. logMessage("No files in this playlist. Add files first.");
  851. return;
  852. }
  853. logMessage(`Saving playlist "${name}" with ${playlist.length} file(s)...`);
  854. try {
  855. // We can use /create_playlist or /modify_playlist. They do roughly the same in our single-file approach.
  856. // Let's use /create_playlist to always overwrite or create anew.
  857. const response = await fetch('/create_playlist', {
  858. method: 'POST',
  859. headers: { 'Content-Type': 'application/json' },
  860. body: JSON.stringify({
  861. name: name,
  862. files: playlist
  863. })
  864. });
  865. const result = await response.json();
  866. if (result.success) {
  867. logMessage(`Playlist "${name}" with ${playlist.length} patterns saved`, LOG_TYPE.SUCCESS);
  868. // Reload the entire list of playlists to reflect changes
  869. // Check for changes and refresh the UI
  870. detectPlaylistChanges();
  871. refreshPlaylistUI();
  872. // Restore default action buttons
  873. toggleSaveCancelButtons(false);
  874. } else {
  875. logMessage(`Failed to save playlist: ${result.error}`, LOG_TYPE.ERROR);
  876. }
  877. } catch (err) {
  878. logMessage(`Error saving playlist: ${err}`);
  879. }
  880. }
  881. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  882. // PART C: Renaming and Deleting a playlist
  883. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  884. // Toggle the rename playlist input
  885. function populatePlaylistDropdown() {
  886. return fetch('/list_all_playlists')
  887. .then(response => response.json())
  888. .then(playlists => {
  889. const select = document.getElementById('select-playlist');
  890. select.innerHTML = ''; // Clear existing options
  891. // Retrieve the saved playlist from the cookie
  892. const savedPlaylist = getCookie('selected_playlist');
  893. playlists.forEach(playlist => {
  894. const option = document.createElement('option');
  895. option.value = playlist;
  896. option.textContent = playlist;
  897. // Mark the saved playlist as selected
  898. if (playlist === savedPlaylist) {
  899. option.selected = true;
  900. }
  901. select.appendChild(option);
  902. });
  903. // Attach the onchange event listener after populating the dropdown
  904. select.addEventListener('change', function () {
  905. const selectedPlaylist = this.value;
  906. setCookie('selected_playlist', selectedPlaylist, 7); // Save to cookie
  907. logMessage(`Selected playlist saved: ${selectedPlaylist}`);
  908. });
  909. logMessage('Playlist dropdown populated, event listener attached, and saved playlist restored.');
  910. })
  911. .catch(error => logMessage(`Error fetching playlists: ${error.message}`, LOG_TYPE.ERROR));
  912. }
  913. populatePlaylistDropdown().then(() => {
  914. loadSettingsFromCookies(); // Restore selected playlist after populating the dropdown
  915. });
  916. // Confirm and save the renamed playlist
  917. async function confirmAddPlaylist() {
  918. const playlistNameInput = document.getElementById('new_playlist_name');
  919. const playlistName = playlistNameInput.value.trim();
  920. if (!playlistName) {
  921. logMessage('Playlist name cannot be empty.', LOG_TYPE.ERROR);
  922. return;
  923. }
  924. try {
  925. logMessage(`Adding new playlist: "${playlistName}"...`);
  926. const response = await fetch('/create_playlist', {
  927. method: 'POST',
  928. headers: { 'Content-Type': 'application/json' },
  929. body: JSON.stringify({
  930. name: playlistName,
  931. files: [] // New playlist starts empty
  932. })
  933. });
  934. const result = await response.json();
  935. if (result.success) {
  936. logMessage(`Playlist "${playlistName}" created successfully.`, LOG_TYPE.SUCCESS);
  937. // Clear the input field
  938. playlistNameInput.value = '';
  939. // Refresh the playlist list
  940. loadAllPlaylists();
  941. // Hide the add playlist container
  942. toggleSecondaryButtons('add-playlist-container');
  943. } else {
  944. logMessage(`Failed to create playlist: ${result.error}`, LOG_TYPE.ERROR);
  945. }
  946. } catch (error) {
  947. logMessage(`Error creating playlist: ${error.message}`);
  948. }
  949. }
  950. async function confirmRenamePlaylist() {
  951. const newName = document.getElementById('playlist_name_input').value.trim();
  952. const currentName = document.getElementById('playlist_name_display').textContent;
  953. if (!newName) {
  954. logMessage("New playlist name cannot be empty.", LOG_TYPE.ERROR);
  955. return;
  956. }
  957. if (newName === currentName) {
  958. logMessage("New playlist name is the same as the current name. No changes made.", LOG_TYPE.WARNING);
  959. toggleSecondaryButtons('rename-playlist-container'); // Close the rename container
  960. return;
  961. }
  962. try {
  963. // Step 1: Create/Modify the playlist with the new name
  964. const createResponse = await fetch('/modify_playlist', {
  965. method: 'POST',
  966. headers: { 'Content-Type': 'application/json' },
  967. body: JSON.stringify({
  968. name: newName,
  969. files: playlist // Ensure `playlist` contains the current list of files
  970. })
  971. });
  972. const createResult = await createResponse.json();
  973. if (createResult.success) {
  974. logMessage(createResult.message, LOG_TYPE.SUCCESS);
  975. // Step 2: Delete the old playlist
  976. const deleteResponse = await fetch('/delete_playlist', {
  977. method: 'DELETE',
  978. headers: { 'Content-Type': 'application/json' },
  979. body: JSON.stringify({ name: currentName })
  980. });
  981. const deleteResult = await deleteResponse.json();
  982. if (deleteResult.success) {
  983. logMessage(deleteResult.message);
  984. // Update the UI with the new name
  985. document.getElementById('playlist_name_display').textContent = newName;
  986. // Refresh playlists list
  987. loadAllPlaylists();
  988. // Close the rename container and restore original action buttons
  989. toggleSecondaryButtons('rename-playlist-container');
  990. } else {
  991. logMessage(`Failed to delete old playlist: ${deleteResult.error}`, LOG_TYPE.ERROR);
  992. }
  993. } else {
  994. logMessage(`Failed to rename playlist: ${createResult.error}`, LOG_TYPE.ERROR);
  995. }
  996. } catch (error) {
  997. logMessage(`Error renaming playlist: ${error.message}`);
  998. }
  999. }
  1000. // Delete the currently opened playlist
  1001. async function deleteCurrentPlaylist() {
  1002. const playlistName = document.getElementById('playlist_name_display').textContent;
  1003. if (!confirm(`Are you sure you want to delete the playlist "${playlistName}"? This action cannot be undone.`)) {
  1004. return;
  1005. }
  1006. try {
  1007. const response = await fetch('/delete_playlist', {
  1008. method: 'DELETE',
  1009. headers: { 'Content-Type': 'application/json' },
  1010. body: JSON.stringify({ name: playlistName })
  1011. });
  1012. const result = await response.json();
  1013. if (result.success) {
  1014. logMessage(`Playlist "${playlistName}" deleted.`, LOG_TYPE.INFO);
  1015. closeStickySection('playlist-editor');
  1016. loadAllPlaylists();
  1017. } else {
  1018. logMessage(`Failed to delete playlist: ${result.error}`, LOG_TYPE.ERROR);
  1019. }
  1020. } catch (error) {
  1021. logMessage(`Error deleting playlist: ${error.message}`);
  1022. }
  1023. }
  1024. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1025. // PART D: Local playlist array UI
  1026. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1027. // Refresh the playlist UI and detect changes
  1028. function refreshPlaylistUI() {
  1029. const ul = document.getElementById('playlist_items');
  1030. if (!ul) {
  1031. logMessage('Error: Playlist container not found');
  1032. return;
  1033. }
  1034. ul.innerHTML = ''; // Clear existing items
  1035. if (playlist.length === 0) {
  1036. // Add a placeholder if the playlist is empty
  1037. const emptyLi = document.createElement('li');
  1038. emptyLi.textContent = 'No items in the playlist.';
  1039. emptyLi.classList.add('empty-placeholder'); // Optional: Add a class for styling
  1040. ul.appendChild(emptyLi);
  1041. return;
  1042. }
  1043. playlist.forEach((file, index) => {
  1044. const li = document.createElement('li');
  1045. // Add filename in a span
  1046. const filenameSpan = document.createElement('span');
  1047. filenameSpan.textContent = file;
  1048. filenameSpan.classList.add('filename'); // Add a class for styling
  1049. li.appendChild(filenameSpan);
  1050. // Move Up button
  1051. const moveUpBtn = document.createElement('button');
  1052. moveUpBtn.textContent = '▲'; // Up arrow symbol
  1053. moveUpBtn.classList.add('move-button');
  1054. moveUpBtn.onclick = () => {
  1055. if (index > 0) {
  1056. const temp = playlist[index - 1];
  1057. playlist[index - 1] = playlist[index];
  1058. playlist[index] = temp;
  1059. detectPlaylistChanges(); // Check for changes
  1060. refreshPlaylistUI();
  1061. }
  1062. };
  1063. li.appendChild(moveUpBtn);
  1064. // Move Down button
  1065. const moveDownBtn = document.createElement('button');
  1066. moveDownBtn.textContent = '▼'; // Down arrow symbol
  1067. moveDownBtn.classList.add('move-button');
  1068. moveDownBtn.onclick = () => {
  1069. if (index < playlist.length - 1) {
  1070. const temp = playlist[index + 1];
  1071. playlist[index + 1] = playlist[index];
  1072. playlist[index] = temp;
  1073. detectPlaylistChanges(); // Check for changes
  1074. refreshPlaylistUI();
  1075. }
  1076. };
  1077. li.appendChild(moveDownBtn);
  1078. // Remove button
  1079. const removeBtn = document.createElement('button');
  1080. removeBtn.textContent = '✖';
  1081. removeBtn.classList.add('remove-button');
  1082. removeBtn.onclick = () => {
  1083. playlist.splice(index, 1);
  1084. detectPlaylistChanges(); // Check for changes
  1085. refreshPlaylistUI();
  1086. };
  1087. li.appendChild(removeBtn);
  1088. ul.appendChild(li);
  1089. });
  1090. }
  1091. // Toggle the visibility of the save and cancel buttons
  1092. function toggleSaveCancelButtons(show) {
  1093. const actionButtons = document.querySelector('#playlist-editor .action-buttons');
  1094. if (actionButtons) {
  1095. // Show/hide all buttons except Save and Cancel
  1096. actionButtons.querySelectorAll('button:not(.save-cancel)').forEach(button => {
  1097. button.style.display = show ? 'none' : 'inline-block';
  1098. });
  1099. // Show/hide Save and Cancel buttons
  1100. actionButtons.querySelectorAll('.save-cancel').forEach(button => {
  1101. button.style.display = show ? 'inline-block' : 'none';
  1102. });
  1103. } else {
  1104. logMessage('Error: Action buttons container not found.', LOG_TYPE.ERROR);
  1105. }
  1106. }
  1107. // Detect changes in the playlist
  1108. function detectPlaylistChanges() {
  1109. isPlaylistChanged = JSON.stringify(originalPlaylist) !== JSON.stringify(playlist);
  1110. toggleSaveCancelButtons(isPlaylistChanged);
  1111. }
  1112. // Toggle the "Add to Playlist" section
  1113. function toggleSecondaryButtons(containerId, onShowCallback = null) {
  1114. const container = document.getElementById(containerId);
  1115. if (!container) {
  1116. logMessage(`Error: Element with ID "${containerId}" not found`);
  1117. return;
  1118. }
  1119. // Find the .action-buttons element preceding the container
  1120. const previousActionButtons = container.previousElementSibling?.classList.contains('action-buttons')
  1121. ? container.previousElementSibling
  1122. : null;
  1123. if (container.classList.contains('hidden')) {
  1124. // Show the container
  1125. container.classList.remove('hidden');
  1126. // Hide the previous .action-buttons element
  1127. if (previousActionButtons) {
  1128. previousActionButtons.style.display = 'none';
  1129. }
  1130. // Optional callback for custom logic when showing the container
  1131. if (onShowCallback) {
  1132. onShowCallback();
  1133. }
  1134. } else {
  1135. // Hide the container
  1136. container.classList.add('hidden');
  1137. // Restore the previous .action-buttons element
  1138. if (previousActionButtons) {
  1139. previousActionButtons.style.display = 'flex';
  1140. }
  1141. }
  1142. }
  1143. // Add the selected pattern to the selected playlist
  1144. async function saveToPlaylist() {
  1145. const playlist = document.getElementById('select-playlist').value;
  1146. if (!playlist) {
  1147. logMessage('No playlist selected.', LOG_TYPE.ERROR);
  1148. return;
  1149. }
  1150. if (!selectedFile) {
  1151. logMessage('No pattern selected to add.', LOG_TYPE.ERROR);
  1152. return;
  1153. }
  1154. try {
  1155. logMessage(`Adding pattern "${selectedFile}" to playlist "${playlist}"...`);
  1156. const response = await fetch('/add_to_playlist', {
  1157. method: 'POST',
  1158. headers: { 'Content-Type': 'application/json' },
  1159. body: JSON.stringify({ playlist_name: playlist, pattern: selectedFile })
  1160. });
  1161. const result = await response.json();
  1162. if (result.success) {
  1163. logMessage(`Pattern "${selectedFile}" successfully added to playlist "${playlist}".`, LOG_TYPE.SUCCESS);
  1164. // Reset the UI state via toggleSecondaryButtons
  1165. toggleSecondaryButtons('add-to-playlist-container', () => {
  1166. const selectPlaylist = document.getElementById('select-playlist');
  1167. selectPlaylist.value = ''; // Clear the selection
  1168. });
  1169. } else {
  1170. logMessage(`Failed to add pattern to playlist: ${result.error}`, LOG_TYPE.ERROR);
  1171. }
  1172. } catch (error) {
  1173. logMessage(`Error adding pattern to playlist: ${error.message}`);
  1174. }
  1175. }
  1176. async function changeSpeed() {
  1177. const speedInput = document.getElementById('speed_input');
  1178. const speed = parseFloat(speedInput.value);
  1179. if (isNaN(speed) || speed <= 0) {
  1180. logMessage('Invalid speed. Please enter a positive number.');
  1181. return;
  1182. }
  1183. logMessage(`Setting speed to: ${speed}...`);
  1184. const response = await fetch('/set_speed', {
  1185. method: 'POST',
  1186. headers: { 'Content-Type': 'application/json' },
  1187. body: JSON.stringify({ speed })
  1188. });
  1189. const result = await response.json();
  1190. if (result.success) {
  1191. document.getElementById('speed_status').textContent = `Current Speed: ${speed}`;
  1192. logMessage(`Speed set to: ${speed}`, LOG_TYPE.SUCCESS);
  1193. } else {
  1194. logMessage(`Failed to set speed: ${result.error}`, LOG_TYPE.ERROR);
  1195. }
  1196. }
  1197. // Function to close any sticky section
  1198. function closeStickySection(sectionId) {
  1199. const section = document.getElementById(sectionId);
  1200. if (section) {
  1201. section.classList.remove('visible');
  1202. section.classList.remove('fullscreen');
  1203. section.classList.add('hidden');
  1204. // Reset the fullscreen button text if it exists
  1205. const fullscreenButton = section.querySelector('.fullscreen-button');
  1206. if (fullscreenButton) {
  1207. fullscreenButton.textContent = '⛶'; // Reset to enter fullscreen icon/text
  1208. }
  1209. logMessage(`Closed section: ${sectionId}`);
  1210. if(sectionId === 'playlist-editor') {
  1211. document.querySelectorAll('#all_playlists .playlist-item').forEach(item => {
  1212. item.classList.remove('selected');
  1213. });
  1214. }
  1215. if(sectionId === 'pattern-preview-container') {
  1216. document.querySelectorAll('#theta_rho_files .file-item').forEach(item => {
  1217. item.classList.remove('selected');
  1218. });
  1219. }
  1220. } else {
  1221. logMessage(`Error: Section with ID "${sectionId}" not found`);
  1222. }
  1223. }
  1224. function attachFullScreenListeners() {
  1225. // Add event listener to all fullscreen buttons
  1226. document.querySelectorAll('.fullscreen-button').forEach(button => {
  1227. button.addEventListener('click', function () {
  1228. const stickySection = this.closest('.sticky'); // Find the closest sticky section
  1229. if (stickySection) {
  1230. // Close all other sections
  1231. document.querySelectorAll('.sticky').forEach(section => {
  1232. if (section !== stickySection) {
  1233. section.classList.remove('fullscreen');
  1234. section.classList.remove('visible');
  1235. section.classList.add('hidden');
  1236. // Reset the fullscreen button text for other sections
  1237. const otherFullscreenButton = section.querySelector('.fullscreen-button');
  1238. if (otherFullscreenButton) {
  1239. otherFullscreenButton.textContent = '⛶'; // Enter fullscreen icon/text
  1240. }
  1241. }
  1242. });
  1243. stickySection.classList.toggle('fullscreen'); // Toggle fullscreen class
  1244. // Update button icon or text
  1245. if (stickySection.classList.contains('fullscreen')) {
  1246. this.textContent = '-'; // Exit fullscreen icon/text
  1247. } else {
  1248. this.textContent = '⛶'; // Enter fullscreen icon/text
  1249. }
  1250. } else {
  1251. console.error('Error: Fullscreen button is not inside a sticky section.');
  1252. }
  1253. });
  1254. });
  1255. }
  1256. let lastPreviewedFile = null; // Track the last previewed file
  1257. async function updateCurrentlyPlaying() {
  1258. try {
  1259. const response = await fetch('/status');
  1260. const data = await response.json();
  1261. const currentlyPlayingSection = document.getElementById('currently-playing-container');
  1262. if (!currentlyPlayingSection) {
  1263. logMessage('Currently Playing section not found.', LOG_TYPE.ERROR);
  1264. return;
  1265. }
  1266. if (data.current_playing_file) {
  1267. const { current_playing_file, execution_progress, pause_requested } = data;
  1268. // Strip './patterns/' prefix from the file name
  1269. const fileName = current_playing_file.replace('./patterns/', '');
  1270. // Show "Currently Playing" section
  1271. currentlyPlayingSection.classList.remove('hidden');
  1272. currentlyPlayingSection.classList.add('visible');
  1273. // Update pattern preview only if the file is different
  1274. if (current_playing_file !== lastPreviewedFile) {
  1275. previewPattern(fileName, 'currently-playing-container');
  1276. lastPreviewedFile = current_playing_file; // Update the last previewed file
  1277. }
  1278. // Update the filename display
  1279. const fileNameDisplay = document.getElementById('currently-playing-file');
  1280. if (fileNameDisplay) fileNameDisplay.textContent = fileName;
  1281. // Update progress bar
  1282. const progressBar = document.getElementById('play_progress');
  1283. const progressText = document.getElementById('play_progress_text');
  1284. if (execution_progress) {
  1285. const progressPercentage =
  1286. (execution_progress[0] / execution_progress[1]) * 100;
  1287. progressBar.value = progressPercentage;
  1288. progressText.textContent = `${Math.round(progressPercentage)}%`;
  1289. } else {
  1290. progressBar.value = 0;
  1291. progressText.textContent = '0%';
  1292. }
  1293. // Update play/pause button
  1294. const pausePlayButton = document.getElementById('pausePlayCurrent');
  1295. if (pausePlayButton) pausePlayButton.textContent = pause_requested ? '▶' : '⏸';
  1296. } else {
  1297. logMessage('No file is currently playing.');
  1298. hideCurrentlyPlaying();
  1299. }
  1300. } catch (error) {
  1301. logMessage(`Error updating "Currently Playing" section: ${error.message}`, LOG_TYPE.ERROR);
  1302. }
  1303. }
  1304. function hideCurrentlyPlaying() {
  1305. const currentlyPlayingSection = document.getElementById('currently-playing-container');
  1306. currentlyPlayingSection.classList.add('hidden');
  1307. currentlyPlayingSection.classList.remove('visible');
  1308. }
  1309. // Utility function to manage cookies
  1310. function setCookie(name, value, days) {
  1311. const date = new Date();
  1312. date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  1313. document.cookie = `${name}=${value};expires=${date.toUTCString()};path=/`;
  1314. }
  1315. function getCookie(name) {
  1316. const nameEQ = `${name}=`;
  1317. const cookies = document.cookie.split(';');
  1318. for (let i = 0; i < cookies.length; i++) {
  1319. let cookie = cookies[i].trim();
  1320. if (cookie.startsWith(nameEQ)) {
  1321. return cookie.substring(nameEQ.length);
  1322. }
  1323. }
  1324. return null;
  1325. }
  1326. // Save settings to cookies
  1327. function saveSettingsToCookies() {
  1328. // Save the pause time
  1329. const pauseTime = document.getElementById('pause_time').value;
  1330. setCookie('pause_time', pauseTime, 7);
  1331. // Save the clear pattern
  1332. const clearPattern = document.getElementById('clear_pattern').value;
  1333. setCookie('clear_pattern', clearPattern, 7);
  1334. // Save the run mode
  1335. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  1336. setCookie('run_mode', runMode, 7);
  1337. // Save shuffle playlist checkbox state
  1338. const shufflePlaylist = document.getElementById('shuffle_playlist').checked;
  1339. setCookie('shuffle_playlist', shufflePlaylist, 7);
  1340. // Save pre-execution action
  1341. const preExecution = document.getElementById('pre_execution').value;
  1342. setCookie('pre_execution', preExecution, 7);
  1343. // Save selected clear action
  1344. const clearAction = document.getElementById('clear_action_label').textContent.trim();
  1345. setCookie('clear_action', clearAction, 7);
  1346. // Save start and end times
  1347. const startTime = document.getElementById('start_time').value;
  1348. const endTime = document.getElementById('end_time').value;
  1349. setCookie('start_time', startTime, 7);
  1350. setCookie('end_time', endTime, 7);
  1351. logMessage('Settings saved.');
  1352. }
  1353. // Load settings from cookies
  1354. function loadSettingsFromCookies() {
  1355. // Load the pause time
  1356. const pauseTime = getCookie('pause_time');
  1357. if (pauseTime !== null) {
  1358. document.getElementById('pause_time').value = pauseTime;
  1359. }
  1360. // Load the clear pattern
  1361. const clearPattern = getCookie('clear_pattern');
  1362. if (clearPattern !== null) {
  1363. document.getElementById('clear_pattern').value = clearPattern;
  1364. }
  1365. // Load the run mode
  1366. const runMode = getCookie('run_mode');
  1367. if (runMode !== null) {
  1368. document.querySelector(`input[name="run_mode"][value="${runMode}"]`).checked = true;
  1369. }
  1370. // Load the shuffle playlist checkbox state
  1371. const shufflePlaylist = getCookie('shuffle_playlist');
  1372. if (shufflePlaylist !== null) {
  1373. document.getElementById('shuffle_playlist').checked = shufflePlaylist === 'true';
  1374. }
  1375. // Load the pre-execution action
  1376. const preExecution = getCookie('pre_execution');
  1377. if (preExecution !== null) {
  1378. document.getElementById('pre_execution').value = preExecution;
  1379. }
  1380. // Load selected clear action
  1381. const clearAction = getCookie('clear_action');
  1382. if (clearAction !== null) {
  1383. const clearLabel = document.getElementById('clear_action_label');
  1384. clearLabel.textContent = clearAction;
  1385. // Update the corresponding action function
  1386. if (clearAction === 'From Center') {
  1387. currentClearAction = 'runClearIn';
  1388. } else if (clearAction === 'From Perimeter') {
  1389. currentClearAction = 'runClearOut';
  1390. } else if (clearAction === 'Sideways') {
  1391. currentClearAction = 'runClearSide';
  1392. }
  1393. }
  1394. // Load start and end times
  1395. const startTime = getCookie('start_time');
  1396. if (startTime !== null) {
  1397. document.getElementById('start_time').value = startTime;
  1398. }
  1399. const endTime = getCookie('end_time');
  1400. if (endTime !== null) {
  1401. document.getElementById('end_time').value = endTime;
  1402. }
  1403. if (startTime !== null || endTime !== null ) {
  1404. document.getElementById('clear_time').style.display = 'block';
  1405. }
  1406. logMessage('Settings loaded from cookies.');
  1407. }
  1408. // Call this function to save settings when a value is changed
  1409. function attachSettingsSaveListeners() {
  1410. // Add event listeners to inputs
  1411. document.getElementById('pause_time').addEventListener('input', saveSettingsToCookies);
  1412. document.getElementById('clear_pattern').addEventListener('change', saveSettingsToCookies);
  1413. document.querySelectorAll('input[name="run_mode"]').forEach(input => {
  1414. input.addEventListener('change', saveSettingsToCookies);
  1415. });
  1416. document.getElementById('shuffle_playlist').addEventListener('change', saveSettingsToCookies);
  1417. document.getElementById('pre_execution').addEventListener('change', saveSettingsToCookies);
  1418. document.getElementById('start_time').addEventListener('change', saveSettingsToCookies);
  1419. document.getElementById('end_time').addEventListener('change', saveSettingsToCookies);
  1420. }
  1421. // Tab switching logic with cookie storage
  1422. function switchTab(tabName) {
  1423. // Store the active tab in a cookie
  1424. setCookie('activeTab', tabName, 7); // Store for 7 days
  1425. // Deactivate all tab content
  1426. document.querySelectorAll('.tab-content').forEach(tab => {
  1427. tab.classList.remove('active');
  1428. });
  1429. // Activate the selected tab content
  1430. const activeTab = document.getElementById(`${tabName}-tab`);
  1431. if (activeTab) {
  1432. activeTab.classList.add('active');
  1433. } else {
  1434. console.error(`Error: Tab "${tabName}" not found.`);
  1435. }
  1436. // Deactivate all nav buttons
  1437. document.querySelectorAll('.bottom-nav .tab-button').forEach(button => {
  1438. button.classList.remove('active');
  1439. });
  1440. // Activate the selected nav button
  1441. const activeNavButton = document.getElementById(`nav-${tabName}`);
  1442. if (activeNavButton) {
  1443. activeNavButton.classList.add('active');
  1444. } else {
  1445. console.error(`Error: Nav button for "${tabName}" not found.`);
  1446. }
  1447. }
  1448. // Initialization
  1449. document.addEventListener('DOMContentLoaded', () => {
  1450. const activeTab = getCookie('activeTab') || 'patterns'; // Default to 'patterns' tab
  1451. switchTab(activeTab); // Load the active tab
  1452. checkSerialStatus(); // Check serial connection status
  1453. loadThetaRhoFiles(); // Load files on page load
  1454. loadAllPlaylists(); // Load all playlists on page load
  1455. attachSettingsSaveListeners(); // Attach event listeners to save changes
  1456. attachFullScreenListeners();
  1457. fetchFirmwareInfo();
  1458. // Periodically check for currently playing status
  1459. setInterval(updateCurrentlyPlaying, 3000);
  1460. });