main.js 52 KB

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