main.js 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465
  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';
  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.querySelector('input[name="pre_execution"]:checked').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. function removeCurrentPattern() {
  207. if (!selectedFile) {
  208. logMessage('No file selected to remove.', LOG_TYPE.ERROR);
  209. return;
  210. }
  211. if (!selectedFile.startsWith('custom_patterns/')) {
  212. logMessage('Only custom patterns can be removed.', LOG_TYPE.WARNING);
  213. return;
  214. }
  215. removeCustomPattern(selectedFile);
  216. }
  217. // Delete the selected file
  218. async function removeCustomPattern(fileName) {
  219. const userConfirmed = confirm(`Are you sure you want to delete the pattern "${fileName}"?`);
  220. if (!userConfirmed) return;
  221. try {
  222. logMessage(`Deleting pattern: ${fileName}...`);
  223. const response = await fetch('/delete_theta_rho_file', {
  224. method: 'POST',
  225. headers: { 'Content-Type': 'application/json' },
  226. body: JSON.stringify({ file_name: fileName })
  227. });
  228. const result = await response.json();
  229. if (result.success) {
  230. logMessage(`File deleted successfully: ${selectedFile}`, LOG_TYPE.SUCCESS);
  231. // Close the preview container
  232. const previewContainer = document.getElementById('pattern-preview-container');
  233. if (previewContainer) {
  234. previewContainer.classList.add('hidden');
  235. previewContainer.classList.remove('visible');
  236. }
  237. // Clear the selected file and refresh the file list
  238. selectedFile = null;
  239. await loadThetaRhoFiles(); // Refresh the file list
  240. } else {
  241. logMessage(`Failed to delete pattern "${fileName}": ${result.error}`, LOG_TYPE.ERROR);
  242. }
  243. } catch (error) {
  244. logMessage(`Error deleting pattern: ${error.message}`);
  245. }
  246. }
  247. // Preview a Theta-Rho file
  248. async function previewPattern(fileName) {
  249. try {
  250. logMessage(`Fetching data to preview file: ${fileName}...`);
  251. const response = await fetch('/preview_thr', {
  252. method: 'POST',
  253. headers: { 'Content-Type': 'application/json' },
  254. body: JSON.stringify({ file_name: fileName })
  255. });
  256. const result = await response.json();
  257. if (result.success) {
  258. const coordinates = result.coordinates;
  259. renderPattern(coordinates);
  260. // Update coordinate display
  261. const firstCoord = coordinates[0];
  262. const lastCoord = coordinates[coordinates.length - 1];
  263. document.getElementById('first_coordinate').textContent = `First Coordinate: θ=${firstCoord[0]}, ρ=${firstCoord[1]}`;
  264. document.getElementById('last_coordinate').textContent = `Last Coordinate: θ=${lastCoord[0]}, ρ=${lastCoord[1]}`;
  265. // Show the preview container
  266. const previewContainer = document.getElementById('pattern-preview-container');
  267. if (previewContainer) {
  268. previewContainer.classList.remove('hidden');
  269. previewContainer.classList.add('visible');
  270. }
  271. // Close the "Add to Playlist" container if it is open
  272. const addToPlaylistContainer = document.getElementById('add-to-playlist-container');
  273. if (addToPlaylistContainer && !addToPlaylistContainer.classList.contains('hidden')) {
  274. toggleSecondaryButtons('add-to-playlist-container'); // Hide the container
  275. }
  276. } else {
  277. logMessage(`Failed to fetch preview for file: ${fileName}`, LOG_TYPE.WARNING);
  278. }
  279. } catch (error) {
  280. logMessage(`Error previewing pattern: ${error.message}`, LOG_TYPE.WARNING);
  281. }
  282. }
  283. // Render the pattern on a canvas
  284. function renderPattern(coordinates) {
  285. const canvas = document.getElementById('patternPreviewCanvas');
  286. if (!canvas) {
  287. logMessage('Error: Canvas not found');
  288. return;
  289. }
  290. const ctx = canvas.getContext('2d');
  291. // Account for device pixel ratio
  292. const dpr = window.devicePixelRatio || 1;
  293. const rect = canvas.getBoundingClientRect();
  294. canvas.width = rect.width * dpr; // Scale canvas width for high DPI
  295. canvas.height = rect.height * dpr; // Scale canvas height for high DPI
  296. ctx.scale(dpr, dpr); // Scale drawing context
  297. ctx.clearRect(0, 0, canvas.width, canvas.height);
  298. const centerX = rect.width / 2; // Use bounding client rect dimensions
  299. const centerY = rect.height / 2;
  300. const maxRho = Math.max(...coordinates.map(coord => coord[1]));
  301. const scale = Math.min(rect.width, rect.height) / (2 * maxRho); // Scale to fit
  302. ctx.beginPath();
  303. ctx.strokeStyle = 'white';
  304. coordinates.forEach(([theta, rho], index) => {
  305. const x = centerX + rho * Math.cos(theta) * scale;
  306. const y = centerY - rho * Math.sin(theta) * scale;
  307. if (index === 0) ctx.moveTo(x, y);
  308. else ctx.lineTo(x, y);
  309. });
  310. ctx.stroke();
  311. logMessage('Pattern preview rendered.');
  312. }
  313. async function moveToCenter() {
  314. logMessage('Moving to center...', LOG_TYPE.INFO);
  315. const response = await fetch('/move_to_center', { method: 'POST' });
  316. const result = await response.json();
  317. if (result.success) {
  318. logMessage('Moved to center successfully.', LOG_TYPE.SUCCESS);
  319. } else {
  320. logMessage(`Failed to move to center: ${result.error}`, LOG_TYPE.ERROR);
  321. }
  322. }
  323. async function moveToPerimeter() {
  324. logMessage('Moving to perimeter...', LOG_TYPE.INFO);
  325. const response = await fetch('/move_to_perimeter', { method: 'POST' });
  326. const result = await response.json();
  327. if (result.success) {
  328. logMessage('Moved to perimeter successfully.', LOG_TYPE.SUCCESS);
  329. } else {
  330. logMessage(`Failed to move to perimeter: ${result.error}`, LOG_TYPE.ERROR);
  331. }
  332. }
  333. async function sendCoordinate() {
  334. const theta = parseFloat(document.getElementById('theta_input').value);
  335. const rho = parseFloat(document.getElementById('rho_input').value);
  336. if (isNaN(theta) || isNaN(rho)) {
  337. logMessage('Invalid input: θ and ρ must be numbers.', LOG_TYPE.ERROR);
  338. return;
  339. }
  340. logMessage(`Sending coordinate: θ=${theta}, ρ=${rho}...`);
  341. const response = await fetch('/send_coordinate', {
  342. method: 'POST',
  343. headers: { 'Content-Type': 'application/json' },
  344. body: JSON.stringify({ theta, rho })
  345. });
  346. const result = await response.json();
  347. if (result.success) {
  348. logMessage(`Coordinate executed successfully: θ=${theta}, ρ=${rho}`, LOG_TYPE.SUCCESS);
  349. } else {
  350. logMessage(`Failed to execute coordinate: ${result.error}`, LOG_TYPE.ERROR);
  351. }
  352. }
  353. async function sendHomeCommand() {
  354. const response = await fetch('/send_home', { method: 'POST' });
  355. const result = await response.json();
  356. if (result.success) {
  357. logMessage('HOME command sent successfully.', LOG_TYPE.SUCCESS);
  358. } else {
  359. logMessage('Failed to send HOME command.', LOG_TYPE.ERROR);
  360. }
  361. }
  362. async function runClearIn() {
  363. await runFile('clear_from_in.thr');
  364. }
  365. async function runClearOut() {
  366. await runFile('clear_from_out.thr');
  367. }
  368. async function runFile(fileName) {
  369. const response = await fetch(`/run_theta_rho_file/${fileName}`, { method: 'POST' });
  370. const result = await response.json();
  371. if (result.success) {
  372. logMessage(`Running file: ${fileName}`, LOG_TYPE.SUCCESS);
  373. } else {
  374. logMessage(`Failed to run file: ${fileName}`, LOG_TYPE.ERROR);
  375. }
  376. }
  377. // Serial Connection Status
  378. async function checkSerialStatus() {
  379. const response = await fetch('/serial_status');
  380. const status = await response.json();
  381. const statusElement = document.getElementById('serial_status');
  382. const statusHeaderElement = document.getElementById('serial_status_header');
  383. const serialPortsContainer = document.getElementById('serial_ports_container');
  384. const connectButton = document.querySelector('button[onclick="connectSerial()"]');
  385. const disconnectButton = document.querySelector('button[onclick="disconnectSerial()"]');
  386. const restartButton = document.querySelector('button[onclick="restartSerial()"]');
  387. if (status.connected) {
  388. const port = status.port || 'Unknown'; // Fallback if port is undefined
  389. statusElement.textContent = `Connected to ${port}`;
  390. statusElement.classList.add('connected');
  391. statusElement.classList.remove('not-connected');
  392. logMessage(`Reconnected to serial port: ${port}`);
  393. // Update header status
  394. statusHeaderElement.classList.add('connected');
  395. statusHeaderElement.classList.remove('not-connected');
  396. // Hide Available Ports and show disconnect/restart buttons
  397. serialPortsContainer.style.display = 'none';
  398. connectButton.style.display = 'none';
  399. disconnectButton.style.display = 'inline-block';
  400. restartButton.style.display = 'inline-block';
  401. } else {
  402. statusElement.textContent = 'Not connected';
  403. statusElement.classList.add('not-connected');
  404. statusElement.classList.remove('connected');
  405. logMessage('No active serial connection.');
  406. // Update header status
  407. statusHeaderElement.classList.add('not-connected');
  408. statusHeaderElement.classList.remove('connected');
  409. // Show Available Ports and the connect button
  410. serialPortsContainer.style.display = 'block';
  411. connectButton.style.display = 'inline-block';
  412. disconnectButton.style.display = 'none';
  413. restartButton.style.display = 'none';
  414. // Attempt to auto-load available ports
  415. await loadSerialPorts();
  416. }
  417. }
  418. async function loadSerialPorts() {
  419. const response = await fetch('/list_serial_ports');
  420. const ports = await response.json();
  421. const select = document.getElementById('serial_ports');
  422. select.innerHTML = '';
  423. ports.forEach(port => {
  424. const option = document.createElement('option');
  425. option.value = port;
  426. option.textContent = port;
  427. select.appendChild(option);
  428. });
  429. logMessage('Serial ports loaded.');
  430. }
  431. async function connectSerial() {
  432. const port = document.getElementById('serial_ports').value;
  433. const response = await fetch('/connect_serial', {
  434. method: 'POST',
  435. headers: { 'Content-Type': 'application/json' },
  436. body: JSON.stringify({ port })
  437. });
  438. const result = await response.json();
  439. if (result.success) {
  440. logMessage(`Connected to serial port: ${port}`, LOG_TYPE.SUCCESS);
  441. // Refresh the status
  442. await checkSerialStatus();
  443. } else {
  444. logMessage(`Error connecting to serial port: ${result.error}`, LOG_TYPE.ERROR);
  445. }
  446. }
  447. async function disconnectSerial() {
  448. const response = await fetch('/disconnect_serial', { method: 'POST' });
  449. const result = await response.json();
  450. if (result.success) {
  451. logMessage('Serial port disconnected.', LOG_TYPE.SUCCESS);
  452. // Refresh the status
  453. await checkSerialStatus();
  454. } else {
  455. logMessage(`Error disconnecting: ${result.error}`, LOG_TYPE.ERROR);
  456. }
  457. }
  458. async function restartSerial() {
  459. const port = document.getElementById('serial_ports').value;
  460. const response = await fetch('/restart_serial', {
  461. method: 'POST',
  462. headers: { 'Content-Type': 'application/json' },
  463. body: JSON.stringify({ port })
  464. });
  465. const result = await response.json();
  466. if (result.success) {
  467. document.getElementById('serial_status').textContent = `Restarted connection to ${port}`;
  468. logMessage('Serial connection restarted.', LOG_TYPE.SUCCESS);
  469. // No need to change visibility for restart
  470. } else {
  471. logMessage(`Error restarting serial connection: ${result.error}`, LOG_TYPE.ERROR);
  472. }
  473. }
  474. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  475. // Firmware / Software Updater
  476. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  477. async function fetchFirmwareInfo(motorType = null) {
  478. const checkButton = document.getElementById("check_updates_button");
  479. const motorTypeElement = document.getElementById("motor_type");
  480. const currentVersionElement = document.getElementById("current_firmware_version");
  481. const newVersionElement = document.getElementById("new_firmware_version");
  482. const motorSelectionDiv = document.getElementById("motor_selection");
  483. const updateButtonElement = document.getElementById("update_firmware_button");
  484. try {
  485. // Disable the button while fetching
  486. checkButton.disabled = true;
  487. checkButton.textContent = "Checking...";
  488. // Prepare fetch options
  489. const options = motorType
  490. ? {
  491. method: "POST",
  492. headers: { "Content-Type": "application/json" },
  493. body: JSON.stringify({ motorType }),
  494. }
  495. : { method: "GET" };
  496. const response = await fetch("/get_firmware_info", options);
  497. if (!response.ok) {
  498. throw new Error(`Server responded with status ${response.status}`);
  499. }
  500. const data = await response.json();
  501. if (data.success) {
  502. const { installedVersion, installedType, inoVersion, inoType, updateAvailable } = data;
  503. // Handle unknown motor type
  504. if (!installedType || installedType === "Unknown") {
  505. motorSelectionDiv.style.display = "flex"; // Show the dropdown
  506. updateButtonElement.style.display = "none"; // Hide update button
  507. checkButton.style.display = "none";
  508. } else {
  509. // Display motor type
  510. motorTypeElement.textContent = `Type: ${installedType || "Unknown"}`;
  511. // Pre-select the correct motor type in the dropdown
  512. const motorSelect = document.getElementById("manual_motor_type");
  513. if (motorSelect) {
  514. Array.from(motorSelect.options).forEach(option => {
  515. option.selected = option.value === installedType;
  516. });
  517. }
  518. // Display firmware versions
  519. currentVersionElement.textContent = `Current version: ${installedVersion || "Unknown"}`;
  520. if (updateAvailable) {
  521. newVersionElement.textContent = `New version: ${inoVersion}`;
  522. updateButtonElement.style.display = "block";
  523. checkButton.style.display = "none";
  524. } else {
  525. newVersionElement.textContent = "You are up to date!";
  526. updateButtonElement.style.display = "none";
  527. checkButton.style.display = "none";
  528. }
  529. }
  530. } else {
  531. logMessage("Error fetching firmware info.", LOG_TYPE.ERROR);
  532. logMessage(data.error, LOG_TYPE.DEBUG);
  533. }
  534. } catch (error) {
  535. logMessage("Error fetching firmware info.", LOG_TYPE.ERROR);
  536. logMessage(error.message, LOG_TYPE.DEBUG);
  537. } finally {
  538. // Re-enable the button after fetching
  539. checkButton.disabled = false;
  540. checkButton.textContent = "Check for Updates";
  541. }
  542. }
  543. function setMotorType() {
  544. const selectElement = document.getElementById("manual_motor_type");
  545. const selectedMotorType = selectElement.value;
  546. if (!selectedMotorType) {
  547. logMessage("Please select a motor type before proceeding.", LOG_TYPE.WARNING);
  548. return;
  549. }
  550. const motorSelectionDiv = document.getElementById("motor_selection");
  551. motorSelectionDiv.style.display = "none";
  552. // Call fetchFirmwareInfo with the selected motor type
  553. fetchFirmwareInfo(selectedMotorType);
  554. }
  555. async function updateFirmware() {
  556. const button = document.getElementById("update_firmware_button");
  557. const motorTypeDropdown = document.getElementById("manual_motor_type");
  558. const motorType = motorTypeDropdown ? motorTypeDropdown.value : null;
  559. if (!motorType) {
  560. logMessage("Motor type is not set. Please select a motor type.", LOG_TYPE.WARNING);
  561. return;
  562. }
  563. button.disabled = true;
  564. button.textContent = "Updating...";
  565. try {
  566. logMessage("Firmware update started...", LOG_TYPE.INFO);
  567. const response = await fetch("/flash_firmware", {
  568. method: "POST",
  569. headers: { "Content-Type": "application/json" },
  570. body: JSON.stringify({ motorType }),
  571. });
  572. const data = await response.json();
  573. if (data.success) {
  574. logMessage("Firmware updated successfully!", LOG_TYPE.SUCCESS);
  575. // Refresh the firmware info to update current version
  576. logMessage("Refreshing firmware info...");
  577. await fetchFirmwareInfo();
  578. // Display "You're up to date" message if versions match
  579. const newVersionElement = document.getElementById("new_firmware_version");
  580. newVersionElement.textContent = "You're up to date!";
  581. const motorSelectionDiv = document.getElementById("motor_selection");
  582. motorSelectionDiv.style.display = "none";
  583. } else {
  584. logMessage(`Firmware update failed: ${data.error}`, LOG_TYPE.ERROR);
  585. }
  586. } catch (error) {
  587. logMessage(`Error during firmware update: ${error.message}`, LOG_TYPE.ERROR);
  588. } finally {
  589. button.disabled = false; // Re-enable button
  590. button.textContent = "Update Firmware";
  591. }
  592. }
  593. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  594. // PART A: Loading / listing playlists from the server
  595. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  596. async function loadAllPlaylists() {
  597. try {
  598. const response = await fetch('/list_all_playlists'); // GET
  599. const allPlaylists = await response.json(); // e.g. ["My Playlist", "Summer", ...]
  600. displayAllPlaylists(allPlaylists);
  601. } catch (err) {
  602. logMessage(`Error loading playlists: ${err}`, LOG_TYPE.ERROR);
  603. }
  604. }
  605. // Function to display all playlists with Load, Run, and Delete buttons
  606. function displayAllPlaylists(playlists) {
  607. const ul = document.getElementById('all_playlists');
  608. ul.innerHTML = ''; // Clear current list
  609. playlists.forEach(playlistName => {
  610. const li = document.createElement('li');
  611. li.textContent = playlistName;
  612. li.classList.add('playlist-item'); // Add a class for styling
  613. // Attach click event to handle selection
  614. li.onclick = () => {
  615. // Remove 'selected' class from all items
  616. document.querySelectorAll('#all_playlists li').forEach(item => {
  617. item.classList.remove('selected');
  618. });
  619. // Add 'selected' class to the clicked item
  620. li.classList.add('selected');
  621. // Open the playlist editor for the selected playlist
  622. openPlaylistEditor(playlistName);
  623. };
  624. ul.appendChild(li);
  625. });
  626. }
  627. // Cancel changes and close the editor
  628. function cancelPlaylistChanges() {
  629. playlist = [...originalPlaylist]; // Revert to the original playlist
  630. isPlaylistChanged = false;
  631. toggleSaveCancelButtons(false); // Hide the save and cancel buttons
  632. refreshPlaylistUI(); // Refresh the UI with the original state
  633. closeStickySection('playlist-editor'); // Close the editor
  634. }
  635. // Open the playlist editor
  636. function openPlaylistEditor(playlistName) {
  637. logMessage(`Opening editor for playlist: ${playlistName}`);
  638. const editorSection = document.getElementById('playlist-editor');
  639. // Update the displayed playlist name
  640. document.getElementById('playlist_name_display').textContent = playlistName;
  641. // Store the current playlist name for renaming
  642. document.getElementById('playlist_name_input').value = playlistName;
  643. editorSection.classList.remove('hidden');
  644. editorSection.classList.add('visible');
  645. loadPlaylist(playlistName);
  646. }
  647. // Function to run the selected playlist with specified parameters
  648. async function runPlaylist() {
  649. const playlistName = document.getElementById('playlist_name_display').textContent;
  650. if (!playlistName) {
  651. logMessage("No playlist selected to run.");
  652. return;
  653. }
  654. const pauseTimeInput = document.getElementById('pause_time').value;
  655. const clearPatternSelect = document.getElementById('clear_pattern').value;
  656. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  657. const shuffle = document.getElementById('shuffle_playlist').checked;
  658. const pauseTime = parseFloat(pauseTimeInput);
  659. if (isNaN(pauseTime) || pauseTime < 0) {
  660. logMessage("Invalid pause time. Please enter a non-negative number.", LOG_TYPE.WARNING);
  661. return;
  662. }
  663. logMessage(`Running playlist: ${playlistName} with pause_time=${pauseTime}, clear_pattern=${clearPatternSelect}, run_mode=${runMode}, shuffle=${shuffle}.`);
  664. try {
  665. const response = await fetch('/run_playlist', {
  666. method: 'POST',
  667. headers: { 'Content-Type': 'application/json' },
  668. body: JSON.stringify({
  669. playlist_name: playlistName,
  670. pause_time: pauseTime,
  671. clear_pattern: clearPatternSelect,
  672. run_mode: runMode,
  673. shuffle: shuffle
  674. })
  675. });
  676. const result = await response.json();
  677. if (result.success) {
  678. logMessage(`Playlist "${playlistName}" is now running.`, LOG_TYPE.SUCCESS);
  679. } else {
  680. logMessage(`Failed to run playlist "${playlistName}": ${result.error}`, LOG_TYPE.ERROR);
  681. }
  682. } catch (error) {
  683. logMessage(`Error running playlist "${playlistName}": ${error.message}`, LOG_TYPE.ERROR);
  684. }
  685. }
  686. // Track changes in the playlist
  687. let originalPlaylist = [];
  688. let isPlaylistChanged = false;
  689. // Load playlist and set the original state
  690. async function loadPlaylist(playlistName) {
  691. try {
  692. logMessage(`Loading playlist: ${playlistName}`);
  693. const response = await fetch(`/get_playlist?name=${encodeURIComponent(playlistName)}`);
  694. if (!response.ok) {
  695. throw new Error(`HTTP error! Status: ${response.status}`);
  696. }
  697. const data = await response.json();
  698. if (!data.name) {
  699. throw new Error('Playlist name is missing in the response.');
  700. }
  701. // Populate playlist items and set original state
  702. playlist = data.files || [];
  703. originalPlaylist = [...playlist]; // Clone the playlist as the original
  704. isPlaylistChanged = false; // Reset change tracking
  705. toggleSaveCancelButtons(false); // Hide the save and cancel buttons initially
  706. refreshPlaylistUI();
  707. logMessage(`Loaded playlist: "${playlistName}" with ${playlist.length} file(s).`);
  708. } catch (err) {
  709. logMessage(`Error loading playlist: ${err.message}`, LOG_TYPE.ERROR);
  710. console.error('Error details:', err);
  711. }
  712. }
  713. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  714. // PART B: Creating or Saving (Overwriting) a Playlist
  715. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  716. // Instead of separate create/modify functions, we’ll unify them:
  717. async function savePlaylist() {
  718. const name = document.getElementById('playlist_name_display').textContent
  719. if (!name) {
  720. logMessage("Please enter a playlist name.");
  721. return;
  722. }
  723. if (playlist.length === 0) {
  724. logMessage("No files in this playlist. Add files first.");
  725. return;
  726. }
  727. logMessage(`Saving playlist "${name}" with ${playlist.length} file(s)...`);
  728. try {
  729. // We can use /create_playlist or /modify_playlist. They do roughly the same in our single-file approach.
  730. // Let's use /create_playlist to always overwrite or create anew.
  731. const response = await fetch('/create_playlist', {
  732. method: 'POST',
  733. headers: { 'Content-Type': 'application/json' },
  734. body: JSON.stringify({
  735. name: name,
  736. files: playlist
  737. })
  738. });
  739. const result = await response.json();
  740. if (result.success) {
  741. logMessage(`Playlist "${name}" with ${playlist.length} patterns saved`, LOG_TYPE.SUCCESS);
  742. // Reload the entire list of playlists to reflect changes
  743. // Check for changes and refresh the UI
  744. detectPlaylistChanges();
  745. refreshPlaylistUI();
  746. // Restore default action buttons
  747. toggleSaveCancelButtons(false);
  748. } else {
  749. logMessage(`Failed to save playlist: ${result.error}`, LOG_TYPE.ERROR);
  750. }
  751. } catch (err) {
  752. logMessage(`Error saving playlist: ${err}`);
  753. }
  754. }
  755. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  756. // PART C: Renaming and Deleting a playlist
  757. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  758. // Toggle the rename playlist input
  759. function populatePlaylistDropdown() {
  760. return fetch('/list_all_playlists')
  761. .then(response => response.json())
  762. .then(playlists => {
  763. const select = document.getElementById('select-playlist');
  764. select.innerHTML = ''; // Clear existing options
  765. // Retrieve the saved playlist from the cookie
  766. const savedPlaylist = getCookie('selected_playlist');
  767. playlists.forEach(playlist => {
  768. const option = document.createElement('option');
  769. option.value = playlist;
  770. option.textContent = playlist;
  771. // Mark the saved playlist as selected
  772. if (playlist === savedPlaylist) {
  773. option.selected = true;
  774. }
  775. select.appendChild(option);
  776. });
  777. // Attach the onchange event listener after populating the dropdown
  778. select.addEventListener('change', function () {
  779. const selectedPlaylist = this.value;
  780. setCookie('selected_playlist', selectedPlaylist, 7); // Save to cookie
  781. logMessage(`Selected playlist saved: ${selectedPlaylist}`);
  782. });
  783. logMessage('Playlist dropdown populated, event listener attached, and saved playlist restored.');
  784. })
  785. .catch(error => logMessage(`Error fetching playlists: ${error.message}`, LOG_TYPE.ERROR));
  786. }
  787. populatePlaylistDropdown().then(() => {
  788. loadSettingsFromCookies(); // Restore selected playlist after populating the dropdown
  789. });
  790. // Confirm and save the renamed playlist
  791. async function confirmAddPlaylist() {
  792. const playlistNameInput = document.getElementById('new_playlist_name');
  793. const playlistName = playlistNameInput.value.trim();
  794. if (!playlistName) {
  795. logMessage('Playlist name cannot be empty.', LOG_TYPE.ERROR);
  796. return;
  797. }
  798. try {
  799. logMessage(`Adding new playlist: "${playlistName}"...`);
  800. const response = await fetch('/create_playlist', {
  801. method: 'POST',
  802. headers: { 'Content-Type': 'application/json' },
  803. body: JSON.stringify({
  804. name: playlistName,
  805. files: [] // New playlist starts empty
  806. })
  807. });
  808. const result = await response.json();
  809. if (result.success) {
  810. logMessage(`Playlist "${playlistName}" created successfully.`, LOG_TYPE.SUCCESS);
  811. // Clear the input field
  812. playlistNameInput.value = '';
  813. // Refresh the playlist list
  814. loadAllPlaylists();
  815. // Hide the add playlist container
  816. toggleSecondaryButtons('add-playlist-container');
  817. } else {
  818. logMessage(`Failed to create playlist: ${result.error}`, LOG_TYPE.ERROR);
  819. }
  820. } catch (error) {
  821. logMessage(`Error creating playlist: ${error.message}`);
  822. }
  823. }
  824. async function confirmRenamePlaylist() {
  825. const newName = document.getElementById('playlist_name_input').value.trim();
  826. const currentName = document.getElementById('playlist_name_display').textContent;
  827. if (!newName) {
  828. logMessage("New playlist name cannot be empty.", LOG_TYPE.ERROR);
  829. return;
  830. }
  831. if (newName === currentName) {
  832. logMessage("New playlist name is the same as the current name. No changes made.", LOG_TYPE.WARNING);
  833. toggleSecondaryButtons('rename-playlist-container'); // Close the rename container
  834. return;
  835. }
  836. try {
  837. // Step 1: Create/Modify the playlist with the new name
  838. const createResponse = await fetch('/modify_playlist', {
  839. method: 'POST',
  840. headers: { 'Content-Type': 'application/json' },
  841. body: JSON.stringify({
  842. name: newName,
  843. files: playlist // Ensure `playlist` contains the current list of files
  844. })
  845. });
  846. const createResult = await createResponse.json();
  847. if (createResult.success) {
  848. logMessage(createResult.message, LOG_TYPE.SUCCESS);
  849. // Step 2: Delete the old playlist
  850. const deleteResponse = await fetch('/delete_playlist', {
  851. method: 'DELETE',
  852. headers: { 'Content-Type': 'application/json' },
  853. body: JSON.stringify({ name: currentName })
  854. });
  855. const deleteResult = await deleteResponse.json();
  856. if (deleteResult.success) {
  857. logMessage(deleteResult.message);
  858. // Update the UI with the new name
  859. document.getElementById('playlist_name_display').textContent = newName;
  860. // Refresh playlists list
  861. loadAllPlaylists();
  862. // Close the rename container and restore original action buttons
  863. toggleSecondaryButtons('rename-playlist-container');
  864. } else {
  865. logMessage(`Failed to delete old playlist: ${deleteResult.error}`, LOG_TYPE.ERROR);
  866. }
  867. } else {
  868. logMessage(`Failed to rename playlist: ${createResult.error}`, LOG_TYPE.ERROR);
  869. }
  870. } catch (error) {
  871. logMessage(`Error renaming playlist: ${error.message}`);
  872. }
  873. }
  874. // Delete the currently opened playlist
  875. async function deleteCurrentPlaylist() {
  876. const playlistName = document.getElementById('playlist_name_display').textContent;
  877. if (!confirm(`Are you sure you want to delete the playlist "${playlistName}"? This action cannot be undone.`)) {
  878. return;
  879. }
  880. try {
  881. const response = await fetch('/delete_playlist', {
  882. method: 'DELETE',
  883. headers: { 'Content-Type': 'application/json' },
  884. body: JSON.stringify({ name: playlistName })
  885. });
  886. const result = await response.json();
  887. if (result.success) {
  888. logMessage(`Playlist "${playlistName}" deleted.`, LOG_TYPE.INFO);
  889. closeStickySection('playlist-editor');
  890. loadAllPlaylists();
  891. } else {
  892. logMessage(`Failed to delete playlist: ${result.error}`, LOG_TYPE.ERROR);
  893. }
  894. } catch (error) {
  895. logMessage(`Error deleting playlist: ${error.message}`);
  896. }
  897. }
  898. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  899. // PART D: Local playlist array UI
  900. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  901. // Refresh the playlist UI and detect changes
  902. function refreshPlaylistUI() {
  903. const ul = document.getElementById('playlist_items');
  904. if (!ul) {
  905. logMessage('Error: Playlist container not found');
  906. return;
  907. }
  908. ul.innerHTML = ''; // Clear existing items
  909. if (playlist.length === 0) {
  910. // Add a placeholder if the playlist is empty
  911. const emptyLi = document.createElement('li');
  912. emptyLi.textContent = 'No items in the playlist.';
  913. emptyLi.classList.add('empty-placeholder'); // Optional: Add a class for styling
  914. ul.appendChild(emptyLi);
  915. return;
  916. }
  917. playlist.forEach((file, index) => {
  918. const li = document.createElement('li');
  919. // Add filename in a span
  920. const filenameSpan = document.createElement('span');
  921. filenameSpan.textContent = file;
  922. filenameSpan.classList.add('filename'); // Add a class for styling
  923. li.appendChild(filenameSpan);
  924. // Move Up button
  925. const moveUpBtn = document.createElement('button');
  926. moveUpBtn.textContent = '▲'; // Up arrow symbol
  927. moveUpBtn.classList.add('move-button');
  928. moveUpBtn.onclick = () => {
  929. if (index > 0) {
  930. const temp = playlist[index - 1];
  931. playlist[index - 1] = playlist[index];
  932. playlist[index] = temp;
  933. detectPlaylistChanges(); // Check for changes
  934. refreshPlaylistUI();
  935. }
  936. };
  937. li.appendChild(moveUpBtn);
  938. // Move Down button
  939. const moveDownBtn = document.createElement('button');
  940. moveDownBtn.textContent = '▼'; // Down arrow symbol
  941. moveDownBtn.classList.add('move-button');
  942. moveDownBtn.onclick = () => {
  943. if (index < playlist.length - 1) {
  944. const temp = playlist[index + 1];
  945. playlist[index + 1] = playlist[index];
  946. playlist[index] = temp;
  947. detectPlaylistChanges(); // Check for changes
  948. refreshPlaylistUI();
  949. }
  950. };
  951. li.appendChild(moveDownBtn);
  952. // Remove button
  953. const removeBtn = document.createElement('button');
  954. removeBtn.textContent = '✖';
  955. removeBtn.classList.add('remove-button');
  956. removeBtn.onclick = () => {
  957. playlist.splice(index, 1);
  958. detectPlaylistChanges(); // Check for changes
  959. refreshPlaylistUI();
  960. };
  961. li.appendChild(removeBtn);
  962. ul.appendChild(li);
  963. });
  964. }
  965. // Toggle the visibility of the save and cancel buttons
  966. function toggleSaveCancelButtons(show) {
  967. const actionButtons = document.querySelector('#playlist-editor .action-buttons');
  968. if (actionButtons) {
  969. // Show/hide all buttons except Save and Cancel
  970. actionButtons.querySelectorAll('button:not(.save-cancel)').forEach(button => {
  971. button.style.display = show ? 'none' : 'inline-block';
  972. });
  973. // Show/hide Save and Cancel buttons
  974. actionButtons.querySelectorAll('.save-cancel').forEach(button => {
  975. button.style.display = show ? 'inline-block' : 'none';
  976. });
  977. } else {
  978. logMessage('Error: Action buttons container not found.', LOG_TYPE.ERROR);
  979. }
  980. }
  981. // Detect changes in the playlist
  982. function detectPlaylistChanges() {
  983. isPlaylistChanged = JSON.stringify(originalPlaylist) !== JSON.stringify(playlist);
  984. toggleSaveCancelButtons(isPlaylistChanged);
  985. }
  986. // Toggle the "Add to Playlist" section
  987. function toggleSecondaryButtons(containerId, onShowCallback = null) {
  988. const container = document.getElementById(containerId);
  989. if (!container) {
  990. logMessage(`Error: Element with ID "${containerId}" not found`);
  991. return;
  992. }
  993. // Find the .action-buttons element preceding the container
  994. const previousActionButtons = container.previousElementSibling?.classList.contains('action-buttons')
  995. ? container.previousElementSibling
  996. : null;
  997. if (container.classList.contains('hidden')) {
  998. // Show the container
  999. container.classList.remove('hidden');
  1000. // Hide the previous .action-buttons element
  1001. if (previousActionButtons) {
  1002. previousActionButtons.style.display = 'none';
  1003. }
  1004. // Optional callback for custom logic when showing the container
  1005. if (onShowCallback) {
  1006. onShowCallback();
  1007. }
  1008. } else {
  1009. // Hide the container
  1010. container.classList.add('hidden');
  1011. // Restore the previous .action-buttons element
  1012. if (previousActionButtons) {
  1013. previousActionButtons.style.display = 'flex';
  1014. }
  1015. }
  1016. }
  1017. // Add the selected pattern to the selected playlist
  1018. async function saveToPlaylist() {
  1019. const playlist = document.getElementById('select-playlist').value;
  1020. if (!playlist) {
  1021. logMessage('No playlist selected.', LOG_TYPE.ERROR);
  1022. return;
  1023. }
  1024. if (!selectedFile) {
  1025. logMessage('No pattern selected to add.', LOG_TYPE.ERROR);
  1026. return;
  1027. }
  1028. try {
  1029. logMessage(`Adding pattern "${selectedFile}" to playlist "${playlist}"...`);
  1030. const response = await fetch('/add_to_playlist', {
  1031. method: 'POST',
  1032. headers: { 'Content-Type': 'application/json' },
  1033. body: JSON.stringify({ playlist_name: playlist, pattern: selectedFile })
  1034. });
  1035. const result = await response.json();
  1036. if (result.success) {
  1037. logMessage(`Pattern "${selectedFile}" successfully added to playlist "${playlist}".`, LOG_TYPE.SUCCESS);
  1038. // Reset the UI state via toggleSecondaryButtons
  1039. toggleSecondaryButtons('add-to-playlist-container', () => {
  1040. const selectPlaylist = document.getElementById('select-playlist');
  1041. selectPlaylist.value = ''; // Clear the selection
  1042. });
  1043. } else {
  1044. logMessage(`Failed to add pattern to playlist: ${result.error}`, LOG_TYPE.ERROR);
  1045. }
  1046. } catch (error) {
  1047. logMessage(`Error adding pattern to playlist: ${error.message}`);
  1048. }
  1049. }
  1050. async function changeSpeed() {
  1051. const speedInput = document.getElementById('speed_input');
  1052. const speed = parseFloat(speedInput.value);
  1053. if (isNaN(speed) || speed <= 0) {
  1054. logMessage('Invalid speed. Please enter a positive number.');
  1055. return;
  1056. }
  1057. logMessage(`Setting speed to: ${speed}...`);
  1058. const response = await fetch('/set_speed', {
  1059. method: 'POST',
  1060. headers: { 'Content-Type': 'application/json' },
  1061. body: JSON.stringify({ speed })
  1062. });
  1063. const result = await response.json();
  1064. if (result.success) {
  1065. document.getElementById('speed_status').textContent = `Current Speed: ${speed}`;
  1066. logMessage(`Speed set to: ${speed}`, LOG_TYPE.SUCCESS);
  1067. } else {
  1068. logMessage(`Failed to set speed: ${result.error}`, LOG_TYPE.ERROR);
  1069. }
  1070. }
  1071. // Function to close any sticky section
  1072. function closeStickySection(sectionId) {
  1073. const section = document.getElementById(sectionId);
  1074. if (section) {
  1075. section.classList.remove('visible');
  1076. section.classList.remove('fullscreen');
  1077. section.classList.add('hidden');
  1078. // Reset the fullscreen button text if it exists
  1079. const fullscreenButton = section.querySelector('.fullscreen-button');
  1080. if (fullscreenButton) {
  1081. fullscreenButton.textContent = '⛶'; // Reset to enter fullscreen icon/text
  1082. }
  1083. logMessage(`Closed section: ${sectionId}`);
  1084. if(sectionId === 'playlist-editor') {
  1085. document.querySelectorAll('#all_playlists .playlist-item').forEach(item => {
  1086. item.classList.remove('selected');
  1087. });
  1088. }
  1089. if(sectionId === 'pattern-preview-container') {
  1090. document.querySelectorAll('#theta_rho_files .file-item').forEach(item => {
  1091. item.classList.remove('selected');
  1092. });
  1093. }
  1094. } else {
  1095. logMessage(`Error: Section with ID "${sectionId}" not found`);
  1096. }
  1097. }
  1098. function attachFullScreenListeners() {
  1099. // Add event listener to all fullscreen buttons
  1100. document.querySelectorAll('.fullscreen-button').forEach(button => {
  1101. button.addEventListener('click', function () {
  1102. const stickySection = this.closest('.sticky'); // Find the closest sticky section
  1103. if (stickySection) {
  1104. stickySection.classList.toggle('fullscreen'); // Toggle fullscreen class
  1105. // Update button icon or text
  1106. if (stickySection.classList.contains('fullscreen')) {
  1107. this.textContent = '-'; // Exit fullscreen icon/text
  1108. } else {
  1109. this.textContent = '⛶'; // Enter fullscreen icon/text
  1110. }
  1111. } else {
  1112. console.error('Error: Fullscreen button is not inside a sticky section.');
  1113. }
  1114. });
  1115. });
  1116. }
  1117. // Utility function to manage cookies
  1118. function setCookie(name, value, days) {
  1119. const date = new Date();
  1120. date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  1121. document.cookie = `${name}=${value};expires=${date.toUTCString()};path=/`;
  1122. }
  1123. function getCookie(name) {
  1124. const nameEQ = `${name}=`;
  1125. const cookies = document.cookie.split(';');
  1126. for (let i = 0; i < cookies.length; i++) {
  1127. let cookie = cookies[i].trim();
  1128. if (cookie.startsWith(nameEQ)) {
  1129. return cookie.substring(nameEQ.length);
  1130. }
  1131. }
  1132. return null;
  1133. }
  1134. // Save settings to cookies
  1135. function saveSettingsToCookies() {
  1136. // Save the pause time
  1137. const pauseTime = document.getElementById('pause_time').value;
  1138. setCookie('pause_time', pauseTime, 7);
  1139. // Save the clear pattern
  1140. const clearPattern = document.getElementById('clear_pattern').value;
  1141. setCookie('clear_pattern', clearPattern, 7);
  1142. // Save the run mode
  1143. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  1144. setCookie('run_mode', runMode, 7);
  1145. // Save shuffle playlist checkbox state
  1146. const shufflePlaylist = document.getElementById('shuffle_playlist').checked;
  1147. setCookie('shuffle_playlist', shufflePlaylist, 7);
  1148. // Save pre-execution action
  1149. const preExecution = document.querySelector('input[name="pre_execution"]:checked').value;
  1150. setCookie('pre_execution', preExecution, 7);
  1151. logMessage('Settings saved.');
  1152. }
  1153. // Load settings from cookies
  1154. function loadSettingsFromCookies() {
  1155. // Load the pause time
  1156. const pauseTime = getCookie('pause_time');
  1157. if (pauseTime !== null) {
  1158. document.getElementById('pause_time').value = pauseTime;
  1159. }
  1160. // Load the clear pattern
  1161. const clearPattern = getCookie('clear_pattern');
  1162. if (clearPattern !== null) {
  1163. document.getElementById('clear_pattern').value = clearPattern;
  1164. }
  1165. // Load the run mode
  1166. const runMode = getCookie('run_mode');
  1167. if (runMode !== null) {
  1168. document.querySelector(`input[name="run_mode"][value="${runMode}"]`).checked = true;
  1169. }
  1170. // Load the shuffle playlist checkbox state
  1171. const shufflePlaylist = getCookie('shuffle_playlist');
  1172. if (shufflePlaylist !== null) {
  1173. document.getElementById('shuffle_playlist').checked = shufflePlaylist === 'true';
  1174. }
  1175. // Load the pre-execution action
  1176. const preExecution = getCookie('pre_execution');
  1177. if (preExecution !== null) {
  1178. document.querySelector(`input[name="pre_execution"][value="${preExecution}"]`).checked = true;
  1179. }
  1180. // Load the selected playlist
  1181. const selectedPlaylist = getCookie('selected_playlist');
  1182. if (selectedPlaylist !== null) {
  1183. const playlistDropdown = document.getElementById('select-playlist');
  1184. if (playlistDropdown && [...playlistDropdown.options].some(option => option.value === selectedPlaylist)) {
  1185. playlistDropdown.value = selectedPlaylist;
  1186. }
  1187. }
  1188. logMessage('Settings loaded from cookies.');
  1189. }
  1190. // Call this function to save settings when a value is changed
  1191. function attachSettingsSaveListeners() {
  1192. // Add event listeners to inputs
  1193. document.getElementById('pause_time').addEventListener('input', saveSettingsToCookies);
  1194. document.getElementById('clear_pattern').addEventListener('change', saveSettingsToCookies);
  1195. document.querySelectorAll('input[name="run_mode"]').forEach(input => {
  1196. input.addEventListener('change', saveSettingsToCookies);
  1197. });
  1198. document.getElementById('shuffle_playlist').addEventListener('change', saveSettingsToCookies);
  1199. document.querySelectorAll('input[name="pre_execution"]').forEach(input => {
  1200. input.addEventListener('change', saveSettingsToCookies);
  1201. });
  1202. }
  1203. // Tab switching logic with cookie storage
  1204. function switchTab(tabName) {
  1205. // Store the active tab in a cookie
  1206. setCookie('activeTab', tabName, 7); // Store for 7 days
  1207. // Deactivate all tab content
  1208. document.querySelectorAll('.tab-content').forEach(tab => {
  1209. tab.classList.remove('active');
  1210. });
  1211. // Activate the selected tab content
  1212. const activeTab = document.getElementById(`${tabName}-tab`);
  1213. if (activeTab) {
  1214. activeTab.classList.add('active');
  1215. } else {
  1216. console.error(`Error: Tab "${tabName}" not found.`);
  1217. }
  1218. // Deactivate all nav buttons
  1219. document.querySelectorAll('.bottom-nav .tab-button').forEach(button => {
  1220. button.classList.remove('active');
  1221. });
  1222. // Activate the selected nav button
  1223. const activeNavButton = document.getElementById(`nav-${tabName}`);
  1224. if (activeNavButton) {
  1225. activeNavButton.classList.add('active');
  1226. } else {
  1227. console.error(`Error: Nav button for "${tabName}" not found.`);
  1228. }
  1229. }
  1230. // Initialization
  1231. document.addEventListener('DOMContentLoaded', () => {
  1232. const activeTab = getCookie('activeTab') || 'patterns'; // Default to 'patterns' tab
  1233. switchTab(activeTab); // Load the active tab
  1234. checkSerialStatus(); // Check serial connection status
  1235. loadThetaRhoFiles(); // Load files on page load
  1236. loadAllPlaylists(); // Load all playlists on page load
  1237. loadSettingsFromCookies(); // Load saved settings
  1238. attachSettingsSaveListeners(); // Attach event listeners to save changes
  1239. attachFullScreenListeners();
  1240. });