main.js 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031
  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, clickTargetId = null) {
  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.innerHTML = '<i class="fa-solid fa-xmark"></i>';
  46. closeButton.className = 'close-button no-bg';
  47. closeButton.onclick = (e) => {
  48. e.stopPropagation(); // Prevent triggering the clickTarget when the close button is clicked
  49. notification.classList.remove('show');
  50. setTimeout(() => notification.remove(), 250); // Match transition duration
  51. };
  52. notification.appendChild(closeButton);
  53. // Attach click event to the notification if a clickTargetId is provided
  54. if (clickTargetId) {
  55. notification.onclick = () => {
  56. const target = document.getElementById(clickTargetId);
  57. if (target) {
  58. // Find the closest <main> parent
  59. const parentMain = target.closest('main');
  60. if (parentMain) {
  61. // Remove 'active' class from all <main> elements
  62. document.querySelectorAll('main').forEach((main) => {
  63. main.classList.remove('active');
  64. });
  65. // Add 'active' class to the parent <main>
  66. parentMain.classList.add('active');
  67. target.click();
  68. // Update tab buttons based on the parent <main> ID
  69. const parentId = parentMain.id; // e.g., "patterns-tab"
  70. const tabId = `nav-${parentId.replace('-tab', '')}`; // e.g., "nav-patterns"
  71. document.querySelectorAll('.tab-button').forEach((button) => {
  72. button.classList.remove('active');
  73. });
  74. const tabButton = document.getElementById(tabId);
  75. if (tabButton) {
  76. tabButton.classList.add('active');
  77. }
  78. }
  79. }
  80. };
  81. }
  82. // Append the notification to the header
  83. header.appendChild(notification);
  84. // Trigger the transition
  85. requestAnimationFrame(() => {
  86. notification.classList.add('show');
  87. });
  88. // Auto-remove the notification after 5 seconds
  89. setTimeout(() => {
  90. if (notification.parentNode) {
  91. notification.classList.remove('show');
  92. setTimeout(() => notification.remove(), 250); // Match transition duration
  93. }
  94. }, 5000);
  95. // Also log the message to the status log if available
  96. if (log) {
  97. const entry = document.createElement('p');
  98. entry.textContent = message;
  99. log.appendChild(entry);
  100. log.scrollTop = log.scrollHeight; // Scroll to the bottom of the log
  101. }
  102. }
  103. function toggleDebugLog() {
  104. const statusLog = document.getElementById('status_log');
  105. const debugButton = document.getElementById('debug_button');
  106. if (statusLog.style.display === 'block') {
  107. statusLog.style.display = 'none';
  108. debugButton.classList.remove('active');
  109. } else {
  110. statusLog.style.display = 'block';
  111. debugButton.classList.add( 'active');
  112. statusLog.scrollIntoView({ behavior: 'smooth', block: 'start' }); // Smooth scrolling to the log
  113. }
  114. }
  115. // File selection logic
  116. async function selectFile(file, listItem) {
  117. selectedFile = file;
  118. // Highlight the selected file
  119. document.querySelectorAll('#theta_rho_files li').forEach(li => li.classList.remove('selected'));
  120. listItem.classList.add('selected');
  121. // Update the Remove button visibility
  122. const removeButton = document.querySelector('#pattern-preview-container .remove-button');
  123. if (file.startsWith('custom_patterns/')) {
  124. removeButton.classList.remove('hidden');
  125. } else {
  126. removeButton.classList.add('hidden');
  127. }
  128. logMessage(`Selected file: ${file}`);
  129. await previewPattern(file);
  130. // Populate the playlist dropdown after selecting a pattern
  131. await populatePlaylistDropdown();
  132. }
  133. // Fetch and display Theta-Rho files
  134. async function loadThetaRhoFiles() {
  135. try {
  136. logMessage('Loading Theta-Rho files...');
  137. const response = await fetch('/list_theta_rho_files');
  138. let files = await response.json();
  139. files = files.filter(file => file.endsWith('.thr'));
  140. // Sort files with custom_patterns on top and all alphabetically sorted
  141. const sortedFiles = files.sort((a, b) => {
  142. const isCustomA = a.startsWith('custom_patterns/');
  143. const isCustomB = b.startsWith('custom_patterns/');
  144. if (isCustomA && !isCustomB) return -1; // a comes first
  145. if (!isCustomA && isCustomB) return 1; // b comes first
  146. return a.localeCompare(b); // Alphabetical comparison
  147. });
  148. allFiles = sortedFiles; // Update global files
  149. displayFiles(sortedFiles); // Display sorted files
  150. logMessage('Theta-Rho files loaded and sorted successfully.');
  151. } catch (error) {
  152. logMessage(`Error loading Theta-Rho files: ${error.message}`, 'error');
  153. }
  154. }
  155. // Display files in the UI
  156. function displayFiles(files) {
  157. const ul = document.getElementById('theta_rho_files');
  158. if (!ul) {
  159. logMessage('Error: File list container not found');
  160. return;
  161. }
  162. ul.innerHTML = ''; // Clear existing list
  163. files.forEach(file => {
  164. const li = document.createElement('li');
  165. li.textContent = file;
  166. li.classList.add('file-item');
  167. // Attach file selection handler
  168. li.onclick = () => selectFile(file, li);
  169. ul.appendChild(li);
  170. });
  171. }
  172. // Filter files by search input
  173. function searchPatternFiles() {
  174. const searchInput = document.getElementById('search_pattern').value.toLowerCase();
  175. const filteredFiles = allFiles.filter(file => file.toLowerCase().includes(searchInput));
  176. displayFiles(filteredFiles);
  177. }
  178. // Upload a new Theta-Rho file
  179. async function uploadThetaRho() {
  180. const fileInput = document.getElementById('upload_file');
  181. const file = fileInput.files[0];
  182. if (!file) {
  183. logMessage('No file selected for upload.', LOG_TYPE.ERROR);
  184. return;
  185. }
  186. try {
  187. logMessage(`Uploading file: ${file.name}...`);
  188. const formData = new FormData();
  189. formData.append('file', file);
  190. const response = await fetch('/upload_theta_rho', {
  191. method: 'POST',
  192. body: formData
  193. });
  194. const result = await response.json();
  195. if (result.success) {
  196. logMessage(`File uploaded successfully: ${file.name}`, LOG_TYPE.SUCCESS);
  197. fileInput.value = '';
  198. await loadThetaRhoFiles();
  199. } else {
  200. logMessage(`Failed to upload file: ${file.name}`, LOG_TYPE.ERROR);
  201. }
  202. } catch (error) {
  203. logMessage(`Error uploading file: ${error.message}`);
  204. }
  205. }
  206. async function runThetaRho() {
  207. if (!selectedFile) {
  208. logMessage("No file selected to run.");
  209. return;
  210. }
  211. // Get the selected pre-execution action
  212. const preExecutionAction = document.getElementById('pre_execution').value;
  213. logMessage(`Running file: ${selectedFile} with pre-execution action: ${preExecutionAction}...`);
  214. try {
  215. const response = await fetch('/run_theta_rho', {
  216. method: 'POST',
  217. headers: { 'Content-Type': 'application/json' },
  218. body: JSON.stringify({
  219. file_name: selectedFile,
  220. pre_execution: preExecutionAction
  221. })
  222. });
  223. const result = await response.json();
  224. if (response.ok) {
  225. // Connect WebSocket when starting a pattern
  226. connectStatusWebSocket();
  227. // Show the currently playing UI immediately
  228. document.body.classList.add('playing');
  229. const currentlyPlayingFile = document.getElementById('currently-playing-file');
  230. if (currentlyPlayingFile) {
  231. currentlyPlayingFile.textContent = selectedFile.replace('./patterns/', '');
  232. }
  233. // Show initial preview
  234. previewPattern(selectedFile.replace('./patterns/', ''), 'currently-playing-container');
  235. logMessage(`Pattern running: ${selectedFile}`, LOG_TYPE.SUCCESS);
  236. } else {
  237. if (response.status === 409) {
  238. logMessage("Cannot start pattern: Another pattern is already running", LOG_TYPE.WARNING);
  239. } else {
  240. logMessage(`Failed to run file: ${result.detail || 'Unknown error'}`, LOG_TYPE.ERROR);
  241. }
  242. }
  243. } catch (error) {
  244. logMessage(`Error running pattern: ${error.message}`, LOG_TYPE.ERROR);
  245. }
  246. }
  247. async function stopExecution() {
  248. logMessage('Stopping execution...');
  249. const response = await fetch('/stop_execution', { method: 'POST' });
  250. const result = await response.json();
  251. if (result.success) {
  252. logMessage('Execution stopped.',LOG_TYPE.SUCCESS);
  253. } else {
  254. logMessage('Failed to stop execution.',LOG_TYPE.ERROR);
  255. }
  256. }
  257. let isPaused = false;
  258. function togglePausePlay() {
  259. const button = document.getElementById("pausePlayCurrent");
  260. if (isPaused) {
  261. // Resume execution
  262. fetch('/resume_execution', { method: 'POST' })
  263. .then(response => response.json())
  264. .then(data => {
  265. if (data.success) {
  266. isPaused = false;
  267. button.innerHTML = "<i class=\"fa-solid fa-pause\"></i>"; // Change to pause icon
  268. }
  269. })
  270. .catch(error => console.error("Error resuming execution:", error));
  271. } else {
  272. // Pause execution
  273. fetch('/pause_execution', { method: 'POST' })
  274. .then(response => response.json())
  275. .then(data => {
  276. if (data.success) {
  277. isPaused = true;
  278. button.innerHTML = "<i class=\"fa-solid fa-play\"></i>"; // Change to play icon
  279. }
  280. })
  281. .catch(error => console.error("Error pausing execution:", error));
  282. }
  283. }
  284. function removeCurrentPattern() {
  285. if (!selectedFile) {
  286. logMessage('No file selected to remove.', LOG_TYPE.ERROR);
  287. return;
  288. }
  289. if (!selectedFile.startsWith('custom_patterns/')) {
  290. logMessage('Only custom patterns can be removed.', LOG_TYPE.WARNING);
  291. return;
  292. }
  293. removeCustomPattern(selectedFile);
  294. }
  295. // Delete the selected file
  296. async function removeCustomPattern(fileName) {
  297. const userConfirmed = confirm(`Are you sure you want to delete the pattern "${fileName}"?`);
  298. if (!userConfirmed) return;
  299. try {
  300. logMessage(`Deleting pattern: ${fileName}...`);
  301. const response = await fetch('/delete_theta_rho_file', {
  302. method: 'POST',
  303. headers: { 'Content-Type': 'application/json' },
  304. body: JSON.stringify({ file_name: fileName })
  305. });
  306. const result = await response.json();
  307. if (result.success) {
  308. logMessage(`File deleted successfully: ${selectedFile}`, LOG_TYPE.SUCCESS);
  309. // Close the preview container
  310. const previewContainer = document.getElementById('pattern-preview-container');
  311. if (previewContainer) {
  312. previewContainer.classList.add('hidden');
  313. previewContainer.classList.remove('visible');
  314. }
  315. // Clear the selected file and refresh the file list
  316. selectedFile = null;
  317. await loadThetaRhoFiles(); // Refresh the file list
  318. } else {
  319. logMessage(`Failed to delete pattern "${fileName}": ${result.error}`, LOG_TYPE.ERROR);
  320. }
  321. } catch (error) {
  322. logMessage(`Error deleting pattern: ${error.message}`);
  323. }
  324. }
  325. // Preview a Theta-Rho file
  326. async function previewPattern(fileName, containerId = 'pattern-preview-container') {
  327. try {
  328. logMessage(`Fetching data to preview file: ${fileName}...`);
  329. const response = await fetch('/preview_thr', {
  330. method: 'POST',
  331. headers: { 'Content-Type': 'application/json' },
  332. body: JSON.stringify({ file_name: fileName })
  333. });
  334. const result = await response.json();
  335. if (result.success) {
  336. // Mirror the theta values in the coordinates
  337. const coordinates = result.coordinates.map(coord => [
  338. (coord[0] < Math.PI) ?
  339. Math.PI - coord[0] : // For first half
  340. 3 * Math.PI - coord[0], // For second half
  341. coord[1]
  342. ]);
  343. // Render the pattern in the specified container
  344. const canvasId = containerId === 'currently-playing-container'
  345. ? 'currentlyPlayingCanvas'
  346. : 'patternPreviewCanvas';
  347. renderPattern(coordinates, canvasId);
  348. // Update coordinate display
  349. const firstCoordElement = document.getElementById('first_coordinate');
  350. const lastCoordElement = document.getElementById('last_coordinate');
  351. if (firstCoordElement) {
  352. const firstCoord = coordinates[0];
  353. firstCoordElement.textContent = `First Coordinate: θ=${firstCoord[0].toFixed(2)}, ρ=${firstCoord[1].toFixed(2)}`;
  354. } else {
  355. logMessage('First coordinate element not found.', LOG_TYPE.WARNING);
  356. }
  357. if (lastCoordElement) {
  358. const lastCoord = coordinates[coordinates.length - 1];
  359. lastCoordElement.textContent = `Last Coordinate: θ=${lastCoord[0].toFixed(2)}, ρ=${lastCoord[1].toFixed(2)}`;
  360. } else {
  361. logMessage('Last coordinate element not found.', LOG_TYPE.WARNING);
  362. }
  363. // Show the preview container
  364. const previewContainer = document.getElementById(containerId);
  365. if (previewContainer) {
  366. previewContainer.classList.remove('hidden');
  367. previewContainer.classList.add('visible');
  368. } else {
  369. logMessage(`Preview container not found: ${containerId}`, LOG_TYPE.ERROR);
  370. }
  371. } else {
  372. logMessage(`Failed to fetch preview for file: ${fileName}`, LOG_TYPE.WARNING);
  373. }
  374. } catch (error) {
  375. logMessage(`Error previewing pattern: ${error.message}`, LOG_TYPE.ERROR);
  376. }
  377. }
  378. // Render the pattern on a canvas
  379. function renderPattern(coordinates, canvasId) {
  380. const canvas = document.getElementById(canvasId);
  381. if (!canvas) {
  382. logMessage(`Canvas element not found: ${canvasId}`, LOG_TYPE.ERROR);
  383. return;
  384. }
  385. if (!(canvas instanceof HTMLCanvasElement)) {
  386. logMessage(`Element with ID "${canvasId}" is not a canvas.`, LOG_TYPE.ERROR);
  387. return;
  388. }
  389. const ctx = canvas.getContext('2d');
  390. if (!ctx) {
  391. logMessage(`Could not get 2D context for canvas: ${canvasId}`, LOG_TYPE.ERROR);
  392. return;
  393. }
  394. // Account for device pixel ratio
  395. const dpr = window.devicePixelRatio || 1;
  396. const rect = canvas.getBoundingClientRect();
  397. canvas.width = rect.width * dpr; // Scale canvas width for high DPI
  398. canvas.height = rect.height * dpr; // Scale canvas height for high DPI
  399. ctx.scale(dpr, dpr); // Scale drawing context
  400. ctx.clearRect(0, 0, canvas.width, canvas.height);
  401. const centerX = rect.width / 2; // Use bounding client rect dimensions
  402. const centerY = rect.height / 2;
  403. const maxRho = Math.max(...coordinates.map(coord => coord[1]));
  404. const scale = Math.min(rect.width, rect.height) / (2 * maxRho); // Scale to fit
  405. ctx.beginPath();
  406. ctx.strokeStyle = 'white';
  407. coordinates.forEach(([theta, rho], index) => {
  408. const x = centerX + rho * Math.cos(theta) * scale;
  409. const y = centerY - rho * Math.sin(theta) * scale;
  410. if (index === 0) ctx.moveTo(x, y);
  411. else ctx.lineTo(x, y);
  412. });
  413. ctx.stroke();
  414. }
  415. async function moveToCenter() {
  416. logMessage('Moving to center...', LOG_TYPE.INFO);
  417. const response = await fetch('/move_to_center', { method: 'POST' });
  418. const result = await response.json();
  419. if (result.success) {
  420. logMessage('Moved to center successfully.', LOG_TYPE.SUCCESS);
  421. } else {
  422. logMessage(`Failed to move to center: ${result.error}`, LOG_TYPE.ERROR);
  423. }
  424. }
  425. async function moveToPerimeter() {
  426. logMessage('Moving to perimeter...', LOG_TYPE.INFO);
  427. const response = await fetch('/move_to_perimeter', { method: 'POST' });
  428. const result = await response.json();
  429. if (result.success) {
  430. logMessage('Moved to perimeter successfully.', LOG_TYPE.SUCCESS);
  431. } else {
  432. logMessage(`Failed to move to perimeter: ${result.error}`, LOG_TYPE.ERROR);
  433. }
  434. }
  435. async function sendCoordinate() {
  436. const theta = parseFloat(document.getElementById('theta_input').value);
  437. const rho = parseFloat(document.getElementById('rho_input').value);
  438. if (isNaN(theta) || isNaN(rho)) {
  439. logMessage('Invalid input: θ and ρ must be numbers.', LOG_TYPE.ERROR);
  440. return;
  441. }
  442. logMessage(`Sending coordinate: θ=${theta}, ρ=${rho}...`);
  443. const response = await fetch('/send_coordinate', {
  444. method: 'POST',
  445. headers: { 'Content-Type': 'application/json' },
  446. body: JSON.stringify({ theta, rho })
  447. });
  448. const result = await response.json();
  449. if (result.success) {
  450. logMessage(`Coordinate executed successfully: θ=${theta}, ρ=${rho}`, LOG_TYPE.SUCCESS);
  451. } else {
  452. logMessage(`Failed to execute coordinate: ${result.error}`, LOG_TYPE.ERROR);
  453. }
  454. }
  455. async function sendHomeCommand() {
  456. const response = await fetch('/send_home', { method: 'POST' });
  457. const result = await response.json();
  458. if (result.success) {
  459. logMessage('HOME command sent successfully.', LOG_TYPE.SUCCESS);
  460. } else {
  461. logMessage('Failed to send HOME command.', LOG_TYPE.ERROR);
  462. }
  463. }
  464. async function runClearIn() {
  465. logMessage('Running clear from center pattern...', LOG_TYPE.INFO);
  466. try {
  467. const response = await fetch('/run_theta_rho', {
  468. method: 'POST',
  469. headers: { 'Content-Type': 'application/json' },
  470. body: JSON.stringify({
  471. file_name: 'clear_from_in.thr',
  472. pre_execution: 'none'
  473. })
  474. });
  475. if (!response.ok) {
  476. if (response.status === 409) {
  477. logMessage('Cannot start pattern: Another pattern is already running', LOG_TYPE.WARNING);
  478. return;
  479. }
  480. throw new Error(`HTTP error! status: ${response.status}`);
  481. }
  482. const result = await response.json();
  483. if (result.success) {
  484. logMessage('Clear from center pattern started', LOG_TYPE.SUCCESS);
  485. } else {
  486. logMessage('Failed to run clear pattern', LOG_TYPE.ERROR);
  487. }
  488. } catch (error) {
  489. logMessage(`Error running clear pattern: ${error}`, LOG_TYPE.ERROR);
  490. }
  491. }
  492. async function runClearOut() {
  493. logMessage('Running clear from perimeter pattern...', LOG_TYPE.INFO);
  494. try {
  495. const response = await fetch('/run_theta_rho', {
  496. method: 'POST',
  497. headers: { 'Content-Type': 'application/json' },
  498. body: JSON.stringify({
  499. file_name: 'clear_from_out.thr',
  500. pre_execution: 'none'
  501. })
  502. });
  503. if (!response.ok) {
  504. if (response.status === 409) {
  505. logMessage('Cannot start pattern: Another pattern is already running', LOG_TYPE.WARNING);
  506. return;
  507. }
  508. throw new Error(`HTTP error! status: ${response.status}`);
  509. }
  510. const result = await response.json();
  511. if (result.success) {
  512. logMessage('Clear from perimeter pattern started', LOG_TYPE.SUCCESS);
  513. } else {
  514. logMessage('Failed to run clear pattern', LOG_TYPE.ERROR);
  515. }
  516. } catch (error) {
  517. logMessage(`Error running clear pattern: ${error}`, LOG_TYPE.ERROR);
  518. }
  519. }
  520. async function runClearSide() {
  521. logMessage('Running clear sideways pattern...', LOG_TYPE.INFO);
  522. try {
  523. const response = await fetch('/run_theta_rho', {
  524. method: 'POST',
  525. headers: { 'Content-Type': 'application/json' },
  526. body: JSON.stringify({
  527. file_name: 'clear_sideway.thr',
  528. pre_execution: 'none'
  529. })
  530. });
  531. if (!response.ok) {
  532. if (response.status === 409) {
  533. logMessage('Cannot start pattern: Another pattern is already running', LOG_TYPE.WARNING);
  534. return;
  535. }
  536. throw new Error(`HTTP error! status: ${response.status}`);
  537. }
  538. const result = await response.json();
  539. if (result.success) {
  540. logMessage('Clear sideways pattern started', LOG_TYPE.SUCCESS);
  541. } else {
  542. logMessage('Failed to run clear pattern', LOG_TYPE.ERROR);
  543. }
  544. } catch (error) {
  545. logMessage(`Error running clear pattern: ${error}`, LOG_TYPE.ERROR);
  546. }
  547. }
  548. let scrollPosition = 0;
  549. function scrollSelection(direction) {
  550. const container = document.getElementById('clear_selection');
  551. const itemHeight = 50; // Adjust based on CSS height
  552. const maxScroll = container.children.length - 1;
  553. // Update scroll position
  554. scrollPosition += direction;
  555. scrollPosition = Math.max(0, Math.min(scrollPosition, maxScroll));
  556. // Update the transform to scroll items
  557. container.style.transform = `translateY(-${scrollPosition * itemHeight}px)`;
  558. setCookie('clear_action_index', scrollPosition, 365);
  559. }
  560. function executeClearAction(actionFunction) {
  561. // Save the new action to a cookie (optional)
  562. setCookie('clear_action', actionFunction, 365);
  563. if (actionFunction && typeof window[actionFunction] === 'function') {
  564. window[actionFunction](); // Execute the selected clear action
  565. } else {
  566. logMessage('No clear action selected or function not found.', LOG_TYPE.ERROR);
  567. }
  568. }
  569. async function runFile(fileName) {
  570. const response = await fetch(`/run_theta_rho_file/${fileName}`, { method: 'POST' });
  571. const result = await response.json();
  572. if (result.success) {
  573. logMessage(`Running file: ${fileName}`, LOG_TYPE.SUCCESS);
  574. } else {
  575. logMessage(`Failed to run file: ${fileName}`, LOG_TYPE.ERROR);
  576. }
  577. }
  578. // Connection Status
  579. async function checkSerialStatus() {
  580. const response = await fetch('/serial_status');
  581. const status = await response.json();
  582. const statusElement = document.getElementById('serial_status');
  583. const statusHeaderElement = document.getElementById('connection_status_header');
  584. const serialPortsContainer = document.getElementById('serial_ports_container');
  585. const selectElement = document.getElementById('serial_ports');
  586. const connectButton = document.querySelector('button[onclick="connectSerial()"]');
  587. const disconnectButton = document.querySelector('button[onclick="disconnectSerial()"]');
  588. const restartButton = document.querySelector('button[onclick="restartSerial()"]');
  589. if (status.connected) {
  590. const port = status.port || 'Unknown'; // Fallback if port is undefined
  591. statusElement.textContent = `Connected to ${port}`;
  592. statusElement.classList.add('connected');
  593. statusElement.classList.remove('not-connected');
  594. logMessage(`Connected to serial port: ${port}`);
  595. // Update header status
  596. statusHeaderElement.classList.add('connected');
  597. statusHeaderElement.classList.remove('not-connected');
  598. // Hide Available Ports and show disconnect/restart buttons
  599. serialPortsContainer.style.display = 'none';
  600. connectButton.style.display = 'none';
  601. disconnectButton.style.display = 'flex';
  602. restartButton.style.display = 'flex';
  603. // Preselect the connected port in the dropdown
  604. const newOption = document.createElement('option');
  605. newOption.value = port;
  606. newOption.textContent = port;
  607. selectElement.appendChild(newOption);
  608. selectElement.value = port;
  609. } else {
  610. statusElement.textContent = 'Not connected';
  611. statusElement.classList.add('not-connected');
  612. statusElement.classList.remove('connected');
  613. logMessage('No active connection.');
  614. // Update header status
  615. statusHeaderElement.classList.add('not-connected');
  616. statusHeaderElement.classList.remove('connected');
  617. // Show Available Ports and the connect button
  618. serialPortsContainer.style.display = 'block';
  619. connectButton.style.display = 'flex';
  620. disconnectButton.style.display = 'none';
  621. restartButton.style.display = 'none';
  622. // Attempt to auto-load available ports
  623. await loadSerialPorts();
  624. }
  625. }
  626. async function loadSerialPorts() {
  627. const response = await fetch('/list_serial_ports');
  628. const ports = await response.json();
  629. const select = document.getElementById('serial_ports');
  630. select.innerHTML = '';
  631. ports.forEach(port => {
  632. const option = document.createElement('option');
  633. option.value = port;
  634. option.textContent = port;
  635. select.appendChild(option);
  636. });
  637. logMessage('Serial ports loaded.');
  638. }
  639. async function connectSerial() {
  640. const port = document.getElementById('serial_ports').value;
  641. const response = await fetch('/connect', {
  642. method: 'POST',
  643. headers: { 'Content-Type': 'application/json' },
  644. body: JSON.stringify({ port })
  645. });
  646. const result = await response.json();
  647. if (result.success) {
  648. logMessage(`Connected to serial port: ${port}`, LOG_TYPE.SUCCESS);
  649. // Refresh the status
  650. await checkSerialStatus();
  651. } else {
  652. logMessage(`Error connecting to serial port: ${result.error}`, LOG_TYPE.ERROR);
  653. }
  654. }
  655. async function disconnectSerial() {
  656. const response = await fetch('/disconnect', { method: 'POST' });
  657. const result = await response.json();
  658. if (result.success) {
  659. logMessage('Serial port disconnected.', LOG_TYPE.SUCCESS);
  660. // Refresh the status
  661. await checkSerialStatus();
  662. } else {
  663. logMessage(`Error disconnecting: ${result.error}`, LOG_TYPE.ERROR);
  664. }
  665. }
  666. async function restartSerial() {
  667. const port = document.getElementById('serial_ports').value;
  668. const response = await fetch('/restart_connection', {
  669. method: 'POST',
  670. headers: { 'Content-Type': 'application/json' },
  671. body: JSON.stringify({ port })
  672. });
  673. const result = await response.json();
  674. if (result.success) {
  675. document.getElementById('serial_status').textContent = `Restarted connection to ${port}`;
  676. logMessage('Connection restarted.', LOG_TYPE.SUCCESS);
  677. // No need to change visibility for restart
  678. } else {
  679. logMessage(`Error restarting Connection: ${result.error}`, LOG_TYPE.ERROR);
  680. }
  681. }
  682. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  683. // Firmware / Software Updater
  684. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  685. async function checkForUpdates() {
  686. try {
  687. const response = await fetch('/check_software_update');
  688. const data = await response.json();
  689. // Handle updates available logic
  690. if (data.updates_available) {
  691. const updateButton = document.getElementById('update-software-btn');
  692. const updateLinkElement = document.getElementById('update_link');
  693. const tagLink = `https://github.com/tuanchris/dune-weaver/releases/tag/${data.latest_remote_tag}`;
  694. updateButton.classList.remove('hidden'); // Show the button
  695. logMessage("Software Update Available", LOG_TYPE.INFO, 'open-settings-button')
  696. updateLinkElement.innerHTML = `<a href="${tagLink}" target="_blank">View Release Notes </a>`;
  697. updateLinkElement.classList.remove('hidden'); // Show the link
  698. }
  699. // Update current and latest version in the UI
  700. const currentVersionElem = document.getElementById('current_git_version');
  701. const latestVersionElem = document.getElementById('latest_git_version');
  702. currentVersionElem.textContent = `Current Version: ${data.latest_local_tag || 'Unknown'}`;
  703. latestVersionElem.textContent = data.updates_available
  704. ? `Latest Version: ${data.latest_remote_tag}`
  705. : 'You are up to date!';
  706. } catch (error) {
  707. console.error('Error checking for updates:', error);
  708. }
  709. }
  710. async function updateSoftware() {
  711. const updateButton = document.getElementById('update-software-btn');
  712. try {
  713. // Disable the button and update the text
  714. updateButton.disabled = true;
  715. updateButton.querySelector('span').textContent = 'Updating...';
  716. const response = await fetch('/update_software', { method: 'POST' });
  717. const data = await response.json();
  718. if (data.success) {
  719. logMessage('Software updated successfully!', LOG_TYPE.SUCCESS);
  720. window.location.reload(); // Reload the page after update
  721. } else {
  722. logMessage('Failed to update software: ' + data.error, LOG_TYPE.ERROR);
  723. }
  724. } catch (error) {
  725. console.error('Error updating software:', error);
  726. logMessage('Failed to update software', LOG_TYPE.ERROR);
  727. } finally {
  728. // Re-enable the button and reset the text
  729. updateButton.disabled = false;
  730. updateButton.textContent = 'Update Software'; // Adjust to the original text
  731. }
  732. }
  733. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  734. // PART A: Loading / listing playlists from the server
  735. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  736. async function loadAllPlaylists() {
  737. try {
  738. const response = await fetch('/list_all_playlists'); // GET
  739. const allPlaylists = await response.json(); // e.g. ["My Playlist", "Summer", ...]
  740. displayAllPlaylists(allPlaylists);
  741. } catch (err) {
  742. logMessage(`Error loading playlists: ${err}`, LOG_TYPE.ERROR);
  743. }
  744. }
  745. // Function to display all playlists with Load, Run, and Delete buttons
  746. function displayAllPlaylists(playlists) {
  747. const ul = document.getElementById('all_playlists');
  748. ul.innerHTML = ''; // Clear current list
  749. if (playlists.length === 0) {
  750. // Add a placeholder if the list is empty
  751. const emptyLi = document.createElement('li');
  752. emptyLi.textContent = "You don't have any playlists yet.";
  753. emptyLi.classList.add('empty-placeholder'); // Optional: Add a class for styling
  754. ul.appendChild(emptyLi);
  755. return;
  756. }
  757. playlists.forEach(playlistName => {
  758. const li = document.createElement('li');
  759. li.textContent = playlistName;
  760. li.classList.add('playlist-item'); // Add a class for styling
  761. // Attach click event to handle selection
  762. li.onclick = () => {
  763. // Remove 'selected' class from all items
  764. document.querySelectorAll('#all_playlists li').forEach(item => {
  765. item.classList.remove('selected');
  766. });
  767. // Add 'selected' class to the clicked item
  768. li.classList.add('selected');
  769. // Open the playlist editor for the selected playlist
  770. openPlaylistEditor(playlistName);
  771. };
  772. ul.appendChild(li);
  773. });
  774. }
  775. // Cancel changes and close the editor
  776. function cancelPlaylistChanges() {
  777. playlist = [...originalPlaylist]; // Revert to the original playlist
  778. isPlaylistChanged = false;
  779. toggleSaveCancelButtons(false); // Hide the save and cancel buttons
  780. refreshPlaylistUI(); // Refresh the UI with the original state
  781. closeStickySection('playlist-editor'); // Close the editor
  782. }
  783. // Open the playlist editor
  784. function openPlaylistEditor(playlistName) {
  785. logMessage(`Opening editor for playlist: ${playlistName}`);
  786. const editorSection = document.getElementById('playlist-editor');
  787. // Update the displayed playlist name
  788. document.getElementById('playlist_name_display').textContent = playlistName;
  789. // Store the current playlist name for renaming
  790. document.getElementById('playlist_name_input').value = playlistName;
  791. editorSection.classList.remove('hidden');
  792. editorSection.classList.add('visible');
  793. loadPlaylist(playlistName);
  794. }
  795. function clearSchedule() {
  796. document.getElementById("start_time").value = "";
  797. document.getElementById("end_time").value = "";
  798. document.getElementById('clear_time').style.display = 'none';
  799. setCookie('start_time', '', 365);
  800. setCookie('end_time', '', 365);
  801. }
  802. // Function to run the selected playlist with specified parameters
  803. async function runPlaylist() {
  804. const playlistName = document.getElementById('playlist_name_display').textContent;
  805. if (!playlistName) {
  806. logMessage('No playlist selected', 'error');
  807. return;
  808. }
  809. const pauseTime = parseFloat(document.getElementById('pause_time').value) || 0;
  810. const clearPattern = document.getElementById('clear_pattern').value;
  811. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  812. const shuffle = document.getElementById('shuffle_playlist').checked;
  813. try {
  814. const response = await fetch('/run_playlist', {
  815. method: 'POST',
  816. headers: {
  817. 'Content-Type': 'application/json',
  818. },
  819. body: JSON.stringify({
  820. playlist_name: playlistName,
  821. pause_time: pauseTime,
  822. clear_pattern: clearPattern,
  823. run_mode: runMode,
  824. shuffle: shuffle
  825. })
  826. });
  827. if (!response.ok) {
  828. if (response.status === 409) {
  829. logMessage('Another pattern is already running', 'warning');
  830. } else {
  831. const errorData = await response.json();
  832. logMessage(errorData.detail || 'Failed to run playlist', 'error');
  833. }
  834. return;
  835. }
  836. // Connect WebSocket when starting a playlist
  837. connectStatusWebSocket();
  838. logMessage(`Started playlist: ${playlistName}`, 'success');
  839. // Close the playlist editor container after successfully starting the playlist
  840. closeStickySection('playlist-editor');
  841. } catch (error) {
  842. logMessage('Error running playlist: ' + error, 'error');
  843. }
  844. }
  845. // Track changes in the playlist
  846. let originalPlaylist = [];
  847. let isPlaylistChanged = false;
  848. // Load playlist and set the original state
  849. async function loadPlaylist(playlistName) {
  850. try {
  851. logMessage(`Loading playlist: ${playlistName}`);
  852. const response = await fetch(`/get_playlist?name=${encodeURIComponent(playlistName)}`);
  853. const data = await response.json();
  854. if (!data.name) {
  855. throw new Error('Playlist name is missing in the response.');
  856. }
  857. // Populate playlist items and set original state
  858. playlist = data.files || [];
  859. originalPlaylist = [...playlist]; // Clone the playlist as the original
  860. isPlaylistChanged = false; // Reset change tracking
  861. toggleSaveCancelButtons(false); // Hide the save and cancel buttons initially
  862. refreshPlaylistUI();
  863. logMessage(`Loaded playlist: "${playlistName}" with ${playlist.length} file(s).`);
  864. } catch (err) {
  865. logMessage(`Error loading playlist: ${err.message}`, LOG_TYPE.ERROR);
  866. console.error('Error details:', err);
  867. }
  868. }
  869. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  870. // PART B: Creating or Saving (Overwriting) a Playlist
  871. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  872. // Instead of separate create/modify functions, we'll unify them:
  873. async function savePlaylist() {
  874. const name = document.getElementById('playlist_name_display').textContent
  875. if (!name) {
  876. logMessage("Please enter a playlist name.");
  877. return;
  878. }
  879. if (playlist.length === 0) {
  880. logMessage("No files in this playlist. Add files first.");
  881. return;
  882. }
  883. logMessage(`Saving playlist "${name}" with ${playlist.length} file(s)...`);
  884. try {
  885. // We can use /create_playlist or /modify_playlist. They do roughly the same in our single-file approach.
  886. // Let's use /create_playlist to always overwrite or create anew.
  887. const response = await fetch('/create_playlist', {
  888. method: 'POST',
  889. headers: { 'Content-Type': 'application/json' },
  890. body: JSON.stringify({
  891. playlist_name: name,
  892. files: playlist
  893. })
  894. });
  895. const result = await response.json();
  896. if (result.success) {
  897. logMessage(`Playlist "${name}" with ${playlist.length} patterns saved`, LOG_TYPE.SUCCESS);
  898. // Reload the entire list of playlists to reflect changes
  899. // Check for changes and refresh the UI
  900. detectPlaylistChanges();
  901. refreshPlaylistUI();
  902. // Restore default action buttons
  903. toggleSaveCancelButtons(false);
  904. } else {
  905. logMessage(`Failed to save playlist: ${result.error}`, LOG_TYPE.ERROR);
  906. }
  907. } catch (err) {
  908. logMessage(`Error saving playlist: ${err}`);
  909. }
  910. }
  911. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  912. // PART C: Renaming and Deleting a playlist
  913. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  914. // Toggle the rename playlist input
  915. function populatePlaylistDropdown() {
  916. return fetch('/list_all_playlists')
  917. .then(response => response.json())
  918. .then(playlists => {
  919. const select = document.getElementById('select-playlist');
  920. select.innerHTML = ''; // Clear existing options
  921. // Retrieve the saved playlist from the cookie
  922. const savedPlaylist = getCookie('selected_playlist');
  923. // Check if there are playlists available
  924. if (playlists.length === 0) {
  925. // Add a placeholder option if no playlists are available
  926. const placeholderOption = document.createElement('option');
  927. placeholderOption.value = '';
  928. placeholderOption.textContent = 'No playlists available';
  929. placeholderOption.disabled = true; // Prevent selection
  930. placeholderOption.selected = true; // Set as default
  931. select.appendChild(placeholderOption);
  932. return;
  933. }
  934. playlists.forEach(playlist => {
  935. const option = document.createElement('option');
  936. option.value = playlist;
  937. option.textContent = playlist;
  938. // Mark the saved playlist as selected
  939. if (playlist === savedPlaylist) {
  940. option.selected = true;
  941. }
  942. select.appendChild(option);
  943. });
  944. // Attach the onchange event listener after populating the dropdown
  945. select.addEventListener('change', function () {
  946. const selectedPlaylist = this.value;
  947. setCookie('selected_playlist', selectedPlaylist, 365); // Save to cookie
  948. logMessage(`Selected playlist saved: ${selectedPlaylist}`);
  949. });
  950. logMessage('Playlist dropdown populated, event listener attached, and saved playlist restored.');
  951. })
  952. .catch(error => logMessage(`Error fetching playlists: ${error.message}`));
  953. }
  954. populatePlaylistDropdown().then(() => {
  955. loadSettingsFromCookies(); // Restore selected playlist after populating the dropdown
  956. });
  957. // Confirm and save the renamed playlist
  958. async function confirmAddPlaylist() {
  959. const playlistNameInput = document.getElementById('new_playlist_name');
  960. const playlistName = playlistNameInput.value.trim();
  961. if (!playlistName) {
  962. logMessage('Playlist name cannot be empty.', LOG_TYPE.ERROR);
  963. return;
  964. }
  965. try {
  966. logMessage(`Adding new playlist: "${playlistName}"...`);
  967. const response = await fetch('/create_playlist', {
  968. method: 'POST',
  969. headers: { 'Content-Type': 'application/json' },
  970. body: JSON.stringify({
  971. playlist_name: playlistName,
  972. files: [] // New playlist starts empty
  973. })
  974. });
  975. const result = await response.json();
  976. if (result.success) {
  977. logMessage(`Playlist "${playlistName}" created successfully.`, LOG_TYPE.SUCCESS);
  978. // Clear the input field
  979. playlistNameInput.value = '';
  980. // Refresh the playlist list
  981. loadAllPlaylists();
  982. populatePlaylistDropdown();
  983. // Hide the add playlist container
  984. toggleSecondaryButtons('add-playlist-container');
  985. } else {
  986. logMessage(`Failed to create playlist: ${result.error}`, LOG_TYPE.ERROR);
  987. }
  988. } catch (error) {
  989. logMessage(`Error creating playlist: ${error.message}`);
  990. }
  991. }
  992. async function confirmRenamePlaylist() {
  993. const newName = document.getElementById('playlist_name_input').value.trim();
  994. const currentName = document.getElementById('playlist_name_display').textContent;
  995. if (!newName) {
  996. logMessage("New playlist name cannot be empty.", LOG_TYPE.ERROR);
  997. return;
  998. }
  999. if (newName === currentName) {
  1000. logMessage("New playlist name is the same as the current name. No changes made.", LOG_TYPE.WARNING);
  1001. toggleSecondaryButtons('rename-playlist-container'); // Close the rename container
  1002. return;
  1003. }
  1004. try {
  1005. // Step 1: Create/Modify the playlist with the new name
  1006. const createResponse = await fetch('/modify_playlist', {
  1007. method: 'POST',
  1008. headers: { 'Content-Type': 'application/json' },
  1009. body: JSON.stringify({
  1010. playlist_name: newName,
  1011. files: playlist // Ensure `playlist` contains the current list of files
  1012. })
  1013. });
  1014. const createResult = await createResponse.json();
  1015. if (createResult.success) {
  1016. logMessage(createResult.message, LOG_TYPE.SUCCESS);
  1017. // Step 2: Delete the old playlist
  1018. const deleteResponse = await fetch('/delete_playlist', {
  1019. method: 'DELETE',
  1020. headers: { 'Content-Type': 'application/json' },
  1021. body: JSON.stringify({ playlist_name: currentName })
  1022. });
  1023. const deleteResult = await deleteResponse.json();
  1024. if (deleteResult.success) {
  1025. logMessage(deleteResult.message);
  1026. // Update the UI with the new name
  1027. document.getElementById('playlist_name_display').textContent = newName;
  1028. // Refresh playlists list
  1029. loadAllPlaylists();
  1030. // Close the rename container and restore original action buttons
  1031. toggleSecondaryButtons('rename-playlist-container');
  1032. } else {
  1033. logMessage(`Failed to delete old playlist: ${deleteResult.error}`, LOG_TYPE.ERROR);
  1034. }
  1035. } else {
  1036. logMessage(`Failed to rename playlist: ${createResult.error}`, LOG_TYPE.ERROR);
  1037. }
  1038. } catch (error) {
  1039. logMessage(`Error renaming playlist: ${error.message}`);
  1040. }
  1041. }
  1042. // Delete the currently opened playlist
  1043. async function deleteCurrentPlaylist() {
  1044. const playlistName = document.getElementById('playlist_name_display').textContent;
  1045. if (!confirm(`Are you sure you want to delete the playlist "${playlistName}"? This action cannot be undone.`)) {
  1046. return;
  1047. }
  1048. try {
  1049. const response = await fetch('/delete_playlist', {
  1050. method: 'DELETE',
  1051. headers: { 'Content-Type': 'application/json' },
  1052. body: JSON.stringify({ playlist_name: playlistName })
  1053. });
  1054. const result = await response.json();
  1055. if (result.success) {
  1056. logMessage(`Playlist "${playlistName}" deleted.`, LOG_TYPE.INFO);
  1057. closeStickySection('playlist-editor');
  1058. loadAllPlaylists();
  1059. populatePlaylistDropdown();
  1060. } else {
  1061. logMessage(`Failed to delete playlist: ${result.error}`, LOG_TYPE.ERROR);
  1062. }
  1063. } catch (error) {
  1064. logMessage(`Error deleting playlist: ${error.message}`);
  1065. }
  1066. }
  1067. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1068. // PART D: Local playlist array UI
  1069. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1070. // Refresh the playlist UI and detect changes
  1071. function refreshPlaylistUI() {
  1072. const ul = document.getElementById('playlist_items');
  1073. if (!ul) {
  1074. logMessage('Error: Playlist container not found');
  1075. return;
  1076. }
  1077. ul.innerHTML = ''; // Clear existing items
  1078. if (playlist.length === 0) {
  1079. // Add a placeholder if the playlist is empty
  1080. const emptyLi = document.createElement('li');
  1081. emptyLi.textContent = 'No items in the playlist.';
  1082. emptyLi.classList.add('empty-placeholder'); // Optional: Add a class for styling
  1083. ul.appendChild(emptyLi);
  1084. return;
  1085. }
  1086. playlist.forEach((file, index) => {
  1087. const li = document.createElement('li');
  1088. // Add filename in a span
  1089. const filenameSpan = document.createElement('span');
  1090. filenameSpan.textContent = file;
  1091. filenameSpan.classList.add('filename'); // Add a class for styling
  1092. li.appendChild(filenameSpan);
  1093. // Move Up button
  1094. const moveUpBtn = document.createElement('button');
  1095. moveUpBtn.innerHTML = '<i class="fa-solid fa-turn-up"></i>'; // Up arrow symbol
  1096. moveUpBtn.classList.add('move-button');
  1097. moveUpBtn.onclick = () => {
  1098. if (index > 0) {
  1099. const temp = playlist[index - 1];
  1100. playlist[index - 1] = playlist[index];
  1101. playlist[index] = temp;
  1102. detectPlaylistChanges(); // Check for changes
  1103. refreshPlaylistUI();
  1104. }
  1105. };
  1106. li.appendChild(moveUpBtn);
  1107. // Move Down button
  1108. const moveDownBtn = document.createElement('button');
  1109. moveDownBtn.innerHTML = '<i class="fa-solid fa-turn-down"></i>'; // Down arrow symbol
  1110. moveDownBtn.classList.add('move-button');
  1111. moveDownBtn.onclick = () => {
  1112. if (index < playlist.length - 1) {
  1113. const temp = playlist[index + 1];
  1114. playlist[index + 1] = playlist[index];
  1115. playlist[index] = temp;
  1116. detectPlaylistChanges(); // Check for changes
  1117. refreshPlaylistUI();
  1118. }
  1119. };
  1120. li.appendChild(moveDownBtn);
  1121. // Remove button
  1122. const removeBtn = document.createElement('button');
  1123. removeBtn.innerHTML = '<i class="fa-solid fa-trash"></i>';
  1124. removeBtn.classList.add('remove-button');
  1125. removeBtn.onclick = () => {
  1126. playlist.splice(index, 1);
  1127. detectPlaylistChanges(); // Check for changes
  1128. refreshPlaylistUI();
  1129. };
  1130. li.appendChild(removeBtn);
  1131. ul.appendChild(li);
  1132. });
  1133. }
  1134. // Toggle the visibility of the save and cancel buttons
  1135. function toggleSaveCancelButtons(show) {
  1136. const actionButtons = document.querySelector('#playlist-editor .action-buttons');
  1137. if (actionButtons) {
  1138. // Show/hide all buttons except Save and Cancel
  1139. actionButtons.querySelectorAll('button:not(.save-cancel)').forEach(button => {
  1140. button.style.display = show ? 'none' : 'flex';
  1141. });
  1142. // Show/hide Save and Cancel buttons
  1143. actionButtons.querySelectorAll('.save-cancel').forEach(button => {
  1144. button.style.display = show ? 'flex' : 'none';
  1145. });
  1146. } else {
  1147. logMessage('Error: Action buttons container not found.', LOG_TYPE.ERROR);
  1148. }
  1149. }
  1150. // Detect changes in the playlist
  1151. function detectPlaylistChanges() {
  1152. isPlaylistChanged = JSON.stringify(originalPlaylist) !== JSON.stringify(playlist);
  1153. toggleSaveCancelButtons(isPlaylistChanged);
  1154. }
  1155. // Toggle the "Add to Playlist" section
  1156. function toggleSecondaryButtons(containerId, onShowCallback = null) {
  1157. const container = document.getElementById(containerId);
  1158. if (!container) {
  1159. logMessage(`Error: Element with ID "${containerId}" not found`);
  1160. return;
  1161. }
  1162. // Find the .action-buttons element preceding the container
  1163. const previousActionButtons = container.previousElementSibling?.classList.contains('action-buttons')
  1164. ? container.previousElementSibling
  1165. : null;
  1166. if (container.classList.contains('hidden')) {
  1167. // Show the container
  1168. container.classList.remove('hidden');
  1169. // Hide the previous .action-buttons element
  1170. if (previousActionButtons) {
  1171. previousActionButtons.style.display = 'none';
  1172. }
  1173. // Optional callback for custom logic when showing the container
  1174. if (onShowCallback) {
  1175. onShowCallback();
  1176. }
  1177. } else {
  1178. // Hide the container
  1179. container.classList.add('hidden');
  1180. // Restore the previous .action-buttons element
  1181. if (previousActionButtons) {
  1182. previousActionButtons.style.display = 'flex';
  1183. }
  1184. }
  1185. }
  1186. // Add the selected pattern to the selected playlist
  1187. async function saveToPlaylist() {
  1188. const playlist = document.getElementById('select-playlist').value;
  1189. if (!playlist) {
  1190. logMessage('No playlist selected.', LOG_TYPE.ERROR);
  1191. return;
  1192. }
  1193. if (!selectedFile) {
  1194. logMessage('No pattern selected to add.', LOG_TYPE.ERROR);
  1195. return;
  1196. }
  1197. try {
  1198. logMessage(`Adding pattern "${selectedFile}" to playlist "${playlist}"...`);
  1199. const response = await fetch('/add_to_playlist', {
  1200. method: 'POST',
  1201. headers: { 'Content-Type': 'application/json' },
  1202. body: JSON.stringify({ playlist_name: playlist, pattern: selectedFile })
  1203. });
  1204. const result = await response.json();
  1205. if (result.success) {
  1206. logMessage(`Pattern "${selectedFile}" successfully added to playlist "${playlist}".`, LOG_TYPE.SUCCESS);
  1207. // Reset the UI state via toggleSecondaryButtons
  1208. toggleSecondaryButtons('add-to-playlist-container', () => {
  1209. const selectPlaylist = document.getElementById('select-playlist');
  1210. selectPlaylist.value = ''; // Clear the selection
  1211. });
  1212. } else {
  1213. logMessage(`Failed to add pattern to playlist: ${result.error}`, LOG_TYPE.ERROR);
  1214. }
  1215. } catch (error) {
  1216. logMessage(`Error adding pattern to playlist: ${error.message}`);
  1217. }
  1218. }
  1219. async function changeSpeed() {
  1220. const speedInput = document.getElementById('speed_input');
  1221. const speed = parseFloat(speedInput.value);
  1222. if (isNaN(speed) || speed <= 0) {
  1223. logMessage('Invalid speed. Please enter a positive number.');
  1224. return;
  1225. }
  1226. logMessage(`Setting speed to: ${speed}...`);
  1227. const response = await fetch('/set_speed', {
  1228. method: 'POST',
  1229. headers: { 'Content-Type': 'application/json' },
  1230. body: JSON.stringify({ speed })
  1231. });
  1232. const result = await response.json();
  1233. if (result.success) {
  1234. document.getElementById('speed_status').textContent = `Current Speed: ${speed}`;
  1235. logMessage(`Speed set to: ${speed}`, LOG_TYPE.SUCCESS);
  1236. } else {
  1237. logMessage(`Failed to set speed: ${result.error}`, LOG_TYPE.ERROR);
  1238. }
  1239. }
  1240. // Function to close any sticky section
  1241. function closeStickySection(sectionId) {
  1242. const section = document.getElementById(sectionId);
  1243. if (section) {
  1244. section.classList.remove('visible');
  1245. section.classList.remove('fullscreen');
  1246. section.classList.add('hidden');
  1247. // Reset the fullscreen button text if it exists
  1248. const fullscreenButton = section.querySelector('.fullscreen-button');
  1249. if (fullscreenButton) {
  1250. fullscreenButton.innerHtml = '<i class="fa-solid fa-compress"></i>'; // Reset to enter fullscreen icon/text
  1251. }
  1252. logMessage(`Closed section: ${sectionId}`);
  1253. if(sectionId === 'playlist-editor') {
  1254. document.querySelectorAll('#all_playlists .playlist-item').forEach(item => {
  1255. item.classList.remove('selected');
  1256. });
  1257. }
  1258. if(sectionId === 'pattern-preview-container') {
  1259. document.querySelectorAll('#theta_rho_files .file-item').forEach(item => {
  1260. item.classList.remove('selected');
  1261. });
  1262. }
  1263. } else {
  1264. logMessage(`Error: Section with ID "${sectionId}" not found`);
  1265. }
  1266. }
  1267. // Function to open any sticky section
  1268. function openStickySection(sectionId) {
  1269. const section = document.getElementById(sectionId);
  1270. if (section) {
  1271. // Toggle the 'open' class
  1272. section.classList.toggle('open');
  1273. } else {
  1274. logMessage(`Error: Section with ID "${sectionId}" not found`);
  1275. }
  1276. }
  1277. function attachFullScreenListeners() {
  1278. // Add event listener to all fullscreen buttons
  1279. document.querySelectorAll('.fullscreen-button').forEach(button => {
  1280. button.addEventListener('click', function () {
  1281. const stickySection = this.closest('.sticky'); // Find the closest sticky section
  1282. if (stickySection) {
  1283. // Close all other sections
  1284. document.querySelectorAll('.sticky:not(#currently-playing-container)').forEach(section => {
  1285. if (section !== stickySection) {
  1286. section.classList.remove('fullscreen');
  1287. section.classList.remove('visible');
  1288. section.classList.add('hidden');
  1289. // Reset the fullscreen button text for other sections
  1290. const otherFullscreenButton = section.querySelector('.fullscreen-button');
  1291. if (otherFullscreenButton) {
  1292. otherFullscreenButton.innerHTML = '<i class="fa-solid fa-expand"></i>'; // Enter fullscreen icon/text
  1293. }
  1294. }
  1295. });
  1296. stickySection.classList.toggle('fullscreen'); // Toggle fullscreen class
  1297. // Update button icon or text
  1298. if (stickySection.classList.contains('fullscreen')) {
  1299. this.innerHTML = '<i class="fa-solid fa-compress"></i>'; // Exit fullscreen icon/text
  1300. } else {
  1301. this.innerHTML = '<i class="fa-solid fa-expand"></i>'; // Enter fullscreen icon/text
  1302. }
  1303. } else {
  1304. console.error('Error: Fullscreen button is not inside a sticky section.');
  1305. }
  1306. });
  1307. });
  1308. }
  1309. let lastPreviewedFile = null; // Track the last previewed file
  1310. function formatSecondsToHMS(seconds) {
  1311. const hrs = Math.floor(seconds / 3600);
  1312. const mins = Math.floor((seconds % 3600) / 60);
  1313. const secs = Math.floor(seconds % 60);
  1314. return `${String(hrs).padStart(2, '0')}:${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
  1315. }
  1316. // Function to start or stop updates based on visibility
  1317. function toggleSettings() {
  1318. const settingsContainer = document.getElementById('settings-container');
  1319. if (settingsContainer) {
  1320. settingsContainer.classList.toggle('open');
  1321. }
  1322. }
  1323. // Utility function to manage cookies
  1324. function setCookie(name, value, days) {
  1325. const date = new Date();
  1326. date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  1327. document.cookie = `${name}=${value};expires=${date.toUTCString()};path=/`;
  1328. }
  1329. function getCookie(name) {
  1330. const nameEQ = `${name}=`;
  1331. const cookies = document.cookie.split(';');
  1332. for (let i = 0; i < cookies.length; i++) {
  1333. let cookie = cookies[i].trim();
  1334. if (cookie.startsWith(nameEQ)) {
  1335. return cookie.substring(nameEQ.length);
  1336. }
  1337. }
  1338. return null;
  1339. }
  1340. // Save settings to cookies
  1341. function saveSettingsToCookies() {
  1342. const pauseTime = document.getElementById('pause_time').value;
  1343. const clearPattern = document.getElementById('clear_pattern').value;
  1344. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  1345. const shuffle = document.getElementById('shuffle_playlist').checked;
  1346. setCookie('pause_time', pauseTime, 365);
  1347. setCookie('clear_pattern', clearPattern, 365);
  1348. setCookie('run_mode', runMode, 365);
  1349. setCookie('shuffle', shuffle, 365);
  1350. }
  1351. // Load settings from cookies
  1352. function loadSettingsFromCookies() {
  1353. const pauseTime = getCookie('pause_time');
  1354. if (pauseTime !== '') {
  1355. document.getElementById('pause_time').value = pauseTime;
  1356. }
  1357. const clearPattern = getCookie('clear_pattern');
  1358. if (clearPattern !== '') {
  1359. document.getElementById('clear_pattern').value = clearPattern;
  1360. }
  1361. const runMode = getCookie('run_mode');
  1362. if (runMode !== '') {
  1363. document.querySelector(`input[name="run_mode"][value="${runMode}"]`).checked = true;
  1364. }
  1365. const shuffle = getCookie('shuffle');
  1366. if (shuffle !== '') {
  1367. document.getElementById('shuffle_playlist').checked = shuffle === 'true';
  1368. }
  1369. logMessage('Settings loaded from cookies.');
  1370. }
  1371. // Call this function to save settings when a value is changed
  1372. function attachSettingsSaveListeners() {
  1373. // Add event listeners to inputs
  1374. document.getElementById('pause_time').addEventListener('change', saveSettingsToCookies);
  1375. document.getElementById('clear_pattern').addEventListener('change', saveSettingsToCookies);
  1376. document.querySelectorAll('input[name="run_mode"]').forEach(input => {
  1377. input.addEventListener('change', saveSettingsToCookies);
  1378. });
  1379. document.getElementById('shuffle_playlist').addEventListener('change', saveSettingsToCookies);
  1380. }
  1381. // Tab switching logic with cookie storage
  1382. function switchTab(tabName) {
  1383. // Store the active tab in a cookie
  1384. setCookie('activeTab', tabName, 365); // Store for 7 days
  1385. // Deactivate all tab content
  1386. document.querySelectorAll('.tab-content').forEach(tab => {
  1387. tab.classList.remove('active');
  1388. });
  1389. // Activate the selected tab content
  1390. const activeTab = document.getElementById(`${tabName}-tab`);
  1391. if (activeTab) {
  1392. activeTab.classList.add('active');
  1393. } else {
  1394. console.error(`Error: Tab "${tabName}" not found.`);
  1395. }
  1396. // Deactivate all nav buttons
  1397. document.querySelectorAll('.bottom-nav .tab-button').forEach(button => {
  1398. button.classList.remove('active');
  1399. });
  1400. // Activate the selected nav button
  1401. const activeNavButton = document.getElementById(`nav-${tabName}`);
  1402. if (activeNavButton) {
  1403. activeNavButton.classList.add('active');
  1404. } else {
  1405. console.error(`Error: Nav button for "${tabName}" not found.`);
  1406. }
  1407. }
  1408. // Update the small UI segment to show the IP or hide it if none
  1409. function updateWledUI() {
  1410. const wledIp = localStorage.getItem('wled_ip');
  1411. const wledContainer = document.getElementById('wled-container');
  1412. const wledFrame = document.getElementById('wled-frame');
  1413. const wledStatus = document.getElementById('wled-status');
  1414. if (!wledIp) {
  1415. wledContainer.classList.add('hidden');
  1416. return;
  1417. }
  1418. // Show the container and load WLED UI
  1419. wledContainer.classList.remove('hidden');
  1420. wledFrame.src = `http://${wledIp}`;
  1421. }
  1422. // Save or clear the WLED IP, updating both the browser and backend
  1423. async function saveWledIp() {
  1424. const ipInput = document.getElementById('wled_ip');
  1425. const saveButton = document.querySelector('.wled-settings button.cta');
  1426. const currentIp = localStorage.getItem('wled_ip');
  1427. if (currentIp) {
  1428. // Clear the saved IP if one is already set
  1429. localStorage.removeItem('wled_ip');
  1430. ipInput.disabled = false;
  1431. ipInput.value = '';
  1432. saveButton.innerHTML = '<i class="fa-solid fa-save"></i><span>Save</span>';
  1433. logMessage('WLED IP cleared.', LOG_TYPE.INFO);
  1434. // Also clear the IP on the backend
  1435. try {
  1436. const response = await fetch('/set_wled_ip', {
  1437. method: 'POST',
  1438. headers: { 'Content-Type': 'application/json' },
  1439. body: JSON.stringify({ wled_ip: null })
  1440. });
  1441. const data = await response.json();
  1442. if (data.success) {
  1443. logMessage('Backend IP cleared successfully.', LOG_TYPE.INFO);
  1444. } else {
  1445. logMessage('Failed to clear backend IP.', LOG_TYPE.ERROR);
  1446. }
  1447. } catch (error) {
  1448. logMessage(`Error clearing backend IP: ${error.message}`, LOG_TYPE.ERROR);
  1449. }
  1450. } else {
  1451. // Validate and save the new IP
  1452. const ip = ipInput.value.trim();
  1453. if (!validateIp(ip)) {
  1454. logMessage('Invalid IP address format.', LOG_TYPE.ERROR);
  1455. return;
  1456. }
  1457. localStorage.setItem('wled_ip', ip);
  1458. ipInput.disabled = true;
  1459. saveButton.innerHTML = '<i class="fa-solid fa-xmark"></i><span>Clear</span>';
  1460. logMessage(`WLED IP saved: ${ip}`, LOG_TYPE.SUCCESS);
  1461. // Also save the IP to the backend
  1462. try {
  1463. const response = await fetch('/set_wled_ip', {
  1464. method: 'POST',
  1465. headers: { 'Content-Type': 'application/json' },
  1466. body: JSON.stringify({ wled_ip: ip })
  1467. });
  1468. const data = await response.json();
  1469. if (data.success) {
  1470. logMessage('Backend IP saved successfully.', LOG_TYPE.SUCCESS);
  1471. } else {
  1472. logMessage('Failed to save backend IP.', LOG_TYPE.ERROR);
  1473. }
  1474. } catch (error) {
  1475. logMessage(`Error saving backend IP: ${error.message}`, LOG_TYPE.ERROR);
  1476. }
  1477. }
  1478. updateWledUI(); // Refresh any UI elements that depend on the IP
  1479. }
  1480. // Load the WLED IP from localStorage; if not available, retrieve it from the backend
  1481. async function loadWledIp() {
  1482. const ipInput = document.getElementById('wled_ip');
  1483. const saveButton = document.querySelector('.wled-settings button.cta');
  1484. let savedIp = localStorage.getItem('wled_ip');
  1485. if (!savedIp) {
  1486. // Attempt to load from the backend if not found in localStorage
  1487. try {
  1488. const response = await fetch('/get_wled_ip');
  1489. const data = await response.json();
  1490. if (data.wled_ip) {
  1491. savedIp = data.wled_ip;
  1492. localStorage.setItem('wled_ip', savedIp);
  1493. }
  1494. } catch (error) {
  1495. logMessage(`Error fetching WLED IP from backend: ${error.message}`, LOG_TYPE.ERROR);
  1496. }
  1497. }
  1498. if (savedIp) {
  1499. ipInput.value = savedIp;
  1500. ipInput.disabled = true;
  1501. saveButton.innerHTML = '<i class="fa-solid fa-xmark"></i><span>Clear</span>';
  1502. } else {
  1503. ipInput.disabled = false;
  1504. saveButton.innerHTML = '<i class="fa-solid fa-save"></i><span>Save</span>';
  1505. }
  1506. updateWledUI(); // Update any dependent UI segments
  1507. }
  1508. function validateIp(ip) {
  1509. const ipRegex = /^(25[0-5]|2[0-4]\d|1\d\d|\d?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|\d?\d)){3}$/;
  1510. return ipRegex.test(ip);
  1511. }
  1512. // Theme toggle functionality
  1513. const themeToggle = document.getElementById('theme-toggle');
  1514. const themeIcon = themeToggle.querySelector('i');
  1515. themeToggle.addEventListener('click', () => {
  1516. const root = document.documentElement;
  1517. const currentTheme = root.getAttribute('data-theme');
  1518. const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
  1519. root.setAttribute('data-theme', newTheme);
  1520. localStorage.setItem('theme', newTheme);
  1521. // Toggle the icon
  1522. themeIcon.className = newTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
  1523. });
  1524. // Set initial theme and icon based on saved theme
  1525. const savedTheme = localStorage.getItem('theme') || 'light';
  1526. document.documentElement.setAttribute('data-theme', savedTheme);
  1527. themeIcon.className = savedTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
  1528. // Add WebSocket connection for status updates
  1529. let statusSocket = null;
  1530. let reconnectAttempts = 0;
  1531. const MAX_RECONNECT_ATTEMPTS = 5;
  1532. let statusUpdateInterval = null;
  1533. let wsConnected = false;
  1534. function connectStatusWebSocket() {
  1535. // Don't create a new connection if one already exists
  1536. if (wsConnected) {
  1537. console.log('WebSocket already connected');
  1538. return;
  1539. }
  1540. // Close existing connection and clear interval if any
  1541. if (statusSocket) {
  1542. statusSocket.close();
  1543. }
  1544. if (statusUpdateInterval) {
  1545. clearInterval(statusUpdateInterval);
  1546. }
  1547. // Create WebSocket connection
  1548. const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  1549. statusSocket = new WebSocket(`${protocol}//${window.location.host}/ws/status`);
  1550. statusSocket.onopen = () => {
  1551. console.log('Status WebSocket connected');
  1552. wsConnected = true;
  1553. reconnectAttempts = 0; // Reset reconnect attempts on successful connection
  1554. };
  1555. statusSocket.onmessage = (event) => {
  1556. try {
  1557. const message = JSON.parse(event.data);
  1558. if (message.type === 'status_update' && message.data) {
  1559. updateCurrentlyPlayingUI(message.data);
  1560. // Disconnect WebSocket if no pattern is running
  1561. if (!message.data.is_running) {
  1562. console.log('No pattern running, disconnecting WebSocket');
  1563. disconnectStatusWebSocket();
  1564. }
  1565. }
  1566. } catch (error) {
  1567. console.error('Error processing status update:', error);
  1568. console.error('Raw data that caused error:', event.data);
  1569. }
  1570. };
  1571. statusSocket.onclose = () => {
  1572. console.log('Status WebSocket disconnected');
  1573. wsConnected = false;
  1574. clearInterval(statusUpdateInterval);
  1575. // Only attempt to reconnect if we're supposed to be connected
  1576. if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS && document.body.classList.contains('playing')) {
  1577. reconnectAttempts++;
  1578. const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000);
  1579. console.log(`Reconnecting in ${delay/1000}s (Attempt ${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`);
  1580. setTimeout(connectStatusWebSocket, delay);
  1581. }
  1582. };
  1583. statusSocket.onerror = (error) => {
  1584. console.error('WebSocket error:', error);
  1585. };
  1586. }
  1587. function disconnectStatusWebSocket() {
  1588. if (statusSocket && wsConnected) {
  1589. wsConnected = false;
  1590. statusSocket.close();
  1591. statusSocket = null;
  1592. reconnectAttempts = 0;
  1593. }
  1594. }
  1595. // Replace the polling mechanism with WebSocket
  1596. document.addEventListener('DOMContentLoaded', () => {
  1597. const activeTab = getCookie('activeTab') || 'patterns'; // Default to 'patterns' tab
  1598. switchTab(activeTab); // Load the active tab
  1599. checkSerialStatus(); // Check connection status
  1600. loadThetaRhoFiles(); // Load files on page load
  1601. loadAllPlaylists(); // Load all playlists on page load
  1602. attachSettingsSaveListeners(); // Attach event listeners to save changes
  1603. attachFullScreenListeners();
  1604. loadWledIp();
  1605. updateWledUI();
  1606. // Initialize WebSocket connection for status updates
  1607. connectStatusWebSocket();
  1608. // Handle visibility change
  1609. document.addEventListener('visibilitychange', () => {
  1610. if (document.visibilityState === 'visible' && statusSocket && statusSocket.readyState !== WebSocket.OPEN) {
  1611. connectStatusWebSocket();
  1612. }
  1613. });
  1614. checkForUpdates();
  1615. });
  1616. // Track the last time we had a file playing
  1617. let lastPlayingTime = 0;
  1618. const HIDE_DELAY = 5000; // 1 second delay before hiding
  1619. // Update the updateCurrentlyPlayingUI function to handle WebSocket updates
  1620. // Track the last played file to detect when a new pattern starts
  1621. let lastPlayedFile = null;
  1622. function updateCurrentlyPlayingUI(status) {
  1623. console.log('Updating UI with status:', status);
  1624. // Get all required DOM elements once
  1625. const container = document.getElementById('currently-playing-container');
  1626. const fileNameElement = document.getElementById('currently-playing-file');
  1627. const progressBar = document.getElementById('play_progress');
  1628. const progressText = document.getElementById('play_progress_text');
  1629. const pausePlayButton = document.getElementById('pausePlayCurrent');
  1630. const speedDisplay = document.getElementById('current_speed_display');
  1631. // Check if all required elements exist
  1632. if (!container || !fileNameElement || !progressBar || !progressText) {
  1633. console.log('Required DOM elements not found:', {
  1634. container: !!container,
  1635. fileNameElement: !!fileNameElement,
  1636. progressBar: !!progressBar,
  1637. progressText: !!progressText
  1638. });
  1639. setTimeout(() => updateCurrentlyPlayingUI(status), 100);
  1640. return;
  1641. }
  1642. // Update container visibility based on status
  1643. if (status.current_file && status.is_running) {
  1644. document.body.classList.add('playing');
  1645. container.style.display = 'flex';
  1646. // Hide the preview container when a pattern is playing
  1647. const previewContainer = document.getElementById('pattern-preview-container');
  1648. if (previewContainer) {
  1649. // Clear any selected file highlights
  1650. document.querySelectorAll('#theta_rho_files .file-item').forEach(item => {
  1651. item.classList.remove('selected');
  1652. });
  1653. }
  1654. } else {
  1655. document.body.classList.remove('playing');
  1656. container.style.display = 'none';
  1657. }
  1658. // Update file name display
  1659. if (status.current_file) {
  1660. const fileName = status.current_file.replace('./patterns/', '');
  1661. fileNameElement.textContent = fileName;
  1662. } else {
  1663. fileNameElement.textContent = 'No pattern playing';
  1664. }
  1665. // Update next file display
  1666. const nextFileElement = document.getElementById('next-file');
  1667. if (nextFileElement) {
  1668. if (status.playlist && status.playlist.next_file) {
  1669. const nextFileName = status.playlist.next_file.replace('./patterns/', '');
  1670. nextFileElement.textContent = `(Next: ${nextFileName})`;
  1671. nextFileElement.style.display = 'block';
  1672. } else {
  1673. nextFileElement.style.display = 'none';
  1674. }
  1675. }
  1676. // Update speed display if it exists
  1677. if (speedDisplay && status.speed) {
  1678. speedDisplay.textContent = `Current Speed: ${status.speed}`;
  1679. }
  1680. // Update pattern preview if it's a new pattern
  1681. if (status.current_file && lastPlayedFile !== status.current_file) {
  1682. lastPlayedFile = status.current_file;
  1683. const cleanFileName = status.current_file.replace('./patterns/', '');
  1684. previewPattern(cleanFileName, 'currently-playing-container');
  1685. }
  1686. // Update progress information
  1687. if (status.progress) {
  1688. const { percentage, remaining_time, elapsed_time } = status.progress;
  1689. const formattedPercentage = percentage.toFixed(1);
  1690. const remainingText = remaining_time === null ? 'calculating...' : formatSecondsToHMS(remaining_time);
  1691. const elapsedText = formatSecondsToHMS(elapsed_time);
  1692. progressBar.value = formattedPercentage;
  1693. progressText.textContent = `${formattedPercentage}% (Elapsed: ${elapsedText} | Remaining: ${remainingText})`;
  1694. } else {
  1695. progressBar.value = 0;
  1696. progressText.textContent = '0%';
  1697. }
  1698. // Update pause/play button if it exists
  1699. if (pausePlayButton) {
  1700. pausePlayButton.innerHTML = status.is_paused ?
  1701. '<i class="fa-solid fa-play"></i>' :
  1702. '<i class="fa-solid fa-pause"></i>';
  1703. }
  1704. // Update playlist UI if the function exists
  1705. if (typeof updatePlaylistUI === 'function') {
  1706. updatePlaylistUI(status);
  1707. }
  1708. // Update skip button visibility based on playlist status
  1709. updateSkipButtonVisibility(status);
  1710. }
  1711. // Add these functions to handle the skip button
  1712. function updateSkipButtonVisibility(status) {
  1713. const skipButton = document.getElementById('skipCurrent');
  1714. if (skipButton) {
  1715. // Check if a playlist is playing using the correct status properties
  1716. console.log('status', status);
  1717. const isPlaylistPlaying = status && status.playlist && status.playlist.next_file;
  1718. if (isPlaylistPlaying) {
  1719. skipButton.classList.remove('hidden');
  1720. } else {
  1721. skipButton.classList.add('hidden');
  1722. }
  1723. }
  1724. }
  1725. async function skipPattern() {
  1726. try {
  1727. const response = await fetch('/skip_pattern', {
  1728. method: 'POST',
  1729. });
  1730. const data = await response.json();
  1731. if (data.success) {
  1732. logMessage('Skipping to next pattern', LOG_TYPE.INFO);
  1733. } else {
  1734. logMessage(data.message, LOG_TYPE.ERROR);
  1735. }
  1736. } catch (error) {
  1737. logMessage('Error skipping pattern', 'error');
  1738. }
  1739. }