main.js 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610
  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("Error fetching firmware info.", LOG_TYPE.ERROR);
  601. logMessage(data.error, LOG_TYPE.DEBUG);
  602. }
  603. } catch (error) {
  604. logMessage("Error fetching firmware info.", LOG_TYPE.ERROR);
  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. newVersionElement.textContent = "You're up to date!";
  650. const motorSelectionDiv = document.getElementById("motor_selection");
  651. motorSelectionDiv.style.display = "none";
  652. } else {
  653. logMessage(`Firmware update failed: ${data.error}`, LOG_TYPE.ERROR);
  654. }
  655. } catch (error) {
  656. logMessage(`Error during firmware update: ${error.message}`, LOG_TYPE.ERROR);
  657. } finally {
  658. button.disabled = false; // Re-enable button
  659. button.textContent = "Update Firmware";
  660. }
  661. }
  662. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  663. // PART A: Loading / listing playlists from the server
  664. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  665. async function loadAllPlaylists() {
  666. try {
  667. const response = await fetch('/list_all_playlists'); // GET
  668. const allPlaylists = await response.json(); // e.g. ["My Playlist", "Summer", ...]
  669. displayAllPlaylists(allPlaylists);
  670. } catch (err) {
  671. logMessage(`Error loading playlists: ${err}`, LOG_TYPE.ERROR);
  672. }
  673. }
  674. // Function to display all playlists with Load, Run, and Delete buttons
  675. function displayAllPlaylists(playlists) {
  676. const ul = document.getElementById('all_playlists');
  677. ul.innerHTML = ''; // Clear current list
  678. playlists.forEach(playlistName => {
  679. const li = document.createElement('li');
  680. li.textContent = playlistName;
  681. li.classList.add('playlist-item'); // Add a class for styling
  682. // Attach click event to handle selection
  683. li.onclick = () => {
  684. // Remove 'selected' class from all items
  685. document.querySelectorAll('#all_playlists li').forEach(item => {
  686. item.classList.remove('selected');
  687. });
  688. // Add 'selected' class to the clicked item
  689. li.classList.add('selected');
  690. // Open the playlist editor for the selected playlist
  691. openPlaylistEditor(playlistName);
  692. };
  693. ul.appendChild(li);
  694. });
  695. }
  696. // Cancel changes and close the editor
  697. function cancelPlaylistChanges() {
  698. playlist = [...originalPlaylist]; // Revert to the original playlist
  699. isPlaylistChanged = false;
  700. toggleSaveCancelButtons(false); // Hide the save and cancel buttons
  701. refreshPlaylistUI(); // Refresh the UI with the original state
  702. closeStickySection('playlist-editor'); // Close the editor
  703. }
  704. // Open the playlist editor
  705. function openPlaylistEditor(playlistName) {
  706. logMessage(`Opening editor for playlist: ${playlistName}`);
  707. const editorSection = document.getElementById('playlist-editor');
  708. // Update the displayed playlist name
  709. document.getElementById('playlist_name_display').textContent = playlistName;
  710. // Store the current playlist name for renaming
  711. document.getElementById('playlist_name_input').value = playlistName;
  712. editorSection.classList.remove('hidden');
  713. editorSection.classList.add('visible');
  714. loadPlaylist(playlistName);
  715. }
  716. function clearSchedule() {
  717. document.getElementById("start_time").value = "";
  718. document.getElementById("end_time").value = "";
  719. }
  720. // Function to run the selected playlist with specified parameters
  721. async function runPlaylist() {
  722. const playlistName = document.getElementById('playlist_name_display').textContent;
  723. if (!playlistName) {
  724. logMessage("No playlist selected to run.");
  725. return;
  726. }
  727. const pauseTimeInput = document.getElementById('pause_time').value;
  728. const clearPatternSelect = document.getElementById('clear_pattern').value;
  729. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  730. const shuffle = document.getElementById('shuffle_playlist').checked;
  731. const startTimeInput = document.getElementById('start_time').value.trim();
  732. const endTimeInput = document.getElementById('end_time').value.trim();
  733. const pauseTime = parseFloat(pauseTimeInput);
  734. if (isNaN(pauseTime) || pauseTime < 0) {
  735. logMessage("Invalid pause time. Please enter a non-negative number.", LOG_TYPE.WARNING);
  736. return;
  737. }
  738. // Validate start and end time format and logic
  739. let startTime = startTimeInput || null;
  740. let endTime = endTimeInput || null;
  741. // Ensure that if one time is filled, the other must be as well
  742. if ((startTime && !endTime) || (!startTime && endTime)) {
  743. logMessage("Both start and end times must be provided together or left blank.", LOG_TYPE.WARNING);
  744. return;
  745. }
  746. // If both are provided, validate format and ensure start_time < end_time
  747. if (startTime && endTime) {
  748. try {
  749. const startDateTime = new Date(`1970-01-01T${startTime}:00`);
  750. const endDateTime = new Date(`1970-01-01T${endTime}:00`);
  751. if (isNaN(startDateTime.getTime()) || isNaN(endDateTime.getTime())) {
  752. logMessage("Invalid time format. Please use HH:MM format (e.g., 09:30).", LOG_TYPE.WARNING);
  753. return;
  754. }
  755. if (startDateTime >= endDateTime) {
  756. logMessage("Start time must be earlier than end time.", LOG_TYPE.WARNING);
  757. return;
  758. }
  759. } catch (error) {
  760. logMessage("Error parsing start or end time. Ensure correct HH:MM format.", LOG_TYPE.ERROR);
  761. return;
  762. }
  763. }
  764. logMessage(`Running playlist: ${playlistName} with pause_time=${pauseTime}, clear_pattern=${clearPatternSelect}, run_mode=${runMode}, shuffle=${shuffle}.`);
  765. try {
  766. const response = await fetch('/run_playlist', {
  767. method: 'POST',
  768. headers: { 'Content-Type': 'application/json' },
  769. body: JSON.stringify({
  770. playlist_name: playlistName,
  771. pause_time: pauseTime,
  772. clear_pattern: clearPatternSelect,
  773. run_mode: runMode,
  774. shuffle: shuffle,
  775. start_time: startTimeInput,
  776. end_time: endTimeInput
  777. })
  778. });
  779. const result = await response.json();
  780. if (result.success) {
  781. logMessage(`Playlist "${playlistName}" is now running.`, LOG_TYPE.SUCCESS);
  782. } else {
  783. logMessage(`Failed to run playlist "${playlistName}": ${result.error}`, LOG_TYPE.ERROR);
  784. }
  785. } catch (error) {
  786. logMessage(`Error running playlist "${playlistName}": ${error.message}`, LOG_TYPE.ERROR);
  787. }
  788. }
  789. // Track changes in the playlist
  790. let originalPlaylist = [];
  791. let isPlaylistChanged = false;
  792. // Load playlist and set the original state
  793. async function loadPlaylist(playlistName) {
  794. try {
  795. logMessage(`Loading playlist: ${playlistName}`);
  796. const response = await fetch(`/get_playlist?name=${encodeURIComponent(playlistName)}`);
  797. if (!response.ok) {
  798. throw new Error(`HTTP error! Status: ${response.status}`);
  799. }
  800. const data = await response.json();
  801. if (!data.name) {
  802. throw new Error('Playlist name is missing in the response.');
  803. }
  804. // Populate playlist items and set original state
  805. playlist = data.files || [];
  806. originalPlaylist = [...playlist]; // Clone the playlist as the original
  807. isPlaylistChanged = false; // Reset change tracking
  808. toggleSaveCancelButtons(false); // Hide the save and cancel buttons initially
  809. refreshPlaylistUI();
  810. logMessage(`Loaded playlist: "${playlistName}" with ${playlist.length} file(s).`);
  811. } catch (err) {
  812. logMessage(`Error loading playlist: ${err.message}`, LOG_TYPE.ERROR);
  813. console.error('Error details:', err);
  814. }
  815. }
  816. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  817. // PART B: Creating or Saving (Overwriting) a Playlist
  818. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  819. // Instead of separate create/modify functions, we’ll unify them:
  820. async function savePlaylist() {
  821. const name = document.getElementById('playlist_name_display').textContent
  822. if (!name) {
  823. logMessage("Please enter a playlist name.");
  824. return;
  825. }
  826. if (playlist.length === 0) {
  827. logMessage("No files in this playlist. Add files first.");
  828. return;
  829. }
  830. logMessage(`Saving playlist "${name}" with ${playlist.length} file(s)...`);
  831. try {
  832. // We can use /create_playlist or /modify_playlist. They do roughly the same in our single-file approach.
  833. // Let's use /create_playlist to always overwrite or create anew.
  834. const response = await fetch('/create_playlist', {
  835. method: 'POST',
  836. headers: { 'Content-Type': 'application/json' },
  837. body: JSON.stringify({
  838. name: name,
  839. files: playlist
  840. })
  841. });
  842. const result = await response.json();
  843. if (result.success) {
  844. logMessage(`Playlist "${name}" with ${playlist.length} patterns saved`, LOG_TYPE.SUCCESS);
  845. // Reload the entire list of playlists to reflect changes
  846. // Check for changes and refresh the UI
  847. detectPlaylistChanges();
  848. refreshPlaylistUI();
  849. // Restore default action buttons
  850. toggleSaveCancelButtons(false);
  851. } else {
  852. logMessage(`Failed to save playlist: ${result.error}`, LOG_TYPE.ERROR);
  853. }
  854. } catch (err) {
  855. logMessage(`Error saving playlist: ${err}`);
  856. }
  857. }
  858. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  859. // PART C: Renaming and Deleting a playlist
  860. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  861. // Toggle the rename playlist input
  862. function populatePlaylistDropdown() {
  863. return fetch('/list_all_playlists')
  864. .then(response => response.json())
  865. .then(playlists => {
  866. const select = document.getElementById('select-playlist');
  867. select.innerHTML = ''; // Clear existing options
  868. // Retrieve the saved playlist from the cookie
  869. const savedPlaylist = getCookie('selected_playlist');
  870. playlists.forEach(playlist => {
  871. const option = document.createElement('option');
  872. option.value = playlist;
  873. option.textContent = playlist;
  874. // Mark the saved playlist as selected
  875. if (playlist === savedPlaylist) {
  876. option.selected = true;
  877. }
  878. select.appendChild(option);
  879. });
  880. // Attach the onchange event listener after populating the dropdown
  881. select.addEventListener('change', function () {
  882. const selectedPlaylist = this.value;
  883. setCookie('selected_playlist', selectedPlaylist, 7); // Save to cookie
  884. logMessage(`Selected playlist saved: ${selectedPlaylist}`);
  885. });
  886. logMessage('Playlist dropdown populated, event listener attached, and saved playlist restored.');
  887. })
  888. .catch(error => logMessage(`Error fetching playlists: ${error.message}`, LOG_TYPE.ERROR));
  889. }
  890. populatePlaylistDropdown().then(() => {
  891. loadSettingsFromCookies(); // Restore selected playlist after populating the dropdown
  892. });
  893. // Confirm and save the renamed playlist
  894. async function confirmAddPlaylist() {
  895. const playlistNameInput = document.getElementById('new_playlist_name');
  896. const playlistName = playlistNameInput.value.trim();
  897. if (!playlistName) {
  898. logMessage('Playlist name cannot be empty.', LOG_TYPE.ERROR);
  899. return;
  900. }
  901. try {
  902. logMessage(`Adding new playlist: "${playlistName}"...`);
  903. const response = await fetch('/create_playlist', {
  904. method: 'POST',
  905. headers: { 'Content-Type': 'application/json' },
  906. body: JSON.stringify({
  907. name: playlistName,
  908. files: [] // New playlist starts empty
  909. })
  910. });
  911. const result = await response.json();
  912. if (result.success) {
  913. logMessage(`Playlist "${playlistName}" created successfully.`, LOG_TYPE.SUCCESS);
  914. // Clear the input field
  915. playlistNameInput.value = '';
  916. // Refresh the playlist list
  917. loadAllPlaylists();
  918. // Hide the add playlist container
  919. toggleSecondaryButtons('add-playlist-container');
  920. } else {
  921. logMessage(`Failed to create playlist: ${result.error}`, LOG_TYPE.ERROR);
  922. }
  923. } catch (error) {
  924. logMessage(`Error creating playlist: ${error.message}`);
  925. }
  926. }
  927. async function confirmRenamePlaylist() {
  928. const newName = document.getElementById('playlist_name_input').value.trim();
  929. const currentName = document.getElementById('playlist_name_display').textContent;
  930. if (!newName) {
  931. logMessage("New playlist name cannot be empty.", LOG_TYPE.ERROR);
  932. return;
  933. }
  934. if (newName === currentName) {
  935. logMessage("New playlist name is the same as the current name. No changes made.", LOG_TYPE.WARNING);
  936. toggleSecondaryButtons('rename-playlist-container'); // Close the rename container
  937. return;
  938. }
  939. try {
  940. // Step 1: Create/Modify the playlist with the new name
  941. const createResponse = await fetch('/modify_playlist', {
  942. method: 'POST',
  943. headers: { 'Content-Type': 'application/json' },
  944. body: JSON.stringify({
  945. name: newName,
  946. files: playlist // Ensure `playlist` contains the current list of files
  947. })
  948. });
  949. const createResult = await createResponse.json();
  950. if (createResult.success) {
  951. logMessage(createResult.message, LOG_TYPE.SUCCESS);
  952. // Step 2: Delete the old playlist
  953. const deleteResponse = await fetch('/delete_playlist', {
  954. method: 'DELETE',
  955. headers: { 'Content-Type': 'application/json' },
  956. body: JSON.stringify({ name: currentName })
  957. });
  958. const deleteResult = await deleteResponse.json();
  959. if (deleteResult.success) {
  960. logMessage(deleteResult.message);
  961. // Update the UI with the new name
  962. document.getElementById('playlist_name_display').textContent = newName;
  963. // Refresh playlists list
  964. loadAllPlaylists();
  965. // Close the rename container and restore original action buttons
  966. toggleSecondaryButtons('rename-playlist-container');
  967. } else {
  968. logMessage(`Failed to delete old playlist: ${deleteResult.error}`, LOG_TYPE.ERROR);
  969. }
  970. } else {
  971. logMessage(`Failed to rename playlist: ${createResult.error}`, LOG_TYPE.ERROR);
  972. }
  973. } catch (error) {
  974. logMessage(`Error renaming playlist: ${error.message}`);
  975. }
  976. }
  977. // Delete the currently opened playlist
  978. async function deleteCurrentPlaylist() {
  979. const playlistName = document.getElementById('playlist_name_display').textContent;
  980. if (!confirm(`Are you sure you want to delete the playlist "${playlistName}"? This action cannot be undone.`)) {
  981. return;
  982. }
  983. try {
  984. const response = await fetch('/delete_playlist', {
  985. method: 'DELETE',
  986. headers: { 'Content-Type': 'application/json' },
  987. body: JSON.stringify({ name: playlistName })
  988. });
  989. const result = await response.json();
  990. if (result.success) {
  991. logMessage(`Playlist "${playlistName}" deleted.`, LOG_TYPE.INFO);
  992. closeStickySection('playlist-editor');
  993. loadAllPlaylists();
  994. } else {
  995. logMessage(`Failed to delete playlist: ${result.error}`, LOG_TYPE.ERROR);
  996. }
  997. } catch (error) {
  998. logMessage(`Error deleting playlist: ${error.message}`);
  999. }
  1000. }
  1001. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1002. // PART D: Local playlist array UI
  1003. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1004. // Refresh the playlist UI and detect changes
  1005. function refreshPlaylistUI() {
  1006. const ul = document.getElementById('playlist_items');
  1007. if (!ul) {
  1008. logMessage('Error: Playlist container not found');
  1009. return;
  1010. }
  1011. ul.innerHTML = ''; // Clear existing items
  1012. if (playlist.length === 0) {
  1013. // Add a placeholder if the playlist is empty
  1014. const emptyLi = document.createElement('li');
  1015. emptyLi.textContent = 'No items in the playlist.';
  1016. emptyLi.classList.add('empty-placeholder'); // Optional: Add a class for styling
  1017. ul.appendChild(emptyLi);
  1018. return;
  1019. }
  1020. playlist.forEach((file, index) => {
  1021. const li = document.createElement('li');
  1022. // Add filename in a span
  1023. const filenameSpan = document.createElement('span');
  1024. filenameSpan.textContent = file;
  1025. filenameSpan.classList.add('filename'); // Add a class for styling
  1026. li.appendChild(filenameSpan);
  1027. // Move Up button
  1028. const moveUpBtn = document.createElement('button');
  1029. moveUpBtn.textContent = '▲'; // Up arrow symbol
  1030. moveUpBtn.classList.add('move-button');
  1031. moveUpBtn.onclick = () => {
  1032. if (index > 0) {
  1033. const temp = playlist[index - 1];
  1034. playlist[index - 1] = playlist[index];
  1035. playlist[index] = temp;
  1036. detectPlaylistChanges(); // Check for changes
  1037. refreshPlaylistUI();
  1038. }
  1039. };
  1040. li.appendChild(moveUpBtn);
  1041. // Move Down button
  1042. const moveDownBtn = document.createElement('button');
  1043. moveDownBtn.textContent = '▼'; // Down arrow symbol
  1044. moveDownBtn.classList.add('move-button');
  1045. moveDownBtn.onclick = () => {
  1046. if (index < playlist.length - 1) {
  1047. const temp = playlist[index + 1];
  1048. playlist[index + 1] = playlist[index];
  1049. playlist[index] = temp;
  1050. detectPlaylistChanges(); // Check for changes
  1051. refreshPlaylistUI();
  1052. }
  1053. };
  1054. li.appendChild(moveDownBtn);
  1055. // Remove button
  1056. const removeBtn = document.createElement('button');
  1057. removeBtn.textContent = '✖';
  1058. removeBtn.classList.add('remove-button');
  1059. removeBtn.onclick = () => {
  1060. playlist.splice(index, 1);
  1061. detectPlaylistChanges(); // Check for changes
  1062. refreshPlaylistUI();
  1063. };
  1064. li.appendChild(removeBtn);
  1065. ul.appendChild(li);
  1066. });
  1067. }
  1068. // Toggle the visibility of the save and cancel buttons
  1069. function toggleSaveCancelButtons(show) {
  1070. const actionButtons = document.querySelector('#playlist-editor .action-buttons');
  1071. if (actionButtons) {
  1072. // Show/hide all buttons except Save and Cancel
  1073. actionButtons.querySelectorAll('button:not(.save-cancel)').forEach(button => {
  1074. button.style.display = show ? 'none' : 'inline-block';
  1075. });
  1076. // Show/hide Save and Cancel buttons
  1077. actionButtons.querySelectorAll('.save-cancel').forEach(button => {
  1078. button.style.display = show ? 'inline-block' : 'none';
  1079. });
  1080. } else {
  1081. logMessage('Error: Action buttons container not found.', LOG_TYPE.ERROR);
  1082. }
  1083. }
  1084. // Detect changes in the playlist
  1085. function detectPlaylistChanges() {
  1086. isPlaylistChanged = JSON.stringify(originalPlaylist) !== JSON.stringify(playlist);
  1087. toggleSaveCancelButtons(isPlaylistChanged);
  1088. }
  1089. // Toggle the "Add to Playlist" section
  1090. function toggleSecondaryButtons(containerId, onShowCallback = null) {
  1091. const container = document.getElementById(containerId);
  1092. if (!container) {
  1093. logMessage(`Error: Element with ID "${containerId}" not found`);
  1094. return;
  1095. }
  1096. // Find the .action-buttons element preceding the container
  1097. const previousActionButtons = container.previousElementSibling?.classList.contains('action-buttons')
  1098. ? container.previousElementSibling
  1099. : null;
  1100. if (container.classList.contains('hidden')) {
  1101. // Show the container
  1102. container.classList.remove('hidden');
  1103. // Hide the previous .action-buttons element
  1104. if (previousActionButtons) {
  1105. previousActionButtons.style.display = 'none';
  1106. }
  1107. // Optional callback for custom logic when showing the container
  1108. if (onShowCallback) {
  1109. onShowCallback();
  1110. }
  1111. } else {
  1112. // Hide the container
  1113. container.classList.add('hidden');
  1114. // Restore the previous .action-buttons element
  1115. if (previousActionButtons) {
  1116. previousActionButtons.style.display = 'flex';
  1117. }
  1118. }
  1119. }
  1120. // Add the selected pattern to the selected playlist
  1121. async function saveToPlaylist() {
  1122. const playlist = document.getElementById('select-playlist').value;
  1123. if (!playlist) {
  1124. logMessage('No playlist selected.', LOG_TYPE.ERROR);
  1125. return;
  1126. }
  1127. if (!selectedFile) {
  1128. logMessage('No pattern selected to add.', LOG_TYPE.ERROR);
  1129. return;
  1130. }
  1131. try {
  1132. logMessage(`Adding pattern "${selectedFile}" to playlist "${playlist}"...`);
  1133. const response = await fetch('/add_to_playlist', {
  1134. method: 'POST',
  1135. headers: { 'Content-Type': 'application/json' },
  1136. body: JSON.stringify({ playlist_name: playlist, pattern: selectedFile })
  1137. });
  1138. const result = await response.json();
  1139. if (result.success) {
  1140. logMessage(`Pattern "${selectedFile}" successfully added to playlist "${playlist}".`, LOG_TYPE.SUCCESS);
  1141. // Reset the UI state via toggleSecondaryButtons
  1142. toggleSecondaryButtons('add-to-playlist-container', () => {
  1143. const selectPlaylist = document.getElementById('select-playlist');
  1144. selectPlaylist.value = ''; // Clear the selection
  1145. });
  1146. } else {
  1147. logMessage(`Failed to add pattern to playlist: ${result.error}`, LOG_TYPE.ERROR);
  1148. }
  1149. } catch (error) {
  1150. logMessage(`Error adding pattern to playlist: ${error.message}`);
  1151. }
  1152. }
  1153. async function changeSpeed() {
  1154. const speedInput = document.getElementById('speed_input');
  1155. const speed = parseFloat(speedInput.value);
  1156. if (isNaN(speed) || speed <= 0) {
  1157. logMessage('Invalid speed. Please enter a positive number.');
  1158. return;
  1159. }
  1160. logMessage(`Setting speed to: ${speed}...`);
  1161. const response = await fetch('/set_speed', {
  1162. method: 'POST',
  1163. headers: { 'Content-Type': 'application/json' },
  1164. body: JSON.stringify({ speed })
  1165. });
  1166. const result = await response.json();
  1167. if (result.success) {
  1168. document.getElementById('speed_status').textContent = `Current Speed: ${speed}`;
  1169. logMessage(`Speed set to: ${speed}`, LOG_TYPE.SUCCESS);
  1170. } else {
  1171. logMessage(`Failed to set speed: ${result.error}`, LOG_TYPE.ERROR);
  1172. }
  1173. }
  1174. // Function to close any sticky section
  1175. function closeStickySection(sectionId) {
  1176. const section = document.getElementById(sectionId);
  1177. if (section) {
  1178. section.classList.remove('visible');
  1179. section.classList.remove('fullscreen');
  1180. section.classList.add('hidden');
  1181. // Reset the fullscreen button text if it exists
  1182. const fullscreenButton = section.querySelector('.fullscreen-button');
  1183. if (fullscreenButton) {
  1184. fullscreenButton.textContent = '⛶'; // Reset to enter fullscreen icon/text
  1185. }
  1186. logMessage(`Closed section: ${sectionId}`);
  1187. if(sectionId === 'playlist-editor') {
  1188. document.querySelectorAll('#all_playlists .playlist-item').forEach(item => {
  1189. item.classList.remove('selected');
  1190. });
  1191. }
  1192. if(sectionId === 'pattern-preview-container') {
  1193. document.querySelectorAll('#theta_rho_files .file-item').forEach(item => {
  1194. item.classList.remove('selected');
  1195. });
  1196. }
  1197. } else {
  1198. logMessage(`Error: Section with ID "${sectionId}" not found`);
  1199. }
  1200. }
  1201. function attachFullScreenListeners() {
  1202. // Add event listener to all fullscreen buttons
  1203. document.querySelectorAll('.fullscreen-button').forEach(button => {
  1204. button.addEventListener('click', function () {
  1205. const stickySection = this.closest('.sticky'); // Find the closest sticky section
  1206. if (stickySection) {
  1207. // Close all other sections
  1208. document.querySelectorAll('.sticky').forEach(section => {
  1209. if (section !== stickySection) {
  1210. section.classList.remove('fullscreen');
  1211. section.classList.remove('visible');
  1212. section.classList.add('hidden');
  1213. // Reset the fullscreen button text for other sections
  1214. const otherFullscreenButton = section.querySelector('.fullscreen-button');
  1215. if (otherFullscreenButton) {
  1216. otherFullscreenButton.textContent = '⛶'; // Enter fullscreen icon/text
  1217. }
  1218. }
  1219. });
  1220. stickySection.classList.toggle('fullscreen'); // Toggle fullscreen class
  1221. // Update button icon or text
  1222. if (stickySection.classList.contains('fullscreen')) {
  1223. this.textContent = '-'; // Exit fullscreen icon/text
  1224. } else {
  1225. this.textContent = '⛶'; // Enter fullscreen icon/text
  1226. }
  1227. } else {
  1228. console.error('Error: Fullscreen button is not inside a sticky section.');
  1229. }
  1230. });
  1231. });
  1232. }
  1233. // Utility function to manage cookies
  1234. function setCookie(name, value, days) {
  1235. const date = new Date();
  1236. date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  1237. document.cookie = `${name}=${value};expires=${date.toUTCString()};path=/`;
  1238. }
  1239. function getCookie(name) {
  1240. const nameEQ = `${name}=`;
  1241. const cookies = document.cookie.split(';');
  1242. for (let i = 0; i < cookies.length; i++) {
  1243. let cookie = cookies[i].trim();
  1244. if (cookie.startsWith(nameEQ)) {
  1245. return cookie.substring(nameEQ.length);
  1246. }
  1247. }
  1248. return null;
  1249. }
  1250. // Save settings to cookies
  1251. function saveSettingsToCookies() {
  1252. // Save the pause time
  1253. const pauseTime = document.getElementById('pause_time').value;
  1254. setCookie('pause_time', pauseTime, 7);
  1255. // Save the clear pattern
  1256. const clearPattern = document.getElementById('clear_pattern').value;
  1257. setCookie('clear_pattern', clearPattern, 7);
  1258. // Save the run mode
  1259. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  1260. setCookie('run_mode', runMode, 7);
  1261. // Save shuffle playlist checkbox state
  1262. const shufflePlaylist = document.getElementById('shuffle_playlist').checked;
  1263. setCookie('shuffle_playlist', shufflePlaylist, 7);
  1264. // Save pre-execution action
  1265. const preExecution = document.getElementById('pre_execution').value;
  1266. setCookie('pre_execution', preExecution, 7);
  1267. // Save selected clear action
  1268. const clearAction = document.getElementById('clear_action_label').textContent.trim();
  1269. setCookie('clear_action', clearAction, 7);
  1270. logMessage('Settings saved.');
  1271. }
  1272. // Load settings from cookies
  1273. function loadSettingsFromCookies() {
  1274. // Load the pause time
  1275. const pauseTime = getCookie('pause_time');
  1276. if (pauseTime !== null) {
  1277. document.getElementById('pause_time').value = pauseTime;
  1278. }
  1279. // Load the clear pattern
  1280. const clearPattern = getCookie('clear_pattern');
  1281. if (clearPattern !== null) {
  1282. document.getElementById('clear_pattern').value = clearPattern;
  1283. }
  1284. // Load the run mode
  1285. const runMode = getCookie('run_mode');
  1286. if (runMode !== null) {
  1287. document.querySelector(`input[name="run_mode"][value="${runMode}"]`).checked = true;
  1288. }
  1289. // Load the shuffle playlist checkbox state
  1290. const shufflePlaylist = getCookie('shuffle_playlist');
  1291. if (shufflePlaylist !== null) {
  1292. document.getElementById('shuffle_playlist').checked = shufflePlaylist === 'true';
  1293. }
  1294. // Load the pre-execution action
  1295. const preExecution = getCookie('pre_execution');
  1296. if (preExecution !== null) {
  1297. document.getElementById('pre_execution').value = preExecution;
  1298. }
  1299. // Load selected clear action
  1300. const clearAction = getCookie('clear_action');
  1301. if (clearAction !== null) {
  1302. const clearLabel = document.getElementById('clear_action_label');
  1303. clearLabel.textContent = clearAction;
  1304. // Update the corresponding action function
  1305. if (clearAction === 'From Center') {
  1306. currentClearAction = 'runClearIn';
  1307. } else if (clearAction === 'From Perimeter') {
  1308. currentClearAction = 'runClearOut';
  1309. } else if (clearAction === 'Sideways') {
  1310. currentClearAction = 'runClearSide';
  1311. }
  1312. }
  1313. logMessage('Settings loaded from cookies.');
  1314. }
  1315. // Call this function to save settings when a value is changed
  1316. function attachSettingsSaveListeners() {
  1317. // Add event listeners to inputs
  1318. document.getElementById('pause_time').addEventListener('input', saveSettingsToCookies);
  1319. document.getElementById('clear_pattern').addEventListener('change', saveSettingsToCookies);
  1320. document.querySelectorAll('input[name="run_mode"]').forEach(input => {
  1321. input.addEventListener('change', saveSettingsToCookies);
  1322. });
  1323. document.getElementById('shuffle_playlist').addEventListener('change', saveSettingsToCookies);
  1324. document.getElementById('pre_execution').addEventListener('change', saveSettingsToCookies);
  1325. }
  1326. // Tab switching logic with cookie storage
  1327. function switchTab(tabName) {
  1328. // Store the active tab in a cookie
  1329. setCookie('activeTab', tabName, 7); // Store for 7 days
  1330. // Deactivate all tab content
  1331. document.querySelectorAll('.tab-content').forEach(tab => {
  1332. tab.classList.remove('active');
  1333. });
  1334. // Activate the selected tab content
  1335. const activeTab = document.getElementById(`${tabName}-tab`);
  1336. if (activeTab) {
  1337. activeTab.classList.add('active');
  1338. } else {
  1339. console.error(`Error: Tab "${tabName}" not found.`);
  1340. }
  1341. // Deactivate all nav buttons
  1342. document.querySelectorAll('.bottom-nav .tab-button').forEach(button => {
  1343. button.classList.remove('active');
  1344. });
  1345. // Activate the selected nav button
  1346. const activeNavButton = document.getElementById(`nav-${tabName}`);
  1347. if (activeNavButton) {
  1348. activeNavButton.classList.add('active');
  1349. } else {
  1350. console.error(`Error: Nav button for "${tabName}" not found.`);
  1351. }
  1352. }
  1353. // Initialization
  1354. document.addEventListener('DOMContentLoaded', () => {
  1355. const activeTab = getCookie('activeTab') || 'patterns'; // Default to 'patterns' tab
  1356. switchTab(activeTab); // Load the active tab
  1357. checkSerialStatus(); // Check serial connection status
  1358. loadThetaRhoFiles(); // Load files on page load
  1359. loadAllPlaylists(); // Load all playlists on page load
  1360. attachSettingsSaveListeners(); // Attach event listeners to save changes
  1361. attachFullScreenListeners();
  1362. });