main.js 58 KB

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