index.html 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Dune Weaver Controller</title>
  7. <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
  8. <link rel="stylesheet" href="../static/style.css">
  9. </head>
  10. <body>
  11. <h1>Dune Weaver Controller</h1>
  12. <div class="container">
  13. <!-- Left Column -->
  14. <div class="left-column">
  15. <div class="section">
  16. <h2>Serial Connection</h2>
  17. <div id="serial_status_container">Status: <span id="serial_status" class="status"> Not connected</span></div>
  18. <div id="serial_ports_container">
  19. <label for="serial_ports">Available Ports:</label>
  20. <select id="serial_ports"></select>
  21. <button onclick="connectSerial()">Connect</button>
  22. </div>
  23. <div id="serial_ports_buttons" class="button-group">
  24. <button onclick="disconnectSerial()">Disconnect</button>
  25. <button onclick="restartSerial()">Restart</button>
  26. </div>
  27. <div class="button-group">
  28. <label for="speed_input">Speed:</label>
  29. <input type="number" id="speed_input" placeholder="1-5000" min="1" step="1" max="5000">
  30. <button class="small-button" onclick="changeSpeed()">Set Speed</button>
  31. </div>
  32. </div>
  33. <div class="section">
  34. <h2>Mode</h2>
  35. <label>
  36. <input type="radio" name="mode" class="modeSelector" value="single_run" checked> Single Run
  37. </label>
  38. <label>
  39. <input type="radio" name="mode" class="modeSelector" value="create_playlist"> Create Playlist
  40. </label>
  41. <label>
  42. <input type="radio" name="mode" class="modeSelector" value="run_playlist"> Run Playlist
  43. </label>
  44. </div>
  45. <div class="section">
  46. <h2>Quick Actions</h2>
  47. <div class="button-group">
  48. <button onclick="sendHomeCommand()">Home Device</button>
  49. <button onclick="moveToCenter()">Move to Center</button>
  50. <button onclick="moveToPerimeter()">Move to Perimeter</button>
  51. <button onclick="runClearIn()">Clear from In</button>
  52. <button onclick="runClearOut()">Clear from Out</button>
  53. <button onclick="runSideway()">Clear Sideway</button>
  54. <button onclick="stopExecution()" class="delete-button">Stop</button>
  55. </div>
  56. <div class="coordinate-input button-group">
  57. <label for="theta_input">θ:</label>
  58. <input type="number" id="theta_input" placeholder="Theta">
  59. <label for="rho_input">ρ:</label>
  60. <input type="number" id="rho_input" placeholder="Rho">
  61. <button class="small-button" onclick="sendCoordinate()">Send to coordinate</button>
  62. </div>
  63. </div>
  64. <div class="section">
  65. <h2>Preview</h2>
  66. <canvas id="patternPreviewCanvas" style="width: 100%;"></canvas>
  67. <p id="first_coordinate">First Coordinate: Not available</p>
  68. <p id="last_coordinate">Last Coordinate: Not available</p>
  69. </div>
  70. </div>
  71. <!-- Right Column -->
  72. <div class="right-column">
  73. <div class="section modeSection single_run create_playlist">
  74. <h2 class="modeSection single_run">Single Run</h2>
  75. <h2 class="modeSection create_playlist" style="display: none;"> Create Playlist</h2>
  76. <h2 class="modeSection run_playlist" style="display: none;"> Run Playlist</h2>
  77. <input class="modeSection single_run create_playlist" type="text" id="search_pattern" placeholder="Search files..." oninput="searchPatternFiles()">
  78. <ul class="modeSection single_run create_playlist" id="theta_rho_files"></ul>
  79. <div class="pre-execution-toggles modeSection single_run">
  80. <h3>Pre-Execution Action</h3>
  81. <label>
  82. <input type="radio" name="pre_execution" value="clear_in" id="clear_in"> Clear from In
  83. </label>
  84. <label>
  85. <input type="radio" name="pre_execution" value="clear_out" id="clear_out"> Clear from Out
  86. </label>
  87. <label>
  88. <input type="radio" name="pre_execution" value="clear_sideway" id="clear_out"> Clear sideway
  89. </label>
  90. <label>
  91. <input type="radio" name="pre_execution" value="none" id="no_action" checked> None
  92. </label>
  93. </div>
  94. <div class="button-group modeSection single_run">
  95. <button id="run_button" disabled>Run Selected File</button>
  96. <button onclick="stopExecution()" class="delete-button">Stop</button>
  97. </div>
  98. <div class="button-group modeSection create_playlist" style="display: none;">
  99. <button onclick="addToPlaylist()">Add File to Playlist</button>
  100. </div>
  101. </div>
  102. <div class="section modeSection single_run">
  103. <h2>Upload new files</h2>
  104. <div class="button-group">
  105. <input type="file" id="upload_file">
  106. <div class="button-group">
  107. <button onclick="uploadThetaRho()">Upload</button>
  108. <button id="delete_selected_button" class="delete-button" onclick="deleteSelectedFile()" disabled>Delete Selected File</button>
  109. </div>
  110. </div>
  111. </div>
  112. <div class="section modeSection create_playlist run_playlist" style="display: none;">
  113. <h2>Create Playlist</h2>
  114. <!-- A list showing the files that have been added to the playlist -->
  115. <ul id="playlist_items"></ul>
  116. <!-- Buttons to reorder files in the playlist -->
  117. <div class="button-group">
  118. <button onclick="movePlaylistItemUp()">Up</button>
  119. <button onclick="movePlaylistItemDown()">Down</button>
  120. <button onclick="removeFromPlaylist()" class="delete-button">Remove</button>
  121. </div>
  122. <div class="playlist-name-input">
  123. <label for="playlist_name">Playlist Name:</label>
  124. <input type="text" id="playlist_name" placeholder="Enter playlist name" />
  125. </div>
  126. <div class="button-group">
  127. <!-- Button to add the selected file (from #theta_rho_files) to the playlist -->
  128. <!-- Button to create/finalize the playlist -->
  129. <button onclick="savePlaylist()">Create Playlist</button>
  130. </div>
  131. </div>
  132. <div class="section modeSection create_playlist run_playlist" style="display: none;">
  133. <h2>Playlists</h2>
  134. <!-- Parameter Inputs -->
  135. <div class="playlist-parameters">
  136. <label for="pause_time">Pause Time (seconds):</label>
  137. <input type="number" id="pause_time" min="0" step="0.1" value="0">
  138. <label for="clear_pattern">Clear Pattern:</label>
  139. <select id="clear_pattern">
  140. <option value="none">None</option>
  141. <option value="clear_in">Clear from In</option>
  142. <option value="clear_out">Clear from Out</option>
  143. <option value="clear_sideway">Clear Sideway</option>
  144. <option value="random">Random</option>
  145. </select>
  146. <!-- New Parameters -->
  147. <div class="run-options">
  148. <label>Run Mode:</label>
  149. <label>
  150. <input type="radio" name="run_mode" value="single" checked> Single Run
  151. </label>
  152. <label>
  153. <input type="radio" name="run_mode" value="indefinite"> Indefinite Run
  154. </label>
  155. <label>
  156. <input type="checkbox" id="shuffle_playlist"> Shuffle Playlist
  157. </label>
  158. </div>
  159. </div>
  160. <!-- Playlists List -->
  161. <ul id="all_playlists"></ul>
  162. </div>
  163. </div>
  164. </div>
  165. </div>
  166. <div id="status_log">
  167. <h2>Status Log</h2>
  168. <!-- Messages will be appended here -->
  169. </div>
  170. <script>
  171. let selectedFile = null;
  172. function logMessage(message) {
  173. const log = document.getElementById('status_log');
  174. const entry = document.createElement('p');
  175. entry.textContent = message;
  176. log.appendChild(entry);
  177. log.scrollTop = log.scrollHeight; // Keep log scrolled to the bottom
  178. }
  179. async function selectFile(file, listItem) {
  180. selectedFile = file;
  181. // Highlight the selected file
  182. document.querySelectorAll('#theta_rho_files li').forEach(li => li.classList.remove('selected'));
  183. listItem.classList.add('selected');
  184. // Enable buttons
  185. document.getElementById('run_button').disabled = false;
  186. document.getElementById('delete_selected_button').disabled = false;
  187. logMessage(`Selected file: ${file}`);
  188. // Fetch and preview the selected file
  189. await previewPattern(file);
  190. }
  191. async function uploadThetaRho() {
  192. const fileInput = document.getElementById('upload_file');
  193. const file = fileInput.files[0];
  194. if (!file) {
  195. logMessage('No file selected for upload.');
  196. return;
  197. }
  198. logMessage(`Uploading file: ${file.name}...`);
  199. const formData = new FormData();
  200. formData.append('file', file);
  201. const response = await fetch('/upload_theta_rho', {
  202. method: 'POST',
  203. body: formData
  204. });
  205. const result = await response.json();
  206. if (result.success) {
  207. logMessage(`File uploaded successfully: ${file.name}`);
  208. await loadThetaRhoFiles();
  209. } else {
  210. logMessage(`Failed to upload file: ${file.name}`);
  211. }
  212. }
  213. async function deleteSelectedFile() {
  214. if (!selectedFile) {
  215. logMessage("No file selected for deletion.");
  216. return;
  217. }
  218. const userConfirmed = confirm(`Are you sure you want to delete the selected file "${selectedFile}"?`);
  219. if (!userConfirmed) return;
  220. logMessage(`Deleting file: ${selectedFile}...`);
  221. const response = await fetch('/delete_theta_rho_file', {
  222. method: 'POST',
  223. headers: { 'Content-Type': 'application/json' },
  224. body: JSON.stringify({ file_name: selectedFile }),
  225. });
  226. const result = await response.json();
  227. if (result.success) {
  228. const ul = document.getElementById('theta_rho_files');
  229. const selectedItem = Array.from(ul.children).find(li => li.classList.contains('selected'));
  230. if (selectedItem) selectedItem.remove();
  231. selectedFile = null;
  232. document.getElementById('run_button').disabled = true;
  233. document.getElementById('delete_selected_button').disabled = true;
  234. logMessage(`File deleted successfully: ${result.file_name}`);
  235. } else {
  236. logMessage(`Failed to delete file: ${selectedFile}`);
  237. }
  238. }
  239. async function runThetaRho() {
  240. if (!selectedFile) {
  241. logMessage("No file selected to run.");
  242. return;
  243. }
  244. // Get the selected pre-execution action
  245. const preExecutionAction = document.querySelector('input[name="pre_execution"]:checked').value;
  246. logMessage(`Running file: ${selectedFile} with pre-execution action: ${preExecutionAction}...`);
  247. const response = await fetch('/run_theta_rho', {
  248. method: 'POST',
  249. headers: { 'Content-Type': 'application/json' },
  250. body: JSON.stringify({ file_name: selectedFile, pre_execution: preExecutionAction })
  251. });
  252. const result = await response.json();
  253. if (result.success) {
  254. logMessage(`File running: ${selectedFile}`);
  255. } else {
  256. logMessage(`Failed to run file: ${selectedFile}`);
  257. }
  258. }
  259. async function stopExecution() {
  260. logMessage('Stopping execution...');
  261. const response = await fetch('/stop_execution', { method: 'POST' });
  262. const result = await response.json();
  263. if (result.success) {
  264. logMessage('Execution stopped.');
  265. } else {
  266. logMessage('Failed to stop execution.');
  267. }
  268. }
  269. async function loadSerialPorts() {
  270. const response = await fetch('/list_serial_ports');
  271. const ports = await response.json();
  272. const select = document.getElementById('serial_ports');
  273. select.innerHTML = '';
  274. ports.forEach(port => {
  275. const option = document.createElement('option');
  276. option.value = port;
  277. option.textContent = port;
  278. select.appendChild(option);
  279. });
  280. logMessage('Serial ports loaded.');
  281. }
  282. async function connectSerial() {
  283. const port = document.getElementById('serial_ports').value;
  284. const response = await fetch('/connect_serial', {
  285. method: 'POST',
  286. headers: { 'Content-Type': 'application/json' },
  287. body: JSON.stringify({ port })
  288. });
  289. const result = await response.json();
  290. if (result.success) {
  291. logMessage(`Connected to serial port: ${port}`);
  292. // Refresh the status
  293. await checkSerialStatus();
  294. } else {
  295. logMessage(`Error connecting to serial port: ${result.error}`);
  296. }
  297. }
  298. async function disconnectSerial() {
  299. const response = await fetch('/disconnect_serial', { method: 'POST' });
  300. const result = await response.json();
  301. if (result.success) {
  302. logMessage('Serial port disconnected.');
  303. // Refresh the status
  304. await checkSerialStatus();
  305. } else {
  306. logMessage(`Error disconnecting: ${result.error}`);
  307. }
  308. }
  309. async function restartSerial() {
  310. const port = document.getElementById('serial_ports').value;
  311. const response = await fetch('/restart_serial', {
  312. method: 'POST',
  313. headers: { 'Content-Type': 'application/json' },
  314. body: JSON.stringify({ port })
  315. });
  316. const result = await response.json();
  317. if (result.success) {
  318. document.getElementById('serial_status').textContent = `Restarted connection to ${port}`;
  319. logMessage('Serial connection restarted.');
  320. // No need to change visibility for restart
  321. } else {
  322. logMessage(`Error restarting serial connection: ${result.error}`);
  323. }
  324. }
  325. async function sendHomeCommand() {
  326. const response = await fetch('/send_home', { method: 'POST' });
  327. const result = await response.json();
  328. if (result.success) {
  329. logMessage('HOME command sent successfully.');
  330. } else {
  331. logMessage('Failed to send HOME command.');
  332. }
  333. }
  334. let allFiles = []; // Store all files for filtering
  335. async function loadThetaRhoFiles() {
  336. logMessage('Loading Theta-Rho files...');
  337. const response = await fetch('/list_theta_rho_files');
  338. let files = await response.json();
  339. // Filter only .thr files
  340. files = files.filter(file => file.endsWith('.thr'));
  341. // Separate files into categories
  342. const customPatternsFiles = files.filter(file => file.startsWith('custom_patterns/'));
  343. const otherFiles = files.filter(file => !file.startsWith('custom_patterns/'));
  344. // Sort the files
  345. const sortedFiles = [
  346. ...customPatternsFiles.sort(), // Custom patterns first
  347. ...otherFiles.sort() // Remaining files sorted alphabetically
  348. ];
  349. allFiles = sortedFiles; // Store the sorted list of files
  350. displayFiles(allFiles); // Display the sorted files
  351. logMessage('Theta-Rho files loaded successfully.');
  352. }
  353. function displayFiles(files) {
  354. const ul = document.getElementById('theta_rho_files');
  355. ul.innerHTML = ''; // Clear current list
  356. files.forEach(file => {
  357. const li = document.createElement('li');
  358. li.textContent = file;
  359. // Highlight the selected file when clicked
  360. li.onclick = () => selectFile(file, li);
  361. ul.appendChild(li);
  362. });
  363. }
  364. function searchPatternFiles() {
  365. const searchInput = document.getElementById('search_pattern').value.toLowerCase();
  366. const filteredFiles = allFiles.filter(file => file.toLowerCase().includes(searchInput));
  367. displayFiles(filteredFiles); // Display only matching files
  368. }
  369. async function moveToCenter() {
  370. logMessage('Moving to center...');
  371. const response = await fetch('/move_to_center', { method: 'POST' });
  372. const result = await response.json();
  373. if (result.success) {
  374. logMessage('Moved to center successfully.');
  375. } else {
  376. logMessage(`Failed to move to center: ${result.error}`);
  377. }
  378. }
  379. async function moveToPerimeter() {
  380. logMessage('Moving to perimeter...');
  381. const response = await fetch('/move_to_perimeter', { method: 'POST' });
  382. const result = await response.json();
  383. if (result.success) {
  384. logMessage('Moved to perimeter successfully.');
  385. } else {
  386. logMessage(`Failed to move to perimeter: ${result.error}`);
  387. }
  388. }
  389. async function sendCoordinate() {
  390. const theta = parseFloat(document.getElementById('theta_input').value);
  391. const rho = parseFloat(document.getElementById('rho_input').value);
  392. if (isNaN(theta) || isNaN(rho)) {
  393. logMessage('Invalid input: θ and ρ must be numbers.');
  394. return;
  395. }
  396. logMessage(`Sending coordinate: θ=${theta}, ρ=${rho}...`);
  397. const response = await fetch('/send_coordinate', {
  398. method: 'POST',
  399. headers: { 'Content-Type': 'application/json' },
  400. body: JSON.stringify({ theta, rho })
  401. });
  402. const result = await response.json();
  403. if (result.success) {
  404. logMessage(`Coordinate executed successfully: θ=${theta}, ρ=${rho}`);
  405. } else {
  406. logMessage(`Failed to execute coordinate: ${result.error}`);
  407. }
  408. }
  409. async function previewPattern(fileName) {
  410. logMessage(`Fetching data to preview file: ${fileName}...`);
  411. const response = await fetch('/preview_thr', {
  412. method: 'POST',
  413. headers: { 'Content-Type': 'application/json' },
  414. body: JSON.stringify({ file_name: fileName })
  415. });
  416. const result = await response.json();
  417. if (result.success) {
  418. const coordinates = result.coordinates;
  419. // Update coordinates display
  420. if (coordinates.length > 0) {
  421. const firstCoord = coordinates[0];
  422. const lastCoord = coordinates[coordinates.length - 1];
  423. document.getElementById('first_coordinate').textContent = `First Coordinate: θ=${firstCoord[0]}, ρ=${firstCoord[1]}`;
  424. document.getElementById('last_coordinate').textContent = `Last Coordinate: θ=${lastCoord[0]}, ρ=${lastCoord[1]}`;
  425. } else {
  426. document.getElementById('first_coordinate').textContent = 'First Coordinate: Not available';
  427. document.getElementById('last_coordinate').textContent = 'Last Coordinate: Not available';
  428. }
  429. renderPattern(coordinates);
  430. } else {
  431. logMessage(`Failed to fetch preview for file: ${result.error}`);
  432. // Clear the coordinate display on error
  433. document.getElementById('first_coordinate').textContent = 'First Coordinate: Not available';
  434. document.getElementById('last_coordinate').textContent = 'Last Coordinate: Not available';
  435. }
  436. }
  437. function renderPattern(coordinates) {
  438. const canvas = document.getElementById('patternPreviewCanvas');
  439. const ctx = canvas.getContext('2d');
  440. // Make canvas full screen
  441. canvas.width = window.innerWidth;
  442. canvas.height = window.innerHeight;
  443. // Clear the canvas
  444. ctx.clearRect(0, 0, canvas.width, canvas.height);
  445. // Convert polar to Cartesian and draw the pattern
  446. const centerX = canvas.width / 2;
  447. const centerY = canvas.height / 2;
  448. const maxRho = Math.max(...coordinates.map(coord => coord[1]));
  449. const scale = Math.min(canvas.width, canvas.height) / (2 * maxRho); // Scale to fit within the screen
  450. ctx.beginPath();
  451. coordinates.forEach(([theta, rho], index) => {
  452. const x = centerX + rho * Math.cos(theta) * scale;
  453. const y = centerY - rho * Math.sin(theta) * scale; // Invert y-axis for canvas
  454. if (index === 0) {
  455. ctx.moveTo(x, y);
  456. } else {
  457. ctx.lineTo(x, y);
  458. }
  459. });
  460. ctx.closePath();
  461. ctx.stroke();
  462. logMessage('Pattern preview rendered at full screen.');
  463. }
  464. function toggleDebugLog() {
  465. const statusLog = document.getElementById('status_log');
  466. const debugButton = document.getElementById('debug_button');
  467. if (statusLog.style.display === 'block') {
  468. statusLog.style.display = 'none';
  469. debugButton.textContent = 'Show Debug Log'; // Update the button label
  470. } else {
  471. statusLog.style.display = 'block';
  472. debugButton.textContent = 'Hide Debug Log'; // Update the button label
  473. statusLog.scrollIntoView({ behavior: 'smooth', block: 'start' }); // Smooth scrolling to the log
  474. }
  475. }
  476. async function checkSerialStatus() {
  477. const response = await fetch('/serial_status');
  478. const status = await response.json();
  479. const statusElement = document.getElementById('serial_status');
  480. const serialPortsContainer = document.getElementById('serial_ports_container');
  481. const connectButton = document.querySelector('button[onclick="connectSerial()"]');
  482. const disconnectButton = document.querySelector('button[onclick="disconnectSerial()"]');
  483. const restartButton = document.querySelector('button[onclick="restartSerial()"]');
  484. if (status.connected) {
  485. const port = status.port || 'Unknown'; // Fallback if port is undefined
  486. statusElement.textContent = `Connected to ${port}`;
  487. statusElement.classList.add('connected');
  488. statusElement.classList.remove('not-connected');
  489. logMessage(`Reconnected to serial port: ${port}`);
  490. // Hide Available Ports and show disconnect/restart buttons
  491. serialPortsContainer.style.display = 'none';
  492. connectButton.style.display = 'none';
  493. disconnectButton.style.display = 'inline-block';
  494. restartButton.style.display = 'inline-block';
  495. } else {
  496. statusElement.textContent = 'Not connected';
  497. statusElement.classList.add('not-connected');
  498. statusElement.classList.remove('connected');
  499. logMessage('No active serial connection.');
  500. // Show Available Ports and the connect button
  501. serialPortsContainer.style.display = 'block';
  502. connectButton.style.display = 'inline-block';
  503. disconnectButton.style.display = 'none';
  504. restartButton.style.display = 'none';
  505. // Attempt to auto-load available ports
  506. await loadSerialPorts();
  507. }
  508. }
  509. async function runFile(fileName) {
  510. const response = await fetch(`/run_theta_rho_file/${fileName}`, { method: 'POST' });
  511. const result = await response.json();
  512. if (result.success) {
  513. logMessage(`Running file: ${fileName}`);
  514. } else {
  515. logMessage(`Failed to run file: ${fileName}`);
  516. }
  517. }
  518. async function runClearIn() {
  519. await runFile('clear_from_in.thr');
  520. }
  521. async function runClearOut() {
  522. await runFile('clear_from_out.thr');
  523. }
  524. async function runSideway() {
  525. await runFile('clear_sideway.thr');
  526. }
  527. // Call this function on page load
  528. checkSerialStatus();
  529. // Initial load of serial ports and Theta-Rho files
  530. loadSerialPorts();
  531. loadThetaRhoFiles();
  532. document.getElementById('run_button').onclick = runThetaRho;
  533. document.querySelectorAll('.modeSelector').forEach((radio) => {
  534. radio.addEventListener('change', function () {
  535. // Hide all .modeSection first
  536. document.querySelectorAll('.modeSection').forEach((section) => {
  537. section.style.display = 'none';
  538. });
  539. // Figure out which mode was selected
  540. const selectedValue = this.value; // or document.querySelector('.modeSelector:checked').value
  541. // Show every element that has .modeSection AND the selected mode's class
  542. document
  543. .querySelectorAll(`.modeSection.${selectedValue}`)
  544. .forEach((elem) => {
  545. elem.style.display = 'block';
  546. });
  547. });
  548. });
  549. async function changeSpeed() {
  550. const speedInput = document.getElementById('speed_input');
  551. const speed = parseFloat(speedInput.value);
  552. if (isNaN(speed) || speed <= 0) {
  553. logMessage('Invalid speed. Please enter a positive number.');
  554. return;
  555. }
  556. logMessage(`Setting speed to: ${speed}...`);
  557. const response = await fetch('/set_speed', {
  558. method: 'POST',
  559. headers: { 'Content-Type': 'application/json' },
  560. body: JSON.stringify({ speed })
  561. });
  562. const result = await response.json();
  563. if (result.success) {
  564. document.getElementById('speed_status').textContent = `Current Speed: ${speed}`;
  565. logMessage(`Speed set to: ${speed}`);
  566. } else {
  567. logMessage(`Failed to set speed: ${result.error}`);
  568. }
  569. }
  570. // Keep track of the files in the new playlist
  571. let playlist = [];
  572. // Currently selected item in the playlist
  573. let selectedPlaylistIndex = null;
  574. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  575. // PART A: Loading / listing playlists from the server
  576. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  577. async function loadAllPlaylists() {
  578. try {
  579. const response = await fetch('/list_all_playlists'); // GET
  580. const allPlaylists = await response.json(); // e.g. ["My Playlist", "Summer", ...]
  581. displayAllPlaylists(allPlaylists);
  582. } catch (err) {
  583. logMessage(`Error loading playlists: ${err}`);
  584. }
  585. }
  586. // Function to display all playlists with Load, Run, and Delete buttons
  587. function displayAllPlaylists(allPlaylists) {
  588. const ul = document.getElementById('all_playlists');
  589. ul.innerHTML = ''; // Clear current list
  590. allPlaylists.forEach((playlistName) => {
  591. const li = document.createElement('li');
  592. li.classList.add('playlist-item'); // For styling
  593. // Playlist Name
  594. const nameSpan = document.createElement('span');
  595. nameSpan.textContent = playlistName;
  596. li.appendChild(nameSpan);
  597. // "Load" button
  598. const loadBtn = document.createElement('button');
  599. loadBtn.textContent = 'Load';
  600. loadBtn.onclick = () => loadPlaylist(playlistName);
  601. loadBtn.classList.add('load-button'); // For styling
  602. li.appendChild(loadBtn);
  603. // "Run" button
  604. const runBtn = document.createElement('button');
  605. runBtn.textContent = 'Run';
  606. runBtn.onclick = () => runPlaylist(playlistName);
  607. runBtn.classList.add('run-button'); // For styling
  608. li.appendChild(runBtn);
  609. // "Delete" button
  610. const deleteBtn = document.createElement('button');
  611. deleteBtn.textContent = 'Delete';
  612. deleteBtn.onclick = () => deletePlaylist(playlistName);
  613. deleteBtn.classList.add('delete-button'); // For styling
  614. li.appendChild(deleteBtn);
  615. ul.appendChild(li);
  616. });
  617. }
  618. // Function to run the selected playlist with specified parameters
  619. async function runPlaylist(playlistName) {
  620. if (!playlistName) {
  621. logMessage("No playlist selected to run.");
  622. return;
  623. }
  624. // Get the parameters from the UI
  625. const pauseTimeInput = document.getElementById('pause_time').value;
  626. const clearPatternSelect = document.getElementById('clear_pattern').value;
  627. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  628. const shuffle = document.getElementById('shuffle_playlist').checked;
  629. // Validate pause time
  630. const pauseTime = parseFloat(pauseTimeInput);
  631. if (isNaN(pauseTime) || pauseTime < 0) {
  632. logMessage("Invalid pause time. Please enter a non-negative number.");
  633. return;
  634. }
  635. // Map clear_pattern select value to backend expected values
  636. let clearPattern = clearPatternSelect;
  637. if (clearPatternSelect === "none") {
  638. clearPattern = null;
  639. }
  640. logMessage(`Running playlist: ${playlistName} with pause_time=${pauseTime}, clear_pattern=${clearPattern || "None"}, run_mode=${runMode}, shuffle=${shuffle}`);
  641. try {
  642. const response = await fetch('/run_playlist', {
  643. method: 'POST',
  644. headers: { 'Content-Type': 'application/json' },
  645. body: JSON.stringify({
  646. playlist_name: playlistName,
  647. pause_time: pauseTime,
  648. clear_pattern: clearPattern,
  649. run_mode: runMode, // 'single' or 'indefinite'
  650. shuffle: shuffle // true or false
  651. })
  652. });
  653. const result = await response.json();
  654. if (result.success) {
  655. logMessage(`Playlist "${playlistName}" is now running.`);
  656. } else {
  657. logMessage(`Failed to run playlist "${playlistName}": ${result.error}`);
  658. }
  659. } catch (error) {
  660. logMessage(`Error running playlist "${playlistName}": ${error}`);
  661. }
  662. }
  663. async function loadPlaylist(playlistName) {
  664. // This fetches the named playlist from /get_playlist?name=...
  665. try {
  666. const response = await fetch(`/get_playlist?name=${encodeURIComponent(playlistName)}`);
  667. const data = await response.json(); // { "name": "XYZ", "files": [...] }
  668. if (data.error) {
  669. logMessage(`Error loading playlist "${playlistName}": ${data.error}`);
  670. return;
  671. }
  672. // Clear current local playlist; replace with loaded data
  673. playlist = data.files || [];
  674. selectedPlaylistIndex = null;
  675. document.getElementById('playlist_name').value = data.name; // Fill in the name field
  676. refreshPlaylistUI();
  677. logMessage(`Loaded playlist: ${data.name} with ${playlist.length} file(s).`);
  678. } catch (err) {
  679. logMessage(`Error loading playlist: ${err}`);
  680. }
  681. }
  682. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  683. // PART B: Creating or Saving (Overwriting) a Playlist
  684. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  685. // Instead of separate create/modify functions, we’ll unify them:
  686. async function savePlaylist() {
  687. const name = document.getElementById('playlist_name').value.trim();
  688. if (!name) {
  689. logMessage("Please enter a playlist name.");
  690. return;
  691. }
  692. if (playlist.length === 0) {
  693. logMessage("No files in this playlist. Add files first.");
  694. return;
  695. }
  696. logMessage(`Saving playlist "${name}" with ${playlist.length} file(s)...`);
  697. try {
  698. // We can use /create_playlist or /modify_playlist. They do roughly the same in our single-file approach.
  699. // Let's use /create_playlist to always overwrite or create anew.
  700. const response = await fetch('/create_playlist', {
  701. method: 'POST',
  702. headers: { 'Content-Type': 'application/json' },
  703. body: JSON.stringify({
  704. name: name,
  705. files: playlist
  706. })
  707. });
  708. const result = await response.json();
  709. if (result.success) {
  710. logMessage(result.message);
  711. // Reload the entire list of playlists to reflect changes
  712. loadAllPlaylists();
  713. } else {
  714. logMessage(`Failed to save playlist: ${result.error}`);
  715. }
  716. } catch (err) {
  717. logMessage(`Error saving playlist: ${err}`);
  718. }
  719. }
  720. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  721. // PART C: Deleting a playlist
  722. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  723. async function deletePlaylist(playlistName) {
  724. if (!confirm(`Delete playlist "${playlistName}"? This cannot be undone.`)) {
  725. return;
  726. }
  727. try {
  728. const response = await fetch('/delete_playlist', {
  729. method: 'DELETE',
  730. headers: { 'Content-Type': 'application/json' },
  731. body: JSON.stringify({ name: playlistName })
  732. });
  733. const result = await response.json();
  734. if (result.success) {
  735. logMessage(result.message);
  736. loadAllPlaylists(); // Refresh the UI
  737. } else {
  738. logMessage(`Failed to delete playlist: ${result.error}`);
  739. }
  740. } catch (err) {
  741. logMessage(`Error deleting playlist: ${err}`);
  742. }
  743. }
  744. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  745. // PART D: Local playlist array UI
  746. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  747. // Called when the user clicks "Add File to Playlist"
  748. function addToPlaylist() {
  749. if (!selectedFile) {
  750. logMessage("No file selected to add to the playlist.");
  751. return;
  752. }
  753. // Add the current selectedFile to the local array
  754. playlist.push(selectedFile);
  755. logMessage(`Added "${selectedFile}" to the playlist.`);
  756. refreshPlaylistUI();
  757. }
  758. function refreshPlaylistUI() {
  759. const ul = document.getElementById('playlist_items');
  760. ul.innerHTML = '';
  761. playlist.forEach((file, index) => {
  762. const li = document.createElement('li');
  763. li.textContent = file;
  764. // When you click on a file in the playlist, mark it as selected
  765. li.onclick = () => selectPlaylistItem(index);
  766. // Highlight the currently selected playlist item
  767. if (index === selectedPlaylistIndex) {
  768. li.classList.add('selected');
  769. }
  770. ul.appendChild(li);
  771. });
  772. }
  773. function selectPlaylistItem(index) {
  774. selectedPlaylistIndex = index;
  775. refreshPlaylistUI();
  776. logMessage(`Selected playlist file: ${playlist[index]}`);
  777. }
  778. function movePlaylistItemUp() {
  779. if (selectedPlaylistIndex === null || selectedPlaylistIndex <= 0) return;
  780. const temp = playlist[selectedPlaylistIndex - 1];
  781. playlist[selectedPlaylistIndex - 1] = playlist[selectedPlaylistIndex];
  782. playlist[selectedPlaylistIndex] = temp;
  783. selectedPlaylistIndex--;
  784. refreshPlaylistUI();
  785. }
  786. function movePlaylistItemDown() {
  787. if (selectedPlaylistIndex === null || selectedPlaylistIndex >= playlist.length - 1) return;
  788. const temp = playlist[selectedPlaylistIndex + 1];
  789. playlist[selectedPlaylistIndex + 1] = playlist[selectedPlaylistIndex];
  790. playlist[selectedPlaylistIndex] = temp;
  791. selectedPlaylistIndex++;
  792. refreshPlaylistUI();
  793. }
  794. function removeFromPlaylist() {
  795. if (selectedPlaylistIndex === null) {
  796. logMessage("No item selected in the playlist to remove.");
  797. return;
  798. }
  799. const removedFile = playlist[selectedPlaylistIndex];
  800. playlist.splice(selectedPlaylistIndex, 1);
  801. selectedPlaylistIndex = null;
  802. refreshPlaylistUI();
  803. logMessage(`Removed "${removedFile}" from the playlist.`);
  804. }
  805. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  806. // PART E: Page load initialization
  807. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  808. // Make sure we load the existing playlists list on page load
  809. document.addEventListener('DOMContentLoaded', () => {
  810. loadAllPlaylists();
  811. });
  812. </script>
  813. </body>
  814. </html>