main.js 61 KB

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