main.js 52 KB

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