main.js 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060
  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):not(#image-converter)').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. const apiKey = document.getElementById('api-key').value;
  1353. setCookie('pause_time', pauseTime, 365);
  1354. setCookie('clear_pattern', clearPattern, 365);
  1355. setCookie('run_mode', runMode, 365);
  1356. setCookie('shuffle', shuffle, 365);
  1357. setCookie('api_key', apiKey, 365);
  1358. }
  1359. // Load settings from cookies
  1360. function loadSettingsFromCookies() {
  1361. const pauseTime = getCookie('pause_time');
  1362. if (pauseTime !== '') {
  1363. const pauseTimeElement = document.getElementById('pause_time');
  1364. if (pauseTimeElement) {
  1365. pauseTimeElement.value = pauseTime;
  1366. }
  1367. }
  1368. const clearPattern = getCookie('clear_pattern');
  1369. if (clearPattern !== '') {
  1370. const clearPatternElement = document.getElementById('clear_pattern');
  1371. if (clearPatternElement) {
  1372. clearPatternElement.value = clearPattern;
  1373. }
  1374. }
  1375. const runMode = getCookie('run_mode');
  1376. if (runMode !== '') {
  1377. const runModeElement = document.querySelector(`input[name="run_mode"][value="${runMode}"]`);
  1378. if (runModeElement) {
  1379. runModeElement.checked = true;
  1380. }
  1381. }
  1382. const shuffle = getCookie('shuffle');
  1383. if (shuffle !== '') {
  1384. const shuffleElement = document.getElementById('shuffle_playlist');
  1385. if (shuffleElement) {
  1386. shuffleElement.checked = shuffle === 'true';
  1387. }
  1388. }
  1389. const apiKey = getCookie('api_key');
  1390. if (apiKey !== '') {
  1391. const apiKeyElement = document.getElementById('api-key');
  1392. if (apiKeyElement) {
  1393. apiKeyElement.value = apiKey;
  1394. }
  1395. }
  1396. logMessage('Settings loaded from cookies.');
  1397. }
  1398. // Call this function to save settings when a value is changed
  1399. function attachSettingsSaveListeners() {
  1400. // Add event listeners to inputs
  1401. document.getElementById('pause_time').addEventListener('change', saveSettingsToCookies);
  1402. document.getElementById('clear_pattern').addEventListener('change', saveSettingsToCookies);
  1403. document.querySelectorAll('input[name="run_mode"]').forEach(input => {
  1404. input.addEventListener('change', saveSettingsToCookies);
  1405. });
  1406. document.getElementById('shuffle_playlist').addEventListener('change', saveSettingsToCookies);
  1407. document.getElementById('api-key').addEventListener('change', saveSettingsToCookies);
  1408. }
  1409. // Tab switching logic with cookie storage
  1410. function switchTab(tabName, tabGroup = 'main') {
  1411. // Store the active tab in a cookie (per tab group)
  1412. setCookie(`activeTab-${tabGroup}`, tabName, 365);
  1413. // Deactivate all tab content in the specific group
  1414. document.querySelectorAll(`.tab-content[data-group="${tabGroup}"]`).forEach(tab => {
  1415. tab.classList.remove('active');
  1416. });
  1417. // Activate the selected tab content
  1418. const activeTab = document.getElementById(`${tabName}-tab`);
  1419. if (activeTab) {
  1420. activeTab.classList.add('active');
  1421. } else {
  1422. console.error(`Error: Tab "${tabName}" not found.`);
  1423. }
  1424. // Deactivate all buttons in this group
  1425. document.querySelectorAll(`.tab-button[data-group="${tabGroup}"]`).forEach(button => {
  1426. button.classList.remove('active');
  1427. });
  1428. // Activate the selected nav button
  1429. const activeNavButton = document.getElementById(`nav-${tabName}`);
  1430. if (activeNavButton) {
  1431. activeNavButton.classList.add('active');
  1432. } else {
  1433. console.error(`Error: Nav button for "${tabName}" not found.`);
  1434. }
  1435. }
  1436. // Update the small UI segment to show the IP or hide it if none
  1437. function updateWledUI() {
  1438. const wledIp = localStorage.getItem('wled_ip');
  1439. const wledContainer = document.getElementById('wled-container');
  1440. const wledFrame = document.getElementById('wled-frame');
  1441. const wledStatus = document.getElementById('wled-status');
  1442. if (!wledIp) {
  1443. wledContainer.classList.add('hidden');
  1444. return;
  1445. }
  1446. // Show the container and load WLED UI
  1447. wledContainer.classList.remove('hidden');
  1448. wledFrame.src = `http://${wledIp}`;
  1449. }
  1450. // Save or clear the WLED IP, updating both the browser and backend
  1451. async function saveWledIp() {
  1452. const ipInput = document.getElementById('wled_ip');
  1453. const saveButton = document.querySelector('.wled-settings button.cta');
  1454. const currentIp = localStorage.getItem('wled_ip');
  1455. if (currentIp) {
  1456. // Clear the saved IP if one is already set
  1457. localStorage.removeItem('wled_ip');
  1458. ipInput.disabled = false;
  1459. ipInput.value = '';
  1460. saveButton.innerHTML = '<i class="fa-solid fa-save"></i><span>Save</span>';
  1461. logMessage('WLED IP cleared.', LOG_TYPE.INFO);
  1462. // Also clear the IP on the backend
  1463. try {
  1464. const response = await fetch('/set_wled_ip', {
  1465. method: 'POST',
  1466. headers: { 'Content-Type': 'application/json' },
  1467. body: JSON.stringify({ wled_ip: null })
  1468. });
  1469. const data = await response.json();
  1470. if (data.success) {
  1471. logMessage('Backend IP cleared successfully.', LOG_TYPE.INFO);
  1472. } else {
  1473. logMessage('Failed to clear backend IP.', LOG_TYPE.ERROR);
  1474. }
  1475. } catch (error) {
  1476. logMessage(`Error clearing backend IP: ${error.message}`, LOG_TYPE.ERROR);
  1477. }
  1478. } else {
  1479. // Validate and save the new IP
  1480. const ip = ipInput.value.trim();
  1481. if (!validateIp(ip)) {
  1482. logMessage('Invalid IP address format.', LOG_TYPE.ERROR);
  1483. return;
  1484. }
  1485. localStorage.setItem('wled_ip', ip);
  1486. ipInput.disabled = true;
  1487. saveButton.innerHTML = '<i class="fa-solid fa-xmark"></i><span>Clear</span>';
  1488. logMessage(`WLED IP saved: ${ip}`, LOG_TYPE.SUCCESS);
  1489. // Also save the IP to the backend
  1490. try {
  1491. const response = await fetch('/set_wled_ip', {
  1492. method: 'POST',
  1493. headers: { 'Content-Type': 'application/json' },
  1494. body: JSON.stringify({ wled_ip: ip })
  1495. });
  1496. const data = await response.json();
  1497. if (data.success) {
  1498. logMessage('Backend IP saved successfully.', LOG_TYPE.SUCCESS);
  1499. } else {
  1500. logMessage('Failed to save backend IP.', LOG_TYPE.ERROR);
  1501. }
  1502. } catch (error) {
  1503. logMessage(`Error saving backend IP: ${error.message}`, LOG_TYPE.ERROR);
  1504. }
  1505. }
  1506. updateWledUI(); // Refresh any UI elements that depend on the IP
  1507. }
  1508. // Load the WLED IP from localStorage; if not available, retrieve it from the backend
  1509. async function loadWledIp() {
  1510. const ipInput = document.getElementById('wled_ip');
  1511. const saveButton = document.querySelector('.wled-settings button.cta');
  1512. let savedIp = localStorage.getItem('wled_ip');
  1513. if (!savedIp) {
  1514. // Attempt to load from the backend if not found in localStorage
  1515. try {
  1516. const response = await fetch('/get_wled_ip');
  1517. const data = await response.json();
  1518. if (data.wled_ip) {
  1519. savedIp = data.wled_ip;
  1520. localStorage.setItem('wled_ip', savedIp);
  1521. }
  1522. } catch (error) {
  1523. logMessage(`Error fetching WLED IP from backend: ${error.message}`, LOG_TYPE.ERROR);
  1524. }
  1525. }
  1526. if (savedIp) {
  1527. ipInput.value = savedIp;
  1528. ipInput.disabled = true;
  1529. saveButton.innerHTML = '<i class="fa-solid fa-xmark"></i><span>Clear</span>';
  1530. } else {
  1531. ipInput.disabled = false;
  1532. saveButton.innerHTML = '<i class="fa-solid fa-save"></i><span>Save</span>';
  1533. }
  1534. updateWledUI(); // Update any dependent UI segments
  1535. }
  1536. function validateIp(ip) {
  1537. 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}$/;
  1538. return ipRegex.test(ip);
  1539. }
  1540. // Theme toggle functionality
  1541. const themeToggle = document.getElementById('theme-toggle');
  1542. const themeIcon = themeToggle.querySelector('i');
  1543. themeToggle.addEventListener('click', () => {
  1544. const root = document.documentElement;
  1545. const currentTheme = root.getAttribute('data-theme');
  1546. const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
  1547. root.setAttribute('data-theme', newTheme);
  1548. localStorage.setItem('theme', newTheme);
  1549. // Toggle the icon
  1550. themeIcon.className = newTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
  1551. });
  1552. // Set initial theme and icon based on saved theme
  1553. const savedTheme = localStorage.getItem('theme') || 'light';
  1554. document.documentElement.setAttribute('data-theme', savedTheme);
  1555. themeIcon.className = savedTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
  1556. // Add WebSocket connection for status updates
  1557. let statusSocket = null;
  1558. let reconnectAttempts = 0;
  1559. const MAX_RECONNECT_ATTEMPTS = 5;
  1560. let statusUpdateInterval = null;
  1561. let wsConnected = false;
  1562. function connectStatusWebSocket() {
  1563. // Don't create a new connection if one already exists
  1564. if (wsConnected) {
  1565. console.log('WebSocket already connected');
  1566. return;
  1567. }
  1568. // Close existing connection and clear interval if any
  1569. if (statusSocket) {
  1570. statusSocket.close();
  1571. }
  1572. if (statusUpdateInterval) {
  1573. clearInterval(statusUpdateInterval);
  1574. }
  1575. // Create WebSocket connection
  1576. const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  1577. statusSocket = new WebSocket(`${protocol}//${window.location.host}/ws/status`);
  1578. statusSocket.onopen = () => {
  1579. console.log('Status WebSocket connected');
  1580. wsConnected = true;
  1581. reconnectAttempts = 0; // Reset reconnect attempts on successful connection
  1582. };
  1583. statusSocket.onmessage = (event) => {
  1584. try {
  1585. const message = JSON.parse(event.data);
  1586. if (message.type === 'status_update' && message.data) {
  1587. updateCurrentlyPlayingUI(message.data);
  1588. // Disconnect WebSocket if no pattern is running
  1589. if (!message.data.is_running) {
  1590. console.log('No pattern running, disconnecting WebSocket');
  1591. disconnectStatusWebSocket();
  1592. }
  1593. }
  1594. } catch (error) {
  1595. console.error('Error processing status update:', error);
  1596. console.error('Raw data that caused error:', event.data);
  1597. }
  1598. };
  1599. statusSocket.onclose = () => {
  1600. console.log('Status WebSocket disconnected');
  1601. wsConnected = false;
  1602. clearInterval(statusUpdateInterval);
  1603. // Only attempt to reconnect if we're supposed to be connected
  1604. if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS && document.body.classList.contains('playing')) {
  1605. reconnectAttempts++;
  1606. const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000);
  1607. console.log(`Reconnecting in ${delay/1000}s (Attempt ${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`);
  1608. setTimeout(connectStatusWebSocket, delay);
  1609. }
  1610. };
  1611. statusSocket.onerror = (error) => {
  1612. console.error('WebSocket error:', error);
  1613. };
  1614. }
  1615. function disconnectStatusWebSocket() {
  1616. if (statusSocket && wsConnected) {
  1617. wsConnected = false;
  1618. statusSocket.close();
  1619. statusSocket = null;
  1620. reconnectAttempts = 0;
  1621. }
  1622. }
  1623. // Replace the polling mechanism with WebSocket
  1624. document.addEventListener('DOMContentLoaded', () => {
  1625. const activeMainTab = getCookie('activeTab-main') || 'patterns';
  1626. switchTab(activeMainTab, 'main');
  1627. const activeImageConverterTab = getCookie('activeTab-image-converter') || 'dot';
  1628. switchTab(activeImageConverterTab, 'image-converter');
  1629. checkSerialStatus(); // Check connection status
  1630. loadThetaRhoFiles(); // Load files on page load
  1631. loadAllPlaylists(); // Load all playlists on page load
  1632. attachSettingsSaveListeners(); // Attach event listeners to save changes
  1633. attachFullScreenListeners();
  1634. loadWledIp();
  1635. updateWledUI();
  1636. // Initialize WebSocket connection for status updates
  1637. connectStatusWebSocket();
  1638. // Handle visibility change
  1639. document.addEventListener('visibilitychange', () => {
  1640. if (document.visibilityState === 'visible' && statusSocket && statusSocket.readyState !== WebSocket.OPEN) {
  1641. connectStatusWebSocket();
  1642. }
  1643. });
  1644. checkForUpdates();
  1645. });
  1646. // Track the last time we had a file playing
  1647. let lastPlayingTime = 0;
  1648. const HIDE_DELAY = 5000; // 1 second delay before hiding
  1649. // Update the updateCurrentlyPlayingUI function to handle WebSocket updates
  1650. // Track the last played file to detect when a new pattern starts
  1651. let lastPlayedFile = null;
  1652. function updateCurrentlyPlayingUI(status) {
  1653. // Get all required DOM elements once
  1654. const container = document.getElementById('currently-playing-container');
  1655. const fileNameElement = document.getElementById('currently-playing-file');
  1656. const progressBar = document.getElementById('play_progress');
  1657. const progressText = document.getElementById('play_progress_text');
  1658. const pausePlayButton = document.getElementById('pausePlayCurrent');
  1659. const speedDisplay = document.getElementById('current_speed_display');
  1660. // Check if all required elements exist
  1661. if (!container || !fileNameElement || !progressBar || !progressText) {
  1662. console.log('Required DOM elements not found:', {
  1663. container: !!container,
  1664. fileNameElement: !!fileNameElement,
  1665. progressBar: !!progressBar,
  1666. progressText: !!progressText
  1667. });
  1668. setTimeout(() => updateCurrentlyPlayingUI(status), 100);
  1669. return;
  1670. }
  1671. // Update container visibility based on status
  1672. if (status.current_file && status.is_running) {
  1673. document.body.classList.add('playing');
  1674. container.style.display = 'flex';
  1675. // Hide the preview container when a pattern is playing
  1676. const previewContainer = document.getElementById('pattern-preview-container');
  1677. if (previewContainer) {
  1678. // Clear any selected file highlights
  1679. document.querySelectorAll('#theta_rho_files .file-item').forEach(item => {
  1680. item.classList.remove('selected');
  1681. });
  1682. }
  1683. } else {
  1684. document.body.classList.remove('playing');
  1685. container.style.display = 'none';
  1686. }
  1687. // Update file name display
  1688. if (status.current_file) {
  1689. const fileName = status.current_file.replace('./patterns/', '');
  1690. fileNameElement.textContent = fileName;
  1691. } else {
  1692. fileNameElement.textContent = 'No pattern playing';
  1693. }
  1694. // Update next file display
  1695. const nextFileElement = document.getElementById('next-file');
  1696. if (nextFileElement) {
  1697. if (status.playlist && status.playlist.next_file) {
  1698. const nextFileName = status.playlist.next_file.replace('./patterns/', '');
  1699. nextFileElement.textContent = `(Next: ${nextFileName})`;
  1700. nextFileElement.style.display = 'block';
  1701. } else {
  1702. nextFileElement.style.display = 'none';
  1703. }
  1704. }
  1705. // Update speed display if it exists
  1706. if (speedDisplay && status.speed) {
  1707. speedDisplay.textContent = `Current Speed: ${status.speed}`;
  1708. }
  1709. // Update pattern preview if it's a new pattern
  1710. if (status.current_file && lastPlayedFile !== status.current_file) {
  1711. lastPlayedFile = status.current_file;
  1712. const cleanFileName = status.current_file.replace('./patterns/', '');
  1713. previewPattern(cleanFileName, 'currently-playing-container');
  1714. }
  1715. // Update progress information
  1716. if (status.progress) {
  1717. const { percentage, remaining_time, elapsed_time } = status.progress;
  1718. const formattedPercentage = percentage.toFixed(1);
  1719. const remainingText = remaining_time === null ? 'calculating...' : formatSecondsToHMS(remaining_time);
  1720. const elapsedText = formatSecondsToHMS(elapsed_time);
  1721. progressBar.value = formattedPercentage;
  1722. progressText.textContent = `${formattedPercentage}% (Elapsed: ${elapsedText} | Remaining: ${remainingText})`;
  1723. } else {
  1724. progressBar.value = 0;
  1725. progressText.textContent = '0%';
  1726. }
  1727. // Update pause/play button if it exists
  1728. if (pausePlayButton) {
  1729. pausePlayButton.innerHTML = status.is_paused ?
  1730. '<i class="fa-solid fa-play"></i>' :
  1731. '<i class="fa-solid fa-pause"></i>';
  1732. }
  1733. // Update playlist UI if the function exists
  1734. if (typeof updatePlaylistUI === 'function') {
  1735. updatePlaylistUI(status);
  1736. }
  1737. // Update skip button visibility based on playlist status
  1738. updateSkipButtonVisibility(status);
  1739. }
  1740. // Add these functions to handle the skip button
  1741. function updateSkipButtonVisibility(status) {
  1742. const skipButton = document.getElementById('skipCurrent');
  1743. if (skipButton) {
  1744. // Check if a playlist is playing using the correct status properties
  1745. console.log('status', status);
  1746. const isPlaylistPlaying = status && status.playlist && status.playlist.next_file;
  1747. if (isPlaylistPlaying) {
  1748. skipButton.classList.remove('hidden');
  1749. } else {
  1750. skipButton.classList.add('hidden');
  1751. }
  1752. }
  1753. }
  1754. async function skipPattern() {
  1755. try {
  1756. const response = await fetch('/skip_pattern', {
  1757. method: 'POST',
  1758. });
  1759. const data = await response.json();
  1760. if (data.success) {
  1761. logMessage('Skipping to next pattern', LOG_TYPE.INFO);
  1762. } else {
  1763. logMessage(data.message, LOG_TYPE.ERROR);
  1764. }
  1765. } catch (error) {
  1766. logMessage('Error skipping pattern', 'error');
  1767. }
  1768. }