main.js 62 KB

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