main.js 55 KB

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