main.js 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037
  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. connectStatusWebSocket();
  485. document.body.classList.add('playing');
  486. logMessage('Clear from center pattern started', LOG_TYPE.SUCCESS);
  487. } else {
  488. logMessage('Failed to run clear pattern', LOG_TYPE.ERROR);
  489. }
  490. } catch (error) {
  491. logMessage(`Error running clear pattern: ${error}`, LOG_TYPE.ERROR);
  492. }
  493. }
  494. async function runClearOut() {
  495. logMessage('Running clear from perimeter pattern...', LOG_TYPE.INFO);
  496. try {
  497. const response = await fetch('/run_theta_rho', {
  498. method: 'POST',
  499. headers: { 'Content-Type': 'application/json' },
  500. body: JSON.stringify({
  501. file_name: 'clear_from_out.thr',
  502. pre_execution: 'none'
  503. })
  504. });
  505. if (!response.ok) {
  506. if (response.status === 409) {
  507. logMessage('Cannot start pattern: Another pattern is already running', LOG_TYPE.WARNING);
  508. return;
  509. }
  510. throw new Error(`HTTP error! status: ${response.status}`);
  511. }
  512. const result = await response.json();
  513. if (result.success) {
  514. connectStatusWebSocket();
  515. document.body.classList.add('playing');
  516. logMessage('Clear from perimeter pattern started', LOG_TYPE.SUCCESS);
  517. } else {
  518. logMessage('Failed to run clear pattern', LOG_TYPE.ERROR);
  519. }
  520. } catch (error) {
  521. logMessage(`Error running clear pattern: ${error}`, LOG_TYPE.ERROR);
  522. }
  523. }
  524. async function runClearSide() {
  525. logMessage('Running clear sideways pattern...', LOG_TYPE.INFO);
  526. try {
  527. const response = await fetch('/run_theta_rho', {
  528. method: 'POST',
  529. headers: { 'Content-Type': 'application/json' },
  530. body: JSON.stringify({
  531. file_name: 'clear_sideway.thr',
  532. pre_execution: 'none'
  533. })
  534. });
  535. if (!response.ok) {
  536. if (response.status === 409) {
  537. logMessage('Cannot start pattern: Another pattern is already running', LOG_TYPE.WARNING);
  538. return;
  539. }
  540. throw new Error(`HTTP error! status: ${response.status}`);
  541. }
  542. const result = await response.json();
  543. if (result.success) {
  544. connectStatusWebSocket();
  545. document.body.classList.add('playing');
  546. logMessage('Clear sideways pattern started', LOG_TYPE.SUCCESS);
  547. } else {
  548. logMessage('Failed to run clear pattern', LOG_TYPE.ERROR);
  549. }
  550. } catch (error) {
  551. logMessage(`Error running clear pattern: ${error}`, LOG_TYPE.ERROR);
  552. }
  553. }
  554. let scrollPosition = 0;
  555. function scrollSelection(direction) {
  556. const container = document.getElementById('clear_selection');
  557. const itemHeight = 50; // Adjust based on CSS height
  558. const maxScroll = container.children.length - 1;
  559. // Update scroll position
  560. scrollPosition += direction;
  561. scrollPosition = Math.max(0, Math.min(scrollPosition, maxScroll));
  562. // Update the transform to scroll items
  563. container.style.transform = `translateY(-${scrollPosition * itemHeight}px)`;
  564. setCookie('clear_action_index', scrollPosition, 365);
  565. }
  566. function executeClearAction(actionFunction) {
  567. // Save the new action to a cookie (optional)
  568. setCookie('clear_action', actionFunction, 365);
  569. if (actionFunction && typeof window[actionFunction] === 'function') {
  570. window[actionFunction](); // Execute the selected clear action
  571. } else {
  572. logMessage('No clear action selected or function not found.', LOG_TYPE.ERROR);
  573. }
  574. }
  575. async function runFile(fileName) {
  576. const response = await fetch(`/run_theta_rho_file/${fileName}`, { method: 'POST' });
  577. const result = await response.json();
  578. if (result.success) {
  579. logMessage(`Running file: ${fileName}`, LOG_TYPE.SUCCESS);
  580. } else {
  581. logMessage(`Failed to run file: ${fileName}`, LOG_TYPE.ERROR);
  582. }
  583. }
  584. // Connection Status
  585. async function checkSerialStatus() {
  586. const response = await fetch('/serial_status');
  587. const status = await response.json();
  588. const statusElement = document.getElementById('serial_status');
  589. const statusHeaderElement = document.getElementById('connection_status_header');
  590. const serialPortsContainer = document.getElementById('serial_ports_container');
  591. const selectElement = document.getElementById('serial_ports');
  592. const connectButton = document.querySelector('button[onclick="connectSerial()"]');
  593. const disconnectButton = document.querySelector('button[onclick="disconnectSerial()"]');
  594. const restartButton = document.querySelector('button[onclick="restartSerial()"]');
  595. if (status.connected) {
  596. const port = status.port || 'Unknown'; // Fallback if port is undefined
  597. statusElement.textContent = `Connected to ${port}`;
  598. statusElement.classList.add('connected');
  599. statusElement.classList.remove('not-connected');
  600. logMessage(`Connected to serial port: ${port}`);
  601. // Update header status
  602. statusHeaderElement.classList.add('connected');
  603. statusHeaderElement.classList.remove('not-connected');
  604. // Hide Available Ports and show disconnect/restart buttons
  605. serialPortsContainer.style.display = 'none';
  606. connectButton.style.display = 'none';
  607. disconnectButton.style.display = 'flex';
  608. restartButton.style.display = 'flex';
  609. // Preselect the connected port in the dropdown
  610. const newOption = document.createElement('option');
  611. newOption.value = port;
  612. newOption.textContent = port;
  613. selectElement.appendChild(newOption);
  614. selectElement.value = port;
  615. } else {
  616. statusElement.textContent = 'Not connected';
  617. statusElement.classList.add('not-connected');
  618. statusElement.classList.remove('connected');
  619. logMessage('No active connection.');
  620. // Update header status
  621. statusHeaderElement.classList.add('not-connected');
  622. statusHeaderElement.classList.remove('connected');
  623. // Show Available Ports and the connect button
  624. serialPortsContainer.style.display = 'block';
  625. connectButton.style.display = 'flex';
  626. disconnectButton.style.display = 'none';
  627. restartButton.style.display = 'none';
  628. // Attempt to auto-load available ports
  629. await loadSerialPorts();
  630. }
  631. }
  632. async function loadSerialPorts() {
  633. const response = await fetch('/list_serial_ports');
  634. const ports = await response.json();
  635. const select = document.getElementById('serial_ports');
  636. select.innerHTML = '';
  637. ports.forEach(port => {
  638. const option = document.createElement('option');
  639. option.value = port;
  640. option.textContent = port;
  641. select.appendChild(option);
  642. });
  643. logMessage('Serial ports loaded.');
  644. }
  645. async function connectSerial() {
  646. const port = document.getElementById('serial_ports').value;
  647. const response = await fetch('/connect', {
  648. method: 'POST',
  649. headers: { 'Content-Type': 'application/json' },
  650. body: JSON.stringify({ port })
  651. });
  652. const result = await response.json();
  653. if (result.success) {
  654. logMessage(`Connected to serial port: ${port}`, LOG_TYPE.SUCCESS);
  655. // Refresh the status
  656. await checkSerialStatus();
  657. } else {
  658. logMessage(`Error connecting to serial port: ${result.error}`, LOG_TYPE.ERROR);
  659. }
  660. }
  661. async function disconnectSerial() {
  662. const response = await fetch('/disconnect', { method: 'POST' });
  663. const result = await response.json();
  664. if (result.success) {
  665. logMessage('Serial port disconnected.', LOG_TYPE.SUCCESS);
  666. // Refresh the status
  667. await checkSerialStatus();
  668. } else {
  669. logMessage(`Error disconnecting: ${result.error}`, LOG_TYPE.ERROR);
  670. }
  671. }
  672. async function restartSerial() {
  673. const port = document.getElementById('serial_ports').value;
  674. const response = await fetch('/restart_connection', {
  675. method: 'POST',
  676. headers: { 'Content-Type': 'application/json' },
  677. body: JSON.stringify({ port })
  678. });
  679. const result = await response.json();
  680. if (result.success) {
  681. document.getElementById('serial_status').textContent = `Restarted connection to ${port}`;
  682. logMessage('Connection restarted.', LOG_TYPE.SUCCESS);
  683. // No need to change visibility for restart
  684. } else {
  685. logMessage(`Error restarting Connection: ${result.error}`, LOG_TYPE.ERROR);
  686. }
  687. }
  688. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  689. // Firmware / Software Updater
  690. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  691. async function checkForUpdates() {
  692. try {
  693. const response = await fetch('/check_software_update');
  694. const data = await response.json();
  695. // Handle updates available logic
  696. if (data.updates_available) {
  697. const updateButton = document.getElementById('update-software-btn');
  698. const updateLinkElement = document.getElementById('update_link');
  699. const tagLink = `https://github.com/tuanchris/dune-weaver/releases/tag/${data.latest_remote_tag}`;
  700. updateButton.classList.remove('hidden'); // Show the button
  701. logMessage("Software Update Available", LOG_TYPE.INFO, 'open-settings-button')
  702. updateLinkElement.innerHTML = `<a href="${tagLink}" target="_blank">View Release Notes </a>`;
  703. updateLinkElement.classList.remove('hidden'); // Show the link
  704. }
  705. // Update current and latest version in the UI
  706. const currentVersionElem = document.getElementById('current_git_version');
  707. const latestVersionElem = document.getElementById('latest_git_version');
  708. currentVersionElem.textContent = `Current Version: ${data.latest_local_tag || 'Unknown'}`;
  709. latestVersionElem.textContent = data.updates_available
  710. ? `Latest Version: ${data.latest_remote_tag}`
  711. : 'You are up to date!';
  712. } catch (error) {
  713. console.error('Error checking for updates:', error);
  714. }
  715. }
  716. async function updateSoftware() {
  717. const updateButton = document.getElementById('update-software-btn');
  718. try {
  719. // Disable the button and update the text
  720. updateButton.disabled = true;
  721. updateButton.querySelector('span').textContent = 'Updating...';
  722. const response = await fetch('/update_software', { method: 'POST' });
  723. const data = await response.json();
  724. if (data.success) {
  725. logMessage('Software updated successfully!', LOG_TYPE.SUCCESS);
  726. window.location.reload(); // Reload the page after update
  727. } else {
  728. logMessage('Failed to update software: ' + data.error, LOG_TYPE.ERROR);
  729. }
  730. } catch (error) {
  731. console.error('Error updating software:', error);
  732. logMessage('Failed to update software', LOG_TYPE.ERROR);
  733. } finally {
  734. // Re-enable the button and reset the text
  735. updateButton.disabled = false;
  736. updateButton.textContent = 'Update Software'; // Adjust to the original text
  737. }
  738. }
  739. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  740. // PART A: Loading / listing playlists from the server
  741. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  742. async function loadAllPlaylists() {
  743. try {
  744. const response = await fetch('/list_all_playlists'); // GET
  745. const allPlaylists = await response.json(); // e.g. ["My Playlist", "Summer", ...]
  746. displayAllPlaylists(allPlaylists);
  747. } catch (err) {
  748. logMessage(`Error loading playlists: ${err}`, LOG_TYPE.ERROR);
  749. }
  750. }
  751. // Function to display all playlists with Load, Run, and Delete buttons
  752. function displayAllPlaylists(playlists) {
  753. const ul = document.getElementById('all_playlists');
  754. ul.innerHTML = ''; // Clear current list
  755. if (playlists.length === 0) {
  756. // Add a placeholder if the list is empty
  757. const emptyLi = document.createElement('li');
  758. emptyLi.textContent = "You don't have any playlists yet.";
  759. emptyLi.classList.add('empty-placeholder'); // Optional: Add a class for styling
  760. ul.appendChild(emptyLi);
  761. return;
  762. }
  763. playlists.forEach(playlistName => {
  764. const li = document.createElement('li');
  765. li.textContent = playlistName;
  766. li.classList.add('playlist-item'); // Add a class for styling
  767. // Attach click event to handle selection
  768. li.onclick = () => {
  769. // Remove 'selected' class from all items
  770. document.querySelectorAll('#all_playlists li').forEach(item => {
  771. item.classList.remove('selected');
  772. });
  773. // Add 'selected' class to the clicked item
  774. li.classList.add('selected');
  775. // Open the playlist editor for the selected playlist
  776. openPlaylistEditor(playlistName);
  777. };
  778. ul.appendChild(li);
  779. });
  780. }
  781. // Cancel changes and close the editor
  782. function cancelPlaylistChanges() {
  783. playlist = [...originalPlaylist]; // Revert to the original playlist
  784. isPlaylistChanged = false;
  785. toggleSaveCancelButtons(false); // Hide the save and cancel buttons
  786. refreshPlaylistUI(); // Refresh the UI with the original state
  787. closeStickySection('playlist-editor'); // Close the editor
  788. }
  789. // Open the playlist editor
  790. function openPlaylistEditor(playlistName) {
  791. logMessage(`Opening editor for playlist: ${playlistName}`);
  792. const editorSection = document.getElementById('playlist-editor');
  793. // Update the displayed playlist name
  794. document.getElementById('playlist_name_display').textContent = playlistName;
  795. // Store the current playlist name for renaming
  796. document.getElementById('playlist_name_input').value = playlistName;
  797. editorSection.classList.remove('hidden');
  798. editorSection.classList.add('visible');
  799. loadPlaylist(playlistName);
  800. }
  801. function clearSchedule() {
  802. document.getElementById("start_time").value = "";
  803. document.getElementById("end_time").value = "";
  804. document.getElementById('clear_time').style.display = 'none';
  805. setCookie('start_time', '', 365);
  806. setCookie('end_time', '', 365);
  807. }
  808. // Function to run the selected playlist with specified parameters
  809. async function runPlaylist() {
  810. const playlistName = document.getElementById('playlist_name_display').textContent;
  811. if (!playlistName) {
  812. logMessage('No playlist selected', 'error');
  813. return;
  814. }
  815. const pauseTime = parseFloat(document.getElementById('pause_time').value) || 0;
  816. const clearPattern = document.getElementById('clear_pattern').value;
  817. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  818. const shuffle = document.getElementById('shuffle_playlist').checked;
  819. try {
  820. const response = await fetch('/run_playlist', {
  821. method: 'POST',
  822. headers: {
  823. 'Content-Type': 'application/json',
  824. },
  825. body: JSON.stringify({
  826. playlist_name: playlistName,
  827. pause_time: pauseTime,
  828. clear_pattern: clearPattern,
  829. run_mode: runMode,
  830. shuffle: shuffle
  831. })
  832. });
  833. if (!response.ok) {
  834. if (response.status === 409) {
  835. logMessage('Another pattern is already running', 'warning');
  836. } else {
  837. const errorData = await response.json();
  838. logMessage(errorData.detail || 'Failed to run playlist', 'error');
  839. }
  840. return;
  841. }
  842. // Connect WebSocket when starting a playlist
  843. connectStatusWebSocket();
  844. logMessage(`Started playlist: ${playlistName}`, 'success');
  845. // Close the playlist editor container after successfully starting the playlist
  846. closeStickySection('playlist-editor');
  847. } catch (error) {
  848. logMessage('Error running playlist: ' + error, 'error');
  849. }
  850. }
  851. // Track changes in the playlist
  852. let originalPlaylist = [];
  853. let isPlaylistChanged = false;
  854. // Load playlist and set the original state
  855. async function loadPlaylist(playlistName) {
  856. try {
  857. logMessage(`Loading playlist: ${playlistName}`);
  858. const response = await fetch(`/get_playlist?name=${encodeURIComponent(playlistName)}`);
  859. const data = await response.json();
  860. if (!data.name) {
  861. throw new Error('Playlist name is missing in the response.');
  862. }
  863. // Populate playlist items and set original state
  864. playlist = data.files || [];
  865. originalPlaylist = [...playlist]; // Clone the playlist as the original
  866. isPlaylistChanged = false; // Reset change tracking
  867. toggleSaveCancelButtons(false); // Hide the save and cancel buttons initially
  868. refreshPlaylistUI();
  869. logMessage(`Loaded playlist: "${playlistName}" with ${playlist.length} file(s).`);
  870. } catch (err) {
  871. logMessage(`Error loading playlist: ${err.message}`, LOG_TYPE.ERROR);
  872. console.error('Error details:', err);
  873. }
  874. }
  875. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  876. // PART B: Creating or Saving (Overwriting) a Playlist
  877. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  878. // Instead of separate create/modify functions, we'll unify them:
  879. async function savePlaylist() {
  880. const name = document.getElementById('playlist_name_display').textContent
  881. if (!name) {
  882. logMessage("Please enter a playlist name.");
  883. return;
  884. }
  885. if (playlist.length === 0) {
  886. logMessage("No files in this playlist. Add files first.");
  887. return;
  888. }
  889. logMessage(`Saving playlist "${name}" with ${playlist.length} file(s)...`);
  890. try {
  891. // We can use /create_playlist or /modify_playlist. They do roughly the same in our single-file approach.
  892. // Let's use /create_playlist to always overwrite or create anew.
  893. const response = await fetch('/create_playlist', {
  894. method: 'POST',
  895. headers: { 'Content-Type': 'application/json' },
  896. body: JSON.stringify({
  897. playlist_name: name,
  898. files: playlist
  899. })
  900. });
  901. const result = await response.json();
  902. if (result.success) {
  903. logMessage(`Playlist "${name}" with ${playlist.length} patterns saved`, LOG_TYPE.SUCCESS);
  904. // Reload the entire list of playlists to reflect changes
  905. // Check for changes and refresh the UI
  906. detectPlaylistChanges();
  907. refreshPlaylistUI();
  908. // Restore default action buttons
  909. toggleSaveCancelButtons(false);
  910. } else {
  911. logMessage(`Failed to save playlist: ${result.error}`, LOG_TYPE.ERROR);
  912. }
  913. } catch (err) {
  914. logMessage(`Error saving playlist: ${err}`);
  915. }
  916. }
  917. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  918. // PART C: Renaming and Deleting a playlist
  919. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  920. // Toggle the rename playlist input
  921. function populatePlaylistDropdown() {
  922. return fetch('/list_all_playlists')
  923. .then(response => response.json())
  924. .then(playlists => {
  925. const select = document.getElementById('select-playlist');
  926. select.innerHTML = ''; // Clear existing options
  927. // Retrieve the saved playlist from the cookie
  928. const savedPlaylist = getCookie('selected_playlist');
  929. // Check if there are playlists available
  930. if (playlists.length === 0) {
  931. // Add a placeholder option if no playlists are available
  932. const placeholderOption = document.createElement('option');
  933. placeholderOption.value = '';
  934. placeholderOption.textContent = 'No playlists available';
  935. placeholderOption.disabled = true; // Prevent selection
  936. placeholderOption.selected = true; // Set as default
  937. select.appendChild(placeholderOption);
  938. return;
  939. }
  940. playlists.forEach(playlist => {
  941. const option = document.createElement('option');
  942. option.value = playlist;
  943. option.textContent = playlist;
  944. // Mark the saved playlist as selected
  945. if (playlist === savedPlaylist) {
  946. option.selected = true;
  947. }
  948. select.appendChild(option);
  949. });
  950. // Attach the onchange event listener after populating the dropdown
  951. select.addEventListener('change', function () {
  952. const selectedPlaylist = this.value;
  953. setCookie('selected_playlist', selectedPlaylist, 365); // Save to cookie
  954. logMessage(`Selected playlist saved: ${selectedPlaylist}`);
  955. });
  956. logMessage('Playlist dropdown populated, event listener attached, and saved playlist restored.');
  957. })
  958. .catch(error => logMessage(`Error fetching playlists: ${error.message}`));
  959. }
  960. populatePlaylistDropdown().then(() => {
  961. loadSettingsFromCookies(); // Restore selected playlist after populating the dropdown
  962. });
  963. // Confirm and save the renamed playlist
  964. async function confirmAddPlaylist() {
  965. const playlistNameInput = document.getElementById('new_playlist_name');
  966. const playlistName = playlistNameInput.value.trim();
  967. if (!playlistName) {
  968. logMessage('Playlist name cannot be empty.', LOG_TYPE.ERROR);
  969. return;
  970. }
  971. try {
  972. logMessage(`Adding new playlist: "${playlistName}"...`);
  973. const response = await fetch('/create_playlist', {
  974. method: 'POST',
  975. headers: { 'Content-Type': 'application/json' },
  976. body: JSON.stringify({
  977. playlist_name: playlistName,
  978. files: [] // New playlist starts empty
  979. })
  980. });
  981. const result = await response.json();
  982. if (result.success) {
  983. logMessage(`Playlist "${playlistName}" created successfully.`, LOG_TYPE.SUCCESS);
  984. // Clear the input field
  985. playlistNameInput.value = '';
  986. // Refresh the playlist list
  987. loadAllPlaylists();
  988. populatePlaylistDropdown();
  989. // Hide the add playlist container
  990. toggleSecondaryButtons('add-playlist-container');
  991. } else {
  992. logMessage(`Failed to create playlist: ${result.error}`, LOG_TYPE.ERROR);
  993. }
  994. } catch (error) {
  995. logMessage(`Error creating playlist: ${error.message}`);
  996. }
  997. }
  998. async function confirmRenamePlaylist() {
  999. const newName = document.getElementById('playlist_name_input').value.trim();
  1000. const currentName = document.getElementById('playlist_name_display').textContent;
  1001. if (!newName) {
  1002. logMessage("New playlist name cannot be empty.", LOG_TYPE.ERROR);
  1003. return;
  1004. }
  1005. if (newName === currentName) {
  1006. logMessage("New playlist name is the same as the current name. No changes made.", LOG_TYPE.WARNING);
  1007. toggleSecondaryButtons('rename-playlist-container'); // Close the rename container
  1008. return;
  1009. }
  1010. try {
  1011. // Step 1: Create/Modify the playlist with the new name
  1012. const createResponse = await fetch('/modify_playlist', {
  1013. method: 'POST',
  1014. headers: { 'Content-Type': 'application/json' },
  1015. body: JSON.stringify({
  1016. playlist_name: newName,
  1017. files: playlist // Ensure `playlist` contains the current list of files
  1018. })
  1019. });
  1020. const createResult = await createResponse.json();
  1021. if (createResult.success) {
  1022. logMessage(createResult.message, LOG_TYPE.SUCCESS);
  1023. // Step 2: Delete the old playlist
  1024. const deleteResponse = await fetch('/delete_playlist', {
  1025. method: 'DELETE',
  1026. headers: { 'Content-Type': 'application/json' },
  1027. body: JSON.stringify({ playlist_name: currentName })
  1028. });
  1029. const deleteResult = await deleteResponse.json();
  1030. if (deleteResult.success) {
  1031. logMessage(deleteResult.message);
  1032. // Update the UI with the new name
  1033. document.getElementById('playlist_name_display').textContent = newName;
  1034. // Refresh playlists list
  1035. loadAllPlaylists();
  1036. // Close the rename container and restore original action buttons
  1037. toggleSecondaryButtons('rename-playlist-container');
  1038. } else {
  1039. logMessage(`Failed to delete old playlist: ${deleteResult.error}`, LOG_TYPE.ERROR);
  1040. }
  1041. } else {
  1042. logMessage(`Failed to rename playlist: ${createResult.error}`, LOG_TYPE.ERROR);
  1043. }
  1044. } catch (error) {
  1045. logMessage(`Error renaming playlist: ${error.message}`);
  1046. }
  1047. }
  1048. // Delete the currently opened playlist
  1049. async function deleteCurrentPlaylist() {
  1050. const playlistName = document.getElementById('playlist_name_display').textContent;
  1051. if (!confirm(`Are you sure you want to delete the playlist "${playlistName}"? This action cannot be undone.`)) {
  1052. return;
  1053. }
  1054. try {
  1055. const response = await fetch('/delete_playlist', {
  1056. method: 'DELETE',
  1057. headers: { 'Content-Type': 'application/json' },
  1058. body: JSON.stringify({ playlist_name: playlistName })
  1059. });
  1060. const result = await response.json();
  1061. if (result.success) {
  1062. logMessage(`Playlist "${playlistName}" deleted.`, LOG_TYPE.INFO);
  1063. closeStickySection('playlist-editor');
  1064. loadAllPlaylists();
  1065. populatePlaylistDropdown();
  1066. } else {
  1067. logMessage(`Failed to delete playlist: ${result.error}`, LOG_TYPE.ERROR);
  1068. }
  1069. } catch (error) {
  1070. logMessage(`Error deleting playlist: ${error.message}`);
  1071. }
  1072. }
  1073. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1074. // PART D: Local playlist array UI
  1075. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1076. // Refresh the playlist UI and detect changes
  1077. function refreshPlaylistUI() {
  1078. const ul = document.getElementById('playlist_items');
  1079. if (!ul) {
  1080. logMessage('Error: Playlist container not found');
  1081. return;
  1082. }
  1083. ul.innerHTML = ''; // Clear existing items
  1084. if (playlist.length === 0) {
  1085. // Add a placeholder if the playlist is empty
  1086. const emptyLi = document.createElement('li');
  1087. emptyLi.textContent = 'No items in the playlist.';
  1088. emptyLi.classList.add('empty-placeholder'); // Optional: Add a class for styling
  1089. ul.appendChild(emptyLi);
  1090. return;
  1091. }
  1092. playlist.forEach((file, index) => {
  1093. const li = document.createElement('li');
  1094. // Add filename in a span
  1095. const filenameSpan = document.createElement('span');
  1096. filenameSpan.textContent = file;
  1097. filenameSpan.classList.add('filename'); // Add a class for styling
  1098. li.appendChild(filenameSpan);
  1099. // Move Up button
  1100. const moveUpBtn = document.createElement('button');
  1101. moveUpBtn.innerHTML = '<i class="fa-solid fa-turn-up"></i>'; // Up arrow symbol
  1102. moveUpBtn.classList.add('move-button');
  1103. moveUpBtn.onclick = () => {
  1104. if (index > 0) {
  1105. const temp = playlist[index - 1];
  1106. playlist[index - 1] = playlist[index];
  1107. playlist[index] = temp;
  1108. detectPlaylistChanges(); // Check for changes
  1109. refreshPlaylistUI();
  1110. }
  1111. };
  1112. li.appendChild(moveUpBtn);
  1113. // Move Down button
  1114. const moveDownBtn = document.createElement('button');
  1115. moveDownBtn.innerHTML = '<i class="fa-solid fa-turn-down"></i>'; // Down arrow symbol
  1116. moveDownBtn.classList.add('move-button');
  1117. moveDownBtn.onclick = () => {
  1118. if (index < playlist.length - 1) {
  1119. const temp = playlist[index + 1];
  1120. playlist[index + 1] = playlist[index];
  1121. playlist[index] = temp;
  1122. detectPlaylistChanges(); // Check for changes
  1123. refreshPlaylistUI();
  1124. }
  1125. };
  1126. li.appendChild(moveDownBtn);
  1127. // Remove button
  1128. const removeBtn = document.createElement('button');
  1129. removeBtn.innerHTML = '<i class="fa-solid fa-trash"></i>';
  1130. removeBtn.classList.add('remove-button');
  1131. removeBtn.onclick = () => {
  1132. playlist.splice(index, 1);
  1133. detectPlaylistChanges(); // Check for changes
  1134. refreshPlaylistUI();
  1135. };
  1136. li.appendChild(removeBtn);
  1137. ul.appendChild(li);
  1138. });
  1139. }
  1140. // Toggle the visibility of the save and cancel buttons
  1141. function toggleSaveCancelButtons(show) {
  1142. const actionButtons = document.querySelector('#playlist-editor .action-buttons');
  1143. if (actionButtons) {
  1144. // Show/hide all buttons except Save and Cancel
  1145. actionButtons.querySelectorAll('button:not(.save-cancel)').forEach(button => {
  1146. button.style.display = show ? 'none' : 'flex';
  1147. });
  1148. // Show/hide Save and Cancel buttons
  1149. actionButtons.querySelectorAll('.save-cancel').forEach(button => {
  1150. button.style.display = show ? 'flex' : 'none';
  1151. });
  1152. } else {
  1153. logMessage('Error: Action buttons container not found.', LOG_TYPE.ERROR);
  1154. }
  1155. }
  1156. // Detect changes in the playlist
  1157. function detectPlaylistChanges() {
  1158. isPlaylistChanged = JSON.stringify(originalPlaylist) !== JSON.stringify(playlist);
  1159. toggleSaveCancelButtons(isPlaylistChanged);
  1160. }
  1161. // Toggle the "Add to Playlist" section
  1162. function toggleSecondaryButtons(containerId, onShowCallback = null) {
  1163. const container = document.getElementById(containerId);
  1164. if (!container) {
  1165. logMessage(`Error: Element with ID "${containerId}" not found`);
  1166. return;
  1167. }
  1168. // Find the .action-buttons element preceding the container
  1169. const previousActionButtons = container.previousElementSibling?.classList.contains('action-buttons')
  1170. ? container.previousElementSibling
  1171. : null;
  1172. if (container.classList.contains('hidden')) {
  1173. // Show the container
  1174. container.classList.remove('hidden');
  1175. // Hide the previous .action-buttons element
  1176. if (previousActionButtons) {
  1177. previousActionButtons.style.display = 'none';
  1178. }
  1179. // Optional callback for custom logic when showing the container
  1180. if (onShowCallback) {
  1181. onShowCallback();
  1182. }
  1183. } else {
  1184. // Hide the container
  1185. container.classList.add('hidden');
  1186. // Restore the previous .action-buttons element
  1187. if (previousActionButtons) {
  1188. previousActionButtons.style.display = 'flex';
  1189. }
  1190. }
  1191. }
  1192. // Add the selected pattern to the selected playlist
  1193. async function saveToPlaylist() {
  1194. const playlist = document.getElementById('select-playlist').value;
  1195. if (!playlist) {
  1196. logMessage('No playlist selected.', LOG_TYPE.ERROR);
  1197. return;
  1198. }
  1199. if (!selectedFile) {
  1200. logMessage('No pattern selected to add.', LOG_TYPE.ERROR);
  1201. return;
  1202. }
  1203. try {
  1204. logMessage(`Adding pattern "${selectedFile}" to playlist "${playlist}"...`);
  1205. const response = await fetch('/add_to_playlist', {
  1206. method: 'POST',
  1207. headers: { 'Content-Type': 'application/json' },
  1208. body: JSON.stringify({ playlist_name: playlist, pattern: selectedFile })
  1209. });
  1210. const result = await response.json();
  1211. if (result.success) {
  1212. logMessage(`Pattern "${selectedFile}" successfully added to playlist "${playlist}".`, LOG_TYPE.SUCCESS);
  1213. // Reset the UI state via toggleSecondaryButtons
  1214. toggleSecondaryButtons('add-to-playlist-container', () => {
  1215. const selectPlaylist = document.getElementById('select-playlist');
  1216. selectPlaylist.value = ''; // Clear the selection
  1217. });
  1218. } else {
  1219. logMessage(`Failed to add pattern to playlist: ${result.error}`, LOG_TYPE.ERROR);
  1220. }
  1221. } catch (error) {
  1222. logMessage(`Error adding pattern to playlist: ${error.message}`);
  1223. }
  1224. }
  1225. async function changeSpeed() {
  1226. const speedInput = document.getElementById('speed_input');
  1227. const speed = parseFloat(speedInput.value);
  1228. if (isNaN(speed) || speed <= 0) {
  1229. logMessage('Invalid speed. Please enter a positive number.');
  1230. return;
  1231. }
  1232. logMessage(`Setting speed to: ${speed}...`);
  1233. const response = await fetch('/set_speed', {
  1234. method: 'POST',
  1235. headers: { 'Content-Type': 'application/json' },
  1236. body: JSON.stringify({ speed })
  1237. });
  1238. const result = await response.json();
  1239. if (result.success) {
  1240. document.getElementById('current_speed_display').textContent = `Current Speed: ${speed}`;
  1241. logMessage(`Speed set to: ${speed}`, LOG_TYPE.SUCCESS);
  1242. } else {
  1243. logMessage(`Failed to set speed: ${result.error}`, LOG_TYPE.ERROR);
  1244. }
  1245. }
  1246. // Function to close any sticky section
  1247. function closeStickySection(sectionId) {
  1248. const section = document.getElementById(sectionId);
  1249. if (section) {
  1250. section.classList.remove('visible');
  1251. section.classList.remove('fullscreen');
  1252. section.classList.add('hidden');
  1253. // Reset the fullscreen button text if it exists
  1254. const fullscreenButton = section.querySelector('.fullscreen-button');
  1255. if (fullscreenButton) {
  1256. fullscreenButton.innerHtml = '<i class="fa-solid fa-compress"></i>'; // Reset to enter fullscreen icon/text
  1257. }
  1258. logMessage(`Closed section: ${sectionId}`);
  1259. if(sectionId === 'playlist-editor') {
  1260. document.querySelectorAll('#all_playlists .playlist-item').forEach(item => {
  1261. item.classList.remove('selected');
  1262. });
  1263. }
  1264. if(sectionId === 'pattern-preview-container') {
  1265. document.querySelectorAll('#theta_rho_files .file-item').forEach(item => {
  1266. item.classList.remove('selected');
  1267. });
  1268. }
  1269. } else {
  1270. logMessage(`Error: Section with ID "${sectionId}" not found`);
  1271. }
  1272. }
  1273. // Function to open any sticky section
  1274. function openStickySection(sectionId) {
  1275. const section = document.getElementById(sectionId);
  1276. if (section) {
  1277. // Toggle the 'open' class
  1278. section.classList.toggle('open');
  1279. } else {
  1280. logMessage(`Error: Section with ID "${sectionId}" not found`);
  1281. }
  1282. }
  1283. function attachFullScreenListeners() {
  1284. // Add event listener to all fullscreen buttons
  1285. document.querySelectorAll('.fullscreen-button').forEach(button => {
  1286. button.addEventListener('click', function () {
  1287. const stickySection = this.closest('.sticky'); // Find the closest sticky section
  1288. if (stickySection) {
  1289. // Close all other sections
  1290. document.querySelectorAll('.sticky:not(#currently-playing-container)').forEach(section => {
  1291. if (section !== stickySection) {
  1292. section.classList.remove('fullscreen');
  1293. section.classList.remove('visible');
  1294. section.classList.add('hidden');
  1295. // Reset the fullscreen button text for other sections
  1296. const otherFullscreenButton = section.querySelector('.fullscreen-button');
  1297. if (otherFullscreenButton) {
  1298. otherFullscreenButton.innerHTML = '<i class="fa-solid fa-expand"></i>'; // Enter fullscreen icon/text
  1299. }
  1300. }
  1301. });
  1302. stickySection.classList.toggle('fullscreen'); // Toggle fullscreen class
  1303. // Update button icon or text
  1304. if (stickySection.classList.contains('fullscreen')) {
  1305. this.innerHTML = '<i class="fa-solid fa-compress"></i>'; // Exit fullscreen icon/text
  1306. } else {
  1307. this.innerHTML = '<i class="fa-solid fa-expand"></i>'; // Enter fullscreen icon/text
  1308. }
  1309. } else {
  1310. console.error('Error: Fullscreen button is not inside a sticky section.');
  1311. }
  1312. });
  1313. });
  1314. }
  1315. let lastPreviewedFile = null; // Track the last previewed file
  1316. function formatSecondsToHMS(seconds) {
  1317. const hrs = Math.floor(seconds / 3600);
  1318. const mins = Math.floor((seconds % 3600) / 60);
  1319. const secs = Math.floor(seconds % 60);
  1320. return `${String(hrs).padStart(2, '0')}:${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
  1321. }
  1322. // Function to start or stop updates based on visibility
  1323. function toggleSettings() {
  1324. const settingsContainer = document.getElementById('settings-container');
  1325. if (settingsContainer) {
  1326. settingsContainer.classList.toggle('open');
  1327. }
  1328. }
  1329. // Utility function to manage cookies
  1330. function setCookie(name, value, days) {
  1331. const date = new Date();
  1332. date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  1333. document.cookie = `${name}=${value};expires=${date.toUTCString()};path=/`;
  1334. }
  1335. function getCookie(name) {
  1336. const nameEQ = `${name}=`;
  1337. const cookies = document.cookie.split(';');
  1338. for (let i = 0; i < cookies.length; i++) {
  1339. let cookie = cookies[i].trim();
  1340. if (cookie.startsWith(nameEQ)) {
  1341. return cookie.substring(nameEQ.length);
  1342. }
  1343. }
  1344. return null;
  1345. }
  1346. // Save settings to cookies
  1347. function saveSettingsToCookies() {
  1348. const pauseTime = document.getElementById('pause_time').value;
  1349. const clearPattern = document.getElementById('clear_pattern').value;
  1350. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  1351. const shuffle = document.getElementById('shuffle_playlist').checked;
  1352. setCookie('pause_time', pauseTime, 365);
  1353. setCookie('clear_pattern', clearPattern, 365);
  1354. setCookie('run_mode', runMode, 365);
  1355. setCookie('shuffle', shuffle, 365);
  1356. }
  1357. // Load settings from cookies
  1358. function loadSettingsFromCookies() {
  1359. const pauseTime = getCookie('pause_time');
  1360. if (pauseTime !== '') {
  1361. document.getElementById('pause_time').value = pauseTime;
  1362. }
  1363. const clearPattern = getCookie('clear_pattern');
  1364. if (clearPattern !== '') {
  1365. document.getElementById('clear_pattern').value = clearPattern;
  1366. }
  1367. const runMode = getCookie('run_mode');
  1368. if (runMode !== '') {
  1369. document.querySelector(`input[name="run_mode"][value="${runMode}"]`).checked = true;
  1370. }
  1371. const shuffle = getCookie('shuffle');
  1372. if (shuffle !== '') {
  1373. document.getElementById('shuffle_playlist').checked = shuffle === 'true';
  1374. }
  1375. logMessage('Settings loaded from cookies.');
  1376. }
  1377. // Call this function to save settings when a value is changed
  1378. function attachSettingsSaveListeners() {
  1379. // Add event listeners to inputs
  1380. document.getElementById('pause_time').addEventListener('change', saveSettingsToCookies);
  1381. document.getElementById('clear_pattern').addEventListener('change', saveSettingsToCookies);
  1382. document.querySelectorAll('input[name="run_mode"]').forEach(input => {
  1383. input.addEventListener('change', saveSettingsToCookies);
  1384. });
  1385. document.getElementById('shuffle_playlist').addEventListener('change', saveSettingsToCookies);
  1386. }
  1387. // Tab switching logic with cookie storage
  1388. function switchTab(tabName) {
  1389. // Store the active tab in a cookie
  1390. setCookie('activeTab', tabName, 365); // Store for 7 days
  1391. // Deactivate all tab content
  1392. document.querySelectorAll('.tab-content').forEach(tab => {
  1393. tab.classList.remove('active');
  1394. });
  1395. // Activate the selected tab content
  1396. const activeTab = document.getElementById(`${tabName}-tab`);
  1397. if (activeTab) {
  1398. activeTab.classList.add('active');
  1399. } else {
  1400. console.error(`Error: Tab "${tabName}" not found.`);
  1401. }
  1402. // Deactivate all nav buttons
  1403. document.querySelectorAll('.bottom-nav .tab-button').forEach(button => {
  1404. button.classList.remove('active');
  1405. });
  1406. // Activate the selected nav button
  1407. const activeNavButton = document.getElementById(`nav-${tabName}`);
  1408. if (activeNavButton) {
  1409. activeNavButton.classList.add('active');
  1410. } else {
  1411. console.error(`Error: Nav button for "${tabName}" not found.`);
  1412. }
  1413. }
  1414. // Update the small UI segment to show the IP or hide it if none
  1415. function updateWledUI() {
  1416. const wledIp = localStorage.getItem('wled_ip');
  1417. const wledContainer = document.getElementById('wled-container');
  1418. const wledFrame = document.getElementById('wled-frame');
  1419. const wledStatus = document.getElementById('wled-status');
  1420. if (!wledIp) {
  1421. wledContainer.classList.add('hidden');
  1422. return;
  1423. }
  1424. // Show the container and load WLED UI
  1425. wledContainer.classList.remove('hidden');
  1426. wledFrame.src = `http://${wledIp}`;
  1427. }
  1428. // Save or clear the WLED IP, updating both the browser and backend
  1429. async function saveWledIp() {
  1430. const ipInput = document.getElementById('wled_ip');
  1431. const saveButton = document.querySelector('.wled-settings button.cta');
  1432. const currentIp = localStorage.getItem('wled_ip');
  1433. if (currentIp) {
  1434. // Clear the saved IP if one is already set
  1435. localStorage.removeItem('wled_ip');
  1436. ipInput.disabled = false;
  1437. ipInput.value = '';
  1438. saveButton.innerHTML = '<i class="fa-solid fa-save"></i><span>Save</span>';
  1439. logMessage('WLED IP cleared.', LOG_TYPE.INFO);
  1440. // Also clear the IP on the backend
  1441. try {
  1442. const response = await fetch('/set_wled_ip', {
  1443. method: 'POST',
  1444. headers: { 'Content-Type': 'application/json' },
  1445. body: JSON.stringify({ wled_ip: null })
  1446. });
  1447. const data = await response.json();
  1448. if (data.success) {
  1449. logMessage('Backend IP cleared successfully.', LOG_TYPE.INFO);
  1450. } else {
  1451. logMessage('Failed to clear backend IP.', LOG_TYPE.ERROR);
  1452. }
  1453. } catch (error) {
  1454. logMessage(`Error clearing backend IP: ${error.message}`, LOG_TYPE.ERROR);
  1455. }
  1456. } else {
  1457. // Validate and save the new IP
  1458. const ip = ipInput.value.trim();
  1459. if (!validateIp(ip)) {
  1460. logMessage('Invalid IP address format.', LOG_TYPE.ERROR);
  1461. return;
  1462. }
  1463. localStorage.setItem('wled_ip', ip);
  1464. ipInput.disabled = true;
  1465. saveButton.innerHTML = '<i class="fa-solid fa-xmark"></i><span>Clear</span>';
  1466. logMessage(`WLED IP saved: ${ip}`, LOG_TYPE.SUCCESS);
  1467. // Also save the IP to the backend
  1468. try {
  1469. const response = await fetch('/set_wled_ip', {
  1470. method: 'POST',
  1471. headers: { 'Content-Type': 'application/json' },
  1472. body: JSON.stringify({ wled_ip: ip })
  1473. });
  1474. const data = await response.json();
  1475. if (data.success) {
  1476. logMessage('Backend IP saved successfully.', LOG_TYPE.SUCCESS);
  1477. } else {
  1478. logMessage('Failed to save backend IP.', LOG_TYPE.ERROR);
  1479. }
  1480. } catch (error) {
  1481. logMessage(`Error saving backend IP: ${error.message}`, LOG_TYPE.ERROR);
  1482. }
  1483. }
  1484. updateWledUI(); // Refresh any UI elements that depend on the IP
  1485. }
  1486. // Load the WLED IP from localStorage; if not available, retrieve it from the backend
  1487. async function loadWledIp() {
  1488. const ipInput = document.getElementById('wled_ip');
  1489. const saveButton = document.querySelector('.wled-settings button.cta');
  1490. let savedIp = localStorage.getItem('wled_ip');
  1491. if (!savedIp) {
  1492. // Attempt to load from the backend if not found in localStorage
  1493. try {
  1494. const response = await fetch('/get_wled_ip');
  1495. const data = await response.json();
  1496. if (data.wled_ip) {
  1497. savedIp = data.wled_ip;
  1498. localStorage.setItem('wled_ip', savedIp);
  1499. }
  1500. } catch (error) {
  1501. logMessage(`Error fetching WLED IP from backend: ${error.message}`, LOG_TYPE.ERROR);
  1502. }
  1503. }
  1504. if (savedIp) {
  1505. ipInput.value = savedIp;
  1506. ipInput.disabled = true;
  1507. saveButton.innerHTML = '<i class="fa-solid fa-xmark"></i><span>Clear</span>';
  1508. } else {
  1509. ipInput.disabled = false;
  1510. saveButton.innerHTML = '<i class="fa-solid fa-save"></i><span>Save</span>';
  1511. }
  1512. updateWledUI(); // Update any dependent UI segments
  1513. }
  1514. function validateIp(ip) {
  1515. 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}$/;
  1516. return ipRegex.test(ip);
  1517. }
  1518. // Theme toggle functionality
  1519. const themeToggle = document.getElementById('theme-toggle');
  1520. const themeIcon = themeToggle.querySelector('i');
  1521. themeToggle.addEventListener('click', () => {
  1522. const root = document.documentElement;
  1523. const currentTheme = root.getAttribute('data-theme');
  1524. const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
  1525. root.setAttribute('data-theme', newTheme);
  1526. localStorage.setItem('theme', newTheme);
  1527. // Toggle the icon
  1528. themeIcon.className = newTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
  1529. });
  1530. // Set initial theme and icon based on saved theme
  1531. const savedTheme = localStorage.getItem('theme') || 'light';
  1532. document.documentElement.setAttribute('data-theme', savedTheme);
  1533. themeIcon.className = savedTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
  1534. // Add WebSocket connection for status updates
  1535. let statusSocket = null;
  1536. let reconnectAttempts = 0;
  1537. const MAX_RECONNECT_ATTEMPTS = 5;
  1538. let statusUpdateInterval = null;
  1539. let wsConnected = false;
  1540. function connectStatusWebSocket() {
  1541. // Don't create a new connection if one already exists
  1542. if (wsConnected) {
  1543. console.log('WebSocket already connected');
  1544. return;
  1545. }
  1546. // Close existing connection and clear interval if any
  1547. if (statusSocket) {
  1548. statusSocket.close();
  1549. }
  1550. if (statusUpdateInterval) {
  1551. clearInterval(statusUpdateInterval);
  1552. }
  1553. // Create WebSocket connection
  1554. const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  1555. statusSocket = new WebSocket(`${protocol}//${window.location.host}/ws/status`);
  1556. statusSocket.onopen = () => {
  1557. console.log('Status WebSocket connected');
  1558. wsConnected = true;
  1559. reconnectAttempts = 0; // Reset reconnect attempts on successful connection
  1560. };
  1561. statusSocket.onmessage = (event) => {
  1562. try {
  1563. const message = JSON.parse(event.data);
  1564. if (message.type === 'status_update' && message.data) {
  1565. updateCurrentlyPlayingUI(message.data);
  1566. // Disconnect WebSocket if no pattern is running
  1567. if (!message.data.is_running) {
  1568. console.log('No pattern running, disconnecting WebSocket');
  1569. disconnectStatusWebSocket();
  1570. }
  1571. }
  1572. } catch (error) {
  1573. console.error('Error processing status update:', error);
  1574. console.error('Raw data that caused error:', event.data);
  1575. }
  1576. };
  1577. statusSocket.onclose = () => {
  1578. console.log('Status WebSocket disconnected');
  1579. wsConnected = false;
  1580. clearInterval(statusUpdateInterval);
  1581. // Only attempt to reconnect if we're supposed to be connected
  1582. if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS && document.body.classList.contains('playing')) {
  1583. reconnectAttempts++;
  1584. const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000);
  1585. console.log(`Reconnecting in ${delay/1000}s (Attempt ${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`);
  1586. setTimeout(connectStatusWebSocket, delay);
  1587. }
  1588. };
  1589. statusSocket.onerror = (error) => {
  1590. console.error('WebSocket error:', error);
  1591. };
  1592. }
  1593. function disconnectStatusWebSocket() {
  1594. if (statusSocket && wsConnected) {
  1595. wsConnected = false;
  1596. statusSocket.close();
  1597. statusSocket = null;
  1598. reconnectAttempts = 0;
  1599. }
  1600. }
  1601. // Replace the polling mechanism with WebSocket
  1602. document.addEventListener('DOMContentLoaded', () => {
  1603. const activeTab = getCookie('activeTab') || 'patterns'; // Default to 'patterns' tab
  1604. switchTab(activeTab); // Load the active tab
  1605. checkSerialStatus(); // Check connection status
  1606. loadThetaRhoFiles(); // Load files on page load
  1607. loadAllPlaylists(); // Load all playlists on page load
  1608. attachSettingsSaveListeners(); // Attach event listeners to save changes
  1609. attachFullScreenListeners();
  1610. loadWledIp();
  1611. updateWledUI();
  1612. // Initialize WebSocket connection for status updates
  1613. connectStatusWebSocket();
  1614. // Handle visibility change
  1615. document.addEventListener('visibilitychange', () => {
  1616. if (document.visibilityState === 'visible' && statusSocket && statusSocket.readyState !== WebSocket.OPEN) {
  1617. connectStatusWebSocket();
  1618. }
  1619. });
  1620. checkForUpdates();
  1621. });
  1622. // Track the last time we had a file playing
  1623. let lastPlayingTime = 0;
  1624. const HIDE_DELAY = 5000; // 1 second delay before hiding
  1625. // Update the updateCurrentlyPlayingUI function to handle WebSocket updates
  1626. // Track the last played file to detect when a new pattern starts
  1627. let lastPlayedFile = null;
  1628. function updateCurrentlyPlayingUI(status) {
  1629. console.log('Updating UI with status:', status);
  1630. // Get all required DOM elements once
  1631. const container = document.getElementById('currently-playing-container');
  1632. const fileNameElement = document.getElementById('currently-playing-file');
  1633. const progressBar = document.getElementById('play_progress');
  1634. const progressText = document.getElementById('play_progress_text');
  1635. const pausePlayButton = document.getElementById('pausePlayCurrent');
  1636. const speedDisplay = document.getElementById('current_speed_display');
  1637. // Check if all required elements exist
  1638. if (!container || !fileNameElement || !progressBar || !progressText) {
  1639. console.log('Required DOM elements not found:', {
  1640. container: !!container,
  1641. fileNameElement: !!fileNameElement,
  1642. progressBar: !!progressBar,
  1643. progressText: !!progressText
  1644. });
  1645. setTimeout(() => updateCurrentlyPlayingUI(status), 100);
  1646. return;
  1647. }
  1648. // Update container visibility based on status
  1649. if (status.current_file && status.is_running) {
  1650. document.body.classList.add('playing');
  1651. container.style.display = 'flex';
  1652. // Hide the preview container when a pattern is playing
  1653. const previewContainer = document.getElementById('pattern-preview-container');
  1654. if (previewContainer) {
  1655. // Clear any selected file highlights
  1656. document.querySelectorAll('#theta_rho_files .file-item').forEach(item => {
  1657. item.classList.remove('selected');
  1658. });
  1659. }
  1660. } else {
  1661. document.body.classList.remove('playing');
  1662. container.style.display = 'none';
  1663. }
  1664. // Update file name display
  1665. if (status.current_file) {
  1666. const fileName = status.current_file.replace('./patterns/', '');
  1667. fileNameElement.textContent = fileName;
  1668. } else {
  1669. fileNameElement.textContent = 'No pattern playing';
  1670. }
  1671. // Update next file display
  1672. const nextFileElement = document.getElementById('next-file');
  1673. if (nextFileElement) {
  1674. if (status.playlist && status.playlist.next_file) {
  1675. const nextFileName = status.playlist.next_file.replace('./patterns/', '');
  1676. nextFileElement.textContent = `(Next: ${nextFileName})`;
  1677. nextFileElement.style.display = 'block';
  1678. } else {
  1679. nextFileElement.style.display = 'none';
  1680. }
  1681. }
  1682. // Update speed display if it exists
  1683. if (speedDisplay && status.speed) {
  1684. speedDisplay.textContent = `Current Speed: ${status.speed}`;
  1685. }
  1686. // Update pattern preview if it's a new pattern
  1687. if (status.current_file && lastPlayedFile !== status.current_file) {
  1688. lastPlayedFile = status.current_file;
  1689. const cleanFileName = status.current_file.replace('./patterns/', '');
  1690. previewPattern(cleanFileName, 'currently-playing-container');
  1691. }
  1692. // Update progress information
  1693. if (status.progress) {
  1694. const { percentage, remaining_time, elapsed_time } = status.progress;
  1695. const formattedPercentage = percentage.toFixed(1);
  1696. const remainingText = remaining_time === null ? 'calculating...' : formatSecondsToHMS(remaining_time);
  1697. const elapsedText = formatSecondsToHMS(elapsed_time);
  1698. progressBar.value = formattedPercentage;
  1699. progressText.textContent = `${formattedPercentage}% (Elapsed: ${elapsedText} | Remaining: ${remainingText})`;
  1700. } else {
  1701. progressBar.value = 0;
  1702. progressText.textContent = '0%';
  1703. }
  1704. // Update pause/play button if it exists
  1705. if (pausePlayButton) {
  1706. pausePlayButton.innerHTML = status.is_paused ?
  1707. '<i class="fa-solid fa-play"></i>' :
  1708. '<i class="fa-solid fa-pause"></i>';
  1709. }
  1710. // Update playlist UI if the function exists
  1711. if (typeof updatePlaylistUI === 'function') {
  1712. updatePlaylistUI(status);
  1713. }
  1714. // Update skip button visibility based on playlist status
  1715. updateSkipButtonVisibility(status);
  1716. }
  1717. // Add these functions to handle the skip button
  1718. function updateSkipButtonVisibility(status) {
  1719. const skipButton = document.getElementById('skipCurrent');
  1720. if (skipButton) {
  1721. // Check if a playlist is playing using the correct status properties
  1722. console.log('status', status);
  1723. const isPlaylistPlaying = status && status.playlist && status.playlist.next_file;
  1724. if (isPlaylistPlaying) {
  1725. skipButton.classList.remove('hidden');
  1726. } else {
  1727. skipButton.classList.add('hidden');
  1728. }
  1729. }
  1730. }
  1731. async function skipPattern() {
  1732. try {
  1733. const response = await fetch('/skip_pattern', {
  1734. method: 'POST',
  1735. });
  1736. const data = await response.json();
  1737. if (data.success) {
  1738. logMessage('Skipping to next pattern', LOG_TYPE.INFO);
  1739. } else {
  1740. logMessage(data.message, LOG_TYPE.ERROR);
  1741. }
  1742. } catch (error) {
  1743. logMessage('Error skipping pattern', 'error');
  1744. }
  1745. }