index.html 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  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 class="footer">
  167. <div id="github">
  168. <span>Help us improve! <a href="https://github.com/tuanchris/dune-weaver/pulls" target="_blank">Submit a Pull Request</a> or <a href="https://github.com/tuanchris/dune-weaver/issues/new" target="_blank">Report a Bug</a>.</span>
  169. <a href="https://github.com/tuanchris/dune-weaver/issues" target="_blank">
  170. <img src="https://img.shields.io/github/issues/tuanchris/dune-weaver?style=flat-square" alt="GitHub Issues">
  171. </a>
  172. </div>
  173. <button id="debug_button" class="small-button" onclick="toggleDebugLog()">
  174. Show Debug log
  175. </button>
  176. </div>
  177. <div id="status_log">
  178. <!-- Messages will be appended here -->
  179. </div>
  180. <script>
  181. let selectedFile = null;
  182. function logMessage(message) {
  183. const log = document.getElementById('status_log');
  184. const entry = document.createElement('p');
  185. entry.textContent = message;
  186. log.appendChild(entry);
  187. log.scrollTop = log.scrollHeight; // Keep log scrolled to the bottom
  188. }
  189. async function selectFile(file, listItem) {
  190. selectedFile = file;
  191. // Highlight the selected file
  192. document.querySelectorAll('#theta_rho_files li').forEach(li => li.classList.remove('selected'));
  193. listItem.classList.add('selected');
  194. // Enable buttons
  195. document.getElementById('run_button').disabled = false;
  196. document.getElementById('delete_selected_button').disabled = false;
  197. logMessage(`Selected file: ${file}`);
  198. // Fetch and preview the selected file
  199. await previewPattern(file);
  200. }
  201. async function uploadThetaRho() {
  202. const fileInput = document.getElementById('upload_file');
  203. const file = fileInput.files[0];
  204. if (!file) {
  205. logMessage('No file selected for upload.');
  206. return;
  207. }
  208. logMessage(`Uploading file: ${file.name}...`);
  209. const formData = new FormData();
  210. formData.append('file', file);
  211. const response = await fetch('/upload_theta_rho', {
  212. method: 'POST',
  213. body: formData
  214. });
  215. const result = await response.json();
  216. if (result.success) {
  217. logMessage(`File uploaded successfully: ${file.name}`);
  218. await loadThetaRhoFiles();
  219. } else {
  220. logMessage(`Failed to upload file: ${file.name}`);
  221. }
  222. }
  223. async function deleteSelectedFile() {
  224. if (!selectedFile) {
  225. logMessage("No file selected for deletion.");
  226. return;
  227. }
  228. const userConfirmed = confirm(`Are you sure you want to delete the selected file "${selectedFile}"?`);
  229. if (!userConfirmed) return;
  230. logMessage(`Deleting file: ${selectedFile}...`);
  231. const response = await fetch('/delete_theta_rho_file', {
  232. method: 'POST',
  233. headers: { 'Content-Type': 'application/json' },
  234. body: JSON.stringify({ file_name: selectedFile }),
  235. });
  236. const result = await response.json();
  237. if (result.success) {
  238. const ul = document.getElementById('theta_rho_files');
  239. const selectedItem = Array.from(ul.children).find(li => li.classList.contains('selected'));
  240. if (selectedItem) selectedItem.remove();
  241. selectedFile = null;
  242. document.getElementById('run_button').disabled = true;
  243. document.getElementById('delete_selected_button').disabled = true;
  244. logMessage(`File deleted successfully: ${result.file_name}`);
  245. } else {
  246. logMessage(`Failed to delete file: ${selectedFile}`);
  247. }
  248. }
  249. async function runThetaRho() {
  250. if (!selectedFile) {
  251. logMessage("No file selected to run.");
  252. return;
  253. }
  254. // Get the selected pre-execution action
  255. const preExecutionAction = document.querySelector('input[name="pre_execution"]:checked').value;
  256. logMessage(`Running file: ${selectedFile} with pre-execution action: ${preExecutionAction}...`);
  257. const response = await fetch('/run_theta_rho', {
  258. method: 'POST',
  259. headers: { 'Content-Type': 'application/json' },
  260. body: JSON.stringify({ file_name: selectedFile, pre_execution: preExecutionAction })
  261. });
  262. const result = await response.json();
  263. if (result.success) {
  264. logMessage(`File running: ${selectedFile}`);
  265. } else {
  266. logMessage(`Failed to run file: ${selectedFile}`);
  267. }
  268. }
  269. async function stopExecution() {
  270. logMessage('Stopping execution...');
  271. const response = await fetch('/stop_execution', { method: 'POST' });
  272. const result = await response.json();
  273. if (result.success) {
  274. logMessage('Execution stopped.');
  275. } else {
  276. logMessage('Failed to stop execution.');
  277. }
  278. }
  279. async function loadSerialPorts() {
  280. const response = await fetch('/list_serial_ports');
  281. const ports = await response.json();
  282. const select = document.getElementById('serial_ports');
  283. select.innerHTML = '';
  284. ports.forEach(port => {
  285. const option = document.createElement('option');
  286. option.value = port;
  287. option.textContent = port;
  288. select.appendChild(option);
  289. });
  290. logMessage('Serial ports loaded.');
  291. }
  292. async function connectSerial() {
  293. const port = document.getElementById('serial_ports').value;
  294. const response = await fetch('/connect_serial', {
  295. method: 'POST',
  296. headers: { 'Content-Type': 'application/json' },
  297. body: JSON.stringify({ port })
  298. });
  299. const result = await response.json();
  300. if (result.success) {
  301. logMessage(`Connected to serial port: ${port}`);
  302. // Refresh the status
  303. await checkSerialStatus();
  304. } else {
  305. logMessage(`Error connecting to serial port: ${result.error}`);
  306. }
  307. }
  308. async function disconnectSerial() {
  309. const response = await fetch('/disconnect_serial', { method: 'POST' });
  310. const result = await response.json();
  311. if (result.success) {
  312. logMessage('Serial port disconnected.');
  313. // Refresh the status
  314. await checkSerialStatus();
  315. } else {
  316. logMessage(`Error disconnecting: ${result.error}`);
  317. }
  318. }
  319. async function restartSerial() {
  320. const port = document.getElementById('serial_ports').value;
  321. const response = await fetch('/restart_serial', {
  322. method: 'POST',
  323. headers: { 'Content-Type': 'application/json' },
  324. body: JSON.stringify({ port })
  325. });
  326. const result = await response.json();
  327. if (result.success) {
  328. document.getElementById('serial_status').textContent = `Restarted connection to ${port}`;
  329. logMessage('Serial connection restarted.');
  330. // No need to change visibility for restart
  331. } else {
  332. logMessage(`Error restarting serial connection: ${result.error}`);
  333. }
  334. }
  335. async function sendHomeCommand() {
  336. const response = await fetch('/send_home', { method: 'POST' });
  337. const result = await response.json();
  338. if (result.success) {
  339. logMessage('HOME command sent successfully.');
  340. } else {
  341. logMessage('Failed to send HOME command.');
  342. }
  343. }
  344. let allFiles = []; // Store all files for filtering
  345. async function loadThetaRhoFiles() {
  346. logMessage('Loading Theta-Rho files...');
  347. const response = await fetch('/list_theta_rho_files');
  348. let files = await response.json();
  349. // Filter only .thr files
  350. files = files.filter(file => file.endsWith('.thr'));
  351. // Separate files into categories
  352. const customPatternsFiles = files.filter(file => file.startsWith('custom_patterns/'));
  353. const otherFiles = files.filter(file => !file.startsWith('custom_patterns/'));
  354. // Sort the files
  355. const sortedFiles = [
  356. ...customPatternsFiles.sort(), // Custom patterns first
  357. ...otherFiles.sort() // Remaining files sorted alphabetically
  358. ];
  359. allFiles = sortedFiles; // Store the sorted list of files
  360. displayFiles(allFiles); // Display the sorted files
  361. logMessage('Theta-Rho files loaded successfully.');
  362. }
  363. function displayFiles(files) {
  364. const ul = document.getElementById('theta_rho_files');
  365. ul.innerHTML = ''; // Clear current list
  366. files.forEach(file => {
  367. const li = document.createElement('li');
  368. li.textContent = file;
  369. // Highlight the selected file when clicked
  370. li.onclick = () => selectFile(file, li);
  371. ul.appendChild(li);
  372. });
  373. }
  374. function searchPatternFiles() {
  375. const searchInput = document.getElementById('search_pattern').value.toLowerCase();
  376. const filteredFiles = allFiles.filter(file => file.toLowerCase().includes(searchInput));
  377. displayFiles(filteredFiles); // Display only matching files
  378. }
  379. async function moveToCenter() {
  380. logMessage('Moving to center...');
  381. const response = await fetch('/move_to_center', { method: 'POST' });
  382. const result = await response.json();
  383. if (result.success) {
  384. logMessage('Moved to center successfully.');
  385. } else {
  386. logMessage(`Failed to move to center: ${result.error}`);
  387. }
  388. }
  389. async function moveToPerimeter() {
  390. logMessage('Moving to perimeter...');
  391. const response = await fetch('/move_to_perimeter', { method: 'POST' });
  392. const result = await response.json();
  393. if (result.success) {
  394. logMessage('Moved to perimeter successfully.');
  395. } else {
  396. logMessage(`Failed to move to perimeter: ${result.error}`);
  397. }
  398. }
  399. async function sendCoordinate() {
  400. const theta = parseFloat(document.getElementById('theta_input').value);
  401. const rho = parseFloat(document.getElementById('rho_input').value);
  402. if (isNaN(theta) || isNaN(rho)) {
  403. logMessage('Invalid input: θ and ρ must be numbers.');
  404. return;
  405. }
  406. logMessage(`Sending coordinate: θ=${theta}, ρ=${rho}...`);
  407. const response = await fetch('/send_coordinate', {
  408. method: 'POST',
  409. headers: { 'Content-Type': 'application/json' },
  410. body: JSON.stringify({ theta, rho })
  411. });
  412. const result = await response.json();
  413. if (result.success) {
  414. logMessage(`Coordinate executed successfully: θ=${theta}, ρ=${rho}`);
  415. } else {
  416. logMessage(`Failed to execute coordinate: ${result.error}`);
  417. }
  418. }
  419. async function previewPattern(fileName) {
  420. logMessage(`Fetching data to preview file: ${fileName}...`);
  421. const response = await fetch('/preview_thr', {
  422. method: 'POST',
  423. headers: { 'Content-Type': 'application/json' },
  424. body: JSON.stringify({ file_name: fileName })
  425. });
  426. const result = await response.json();
  427. if (result.success) {
  428. const coordinates = result.coordinates;
  429. // Update coordinates display
  430. if (coordinates.length > 0) {
  431. const firstCoord = coordinates[0];
  432. const lastCoord = coordinates[coordinates.length - 1];
  433. document.getElementById('first_coordinate').textContent = `First Coordinate: θ=${firstCoord[0]}, ρ=${firstCoord[1]}`;
  434. document.getElementById('last_coordinate').textContent = `Last Coordinate: θ=${lastCoord[0]}, ρ=${lastCoord[1]}`;
  435. } else {
  436. document.getElementById('first_coordinate').textContent = 'First Coordinate: Not available';
  437. document.getElementById('last_coordinate').textContent = 'Last Coordinate: Not available';
  438. }
  439. renderPattern(coordinates);
  440. } else {
  441. logMessage(`Failed to fetch preview for file: ${result.error}`);
  442. // Clear the coordinate display on error
  443. document.getElementById('first_coordinate').textContent = 'First Coordinate: Not available';
  444. document.getElementById('last_coordinate').textContent = 'Last Coordinate: Not available';
  445. }
  446. }
  447. function renderPattern(coordinates) {
  448. const canvas = document.getElementById('patternPreviewCanvas');
  449. const ctx = canvas.getContext('2d');
  450. // Make canvas full screen
  451. canvas.width = window.innerWidth;
  452. canvas.height = window.innerHeight;
  453. // Clear the canvas
  454. ctx.clearRect(0, 0, canvas.width, canvas.height);
  455. // Convert polar to Cartesian and draw the pattern
  456. const centerX = canvas.width / 2;
  457. const centerY = canvas.height / 2;
  458. const maxRho = Math.max(...coordinates.map(coord => coord[1]));
  459. const scale = Math.min(canvas.width, canvas.height) / (2 * maxRho); // Scale to fit within the screen
  460. ctx.beginPath();
  461. coordinates.forEach(([theta, rho], index) => {
  462. const x = centerX + rho * Math.cos(theta) * scale;
  463. const y = centerY - rho * Math.sin(theta) * scale; // Invert y-axis for canvas
  464. if (index === 0) {
  465. ctx.moveTo(x, y);
  466. } else {
  467. ctx.lineTo(x, y);
  468. }
  469. });
  470. ctx.closePath();
  471. ctx.stroke();
  472. logMessage('Pattern preview rendered at full screen.');
  473. }
  474. function toggleDebugLog() {
  475. const statusLog = document.getElementById('status_log');
  476. const debugButton = document.getElementById('debug_button');
  477. if (statusLog.style.display === 'block') {
  478. statusLog.style.display = 'none';
  479. debugButton.textContent = 'Show Debug Log'; // Update the button label
  480. } else {
  481. statusLog.style.display = 'block';
  482. debugButton.textContent = 'Hide Debug Log'; // Update the button label
  483. statusLog.scrollIntoView({ behavior: 'smooth', block: 'start' }); // Smooth scrolling to the log
  484. }
  485. }
  486. async function checkSerialStatus() {
  487. const response = await fetch('/serial_status');
  488. const status = await response.json();
  489. const statusElement = document.getElementById('serial_status');
  490. const serialPortsContainer = document.getElementById('serial_ports_container');
  491. const connectButton = document.querySelector('button[onclick="connectSerial()"]');
  492. const disconnectButton = document.querySelector('button[onclick="disconnectSerial()"]');
  493. const restartButton = document.querySelector('button[onclick="restartSerial()"]');
  494. if (status.connected) {
  495. const port = status.port || 'Unknown'; // Fallback if port is undefined
  496. statusElement.textContent = `Connected to ${port}`;
  497. statusElement.classList.add('connected');
  498. statusElement.classList.remove('not-connected');
  499. logMessage(`Reconnected to serial port: ${port}`);
  500. // Hide Available Ports and show disconnect/restart buttons
  501. serialPortsContainer.style.display = 'none';
  502. connectButton.style.display = 'none';
  503. disconnectButton.style.display = 'inline-block';
  504. restartButton.style.display = 'inline-block';
  505. } else {
  506. statusElement.textContent = 'Not connected';
  507. statusElement.classList.add('not-connected');
  508. statusElement.classList.remove('connected');
  509. logMessage('No active serial connection.');
  510. // Show Available Ports and the connect button
  511. serialPortsContainer.style.display = 'block';
  512. connectButton.style.display = 'inline-block';
  513. disconnectButton.style.display = 'none';
  514. restartButton.style.display = 'none';
  515. // Attempt to auto-load available ports
  516. await loadSerialPorts();
  517. }
  518. }
  519. async function runFile(fileName) {
  520. const response = await fetch(`/run_theta_rho_file/${fileName}`, { method: 'POST' });
  521. const result = await response.json();
  522. if (result.success) {
  523. logMessage(`Running file: ${fileName}`);
  524. } else {
  525. logMessage(`Failed to run file: ${fileName}`);
  526. }
  527. }
  528. async function runClearIn() {
  529. await runFile('clear_from_in.thr');
  530. }
  531. async function runClearOut() {
  532. await runFile('clear_from_out.thr');
  533. }
  534. async function runSideway() {
  535. await runFile('clear_sideway.thr');
  536. }
  537. // Call this function on page load
  538. checkSerialStatus();
  539. // Initial load of serial ports and Theta-Rho files
  540. loadSerialPorts();
  541. loadThetaRhoFiles();
  542. document.getElementById('run_button').onclick = runThetaRho;
  543. document.querySelectorAll('.modeSelector').forEach((radio) => {
  544. radio.addEventListener('change', function () {
  545. // Hide all .modeSection first
  546. document.querySelectorAll('.modeSection').forEach((section) => {
  547. section.style.display = 'none';
  548. });
  549. // Figure out which mode was selected
  550. const selectedValue = this.value; // or document.querySelector('.modeSelector:checked').value
  551. // Show every element that has .modeSection AND the selected mode's class
  552. document
  553. .querySelectorAll(`.modeSection.${selectedValue}`)
  554. .forEach((elem) => {
  555. elem.style.display = 'block';
  556. });
  557. });
  558. });
  559. async function changeSpeed() {
  560. const speedInput = document.getElementById('speed_input');
  561. const speed = parseFloat(speedInput.value);
  562. if (isNaN(speed) || speed <= 0) {
  563. logMessage('Invalid speed. Please enter a positive number.');
  564. return;
  565. }
  566. logMessage(`Setting speed to: ${speed}...`);
  567. const response = await fetch('/set_speed', {
  568. method: 'POST',
  569. headers: { 'Content-Type': 'application/json' },
  570. body: JSON.stringify({ speed })
  571. });
  572. const result = await response.json();
  573. if (result.success) {
  574. document.getElementById('speed_status').textContent = `Current Speed: ${speed}`;
  575. logMessage(`Speed set to: ${speed}`);
  576. } else {
  577. logMessage(`Failed to set speed: ${result.error}`);
  578. }
  579. }
  580. // Keep track of the files in the new playlist
  581. let playlist = [];
  582. // Currently selected item in the playlist
  583. let selectedPlaylistIndex = null;
  584. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  585. // PART A: Loading / listing playlists from the server
  586. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  587. async function loadAllPlaylists() {
  588. try {
  589. const response = await fetch('/list_all_playlists'); // GET
  590. const allPlaylists = await response.json(); // e.g. ["My Playlist", "Summer", ...]
  591. displayAllPlaylists(allPlaylists);
  592. } catch (err) {
  593. logMessage(`Error loading playlists: ${err}`);
  594. }
  595. }
  596. // Function to display all playlists with Load, Run, and Delete buttons
  597. function displayAllPlaylists(allPlaylists) {
  598. const ul = document.getElementById('all_playlists');
  599. ul.innerHTML = ''; // Clear current list
  600. allPlaylists.forEach((playlistName) => {
  601. const li = document.createElement('li');
  602. li.classList.add('playlist-item'); // For styling
  603. // Playlist Name
  604. const nameSpan = document.createElement('span');
  605. nameSpan.textContent = playlistName;
  606. li.appendChild(nameSpan);
  607. // "Load" button
  608. const loadBtn = document.createElement('button');
  609. loadBtn.textContent = 'Load';
  610. loadBtn.onclick = () => loadPlaylist(playlistName);
  611. loadBtn.classList.add('load-button'); // For styling
  612. li.appendChild(loadBtn);
  613. // "Run" button
  614. const runBtn = document.createElement('button');
  615. runBtn.textContent = 'Run';
  616. runBtn.onclick = () => runPlaylist(playlistName);
  617. runBtn.classList.add('run-button'); // For styling
  618. li.appendChild(runBtn);
  619. // "Delete" button
  620. const deleteBtn = document.createElement('button');
  621. deleteBtn.textContent = 'Delete';
  622. deleteBtn.onclick = () => deletePlaylist(playlistName);
  623. deleteBtn.classList.add('delete-button'); // For styling
  624. li.appendChild(deleteBtn);
  625. ul.appendChild(li);
  626. });
  627. }
  628. // Function to run the selected playlist with specified parameters
  629. async function runPlaylist(playlistName) {
  630. if (!playlistName) {
  631. logMessage("No playlist selected to run.");
  632. return;
  633. }
  634. // Get the parameters from the UI
  635. const pauseTimeInput = document.getElementById('pause_time').value;
  636. const clearPatternSelect = document.getElementById('clear_pattern').value;
  637. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  638. const shuffle = document.getElementById('shuffle_playlist').checked;
  639. // Validate pause time
  640. const pauseTime = parseFloat(pauseTimeInput);
  641. if (isNaN(pauseTime) || pauseTime < 0) {
  642. logMessage("Invalid pause time. Please enter a non-negative number.");
  643. return;
  644. }
  645. // Map clear_pattern select value to backend expected values
  646. let clearPattern = clearPatternSelect;
  647. if (clearPatternSelect === "none") {
  648. clearPattern = null;
  649. }
  650. logMessage(`Running playlist: ${playlistName} with pause_time=${pauseTime}, clear_pattern=${clearPattern || "None"}, run_mode=${runMode}, shuffle=${shuffle}`);
  651. try {
  652. const response = await fetch('/run_playlist', {
  653. method: 'POST',
  654. headers: { 'Content-Type': 'application/json' },
  655. body: JSON.stringify({
  656. playlist_name: playlistName,
  657. pause_time: pauseTime,
  658. clear_pattern: clearPattern,
  659. run_mode: runMode, // 'single' or 'indefinite'
  660. shuffle: shuffle // true or false
  661. })
  662. });
  663. const result = await response.json();
  664. if (result.success) {
  665. logMessage(`Playlist "${playlistName}" is now running.`);
  666. } else {
  667. logMessage(`Failed to run playlist "${playlistName}": ${result.error}`);
  668. }
  669. } catch (error) {
  670. logMessage(`Error running playlist "${playlistName}": ${error}`);
  671. }
  672. }
  673. async function loadPlaylist(playlistName) {
  674. // This fetches the named playlist from /get_playlist?name=...
  675. try {
  676. const response = await fetch(`/get_playlist?name=${encodeURIComponent(playlistName)}`);
  677. const data = await response.json(); // { "name": "XYZ", "files": [...] }
  678. if (data.error) {
  679. logMessage(`Error loading playlist "${playlistName}": ${data.error}`);
  680. return;
  681. }
  682. // Clear current local playlist; replace with loaded data
  683. playlist = data.files || [];
  684. selectedPlaylistIndex = null;
  685. document.getElementById('playlist_name').value = data.name; // Fill in the name field
  686. refreshPlaylistUI();
  687. logMessage(`Loaded playlist: ${data.name} with ${playlist.length} file(s).`);
  688. } catch (err) {
  689. logMessage(`Error loading playlist: ${err}`);
  690. }
  691. }
  692. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  693. // PART B: Creating or Saving (Overwriting) a Playlist
  694. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  695. // Instead of separate create/modify functions, we’ll unify them:
  696. async function savePlaylist() {
  697. const name = document.getElementById('playlist_name').value.trim();
  698. if (!name) {
  699. logMessage("Please enter a playlist name.");
  700. return;
  701. }
  702. if (playlist.length === 0) {
  703. logMessage("No files in this playlist. Add files first.");
  704. return;
  705. }
  706. logMessage(`Saving playlist "${name}" with ${playlist.length} file(s)...`);
  707. try {
  708. // We can use /create_playlist or /modify_playlist. They do roughly the same in our single-file approach.
  709. // Let's use /create_playlist to always overwrite or create anew.
  710. const response = await fetch('/create_playlist', {
  711. method: 'POST',
  712. headers: { 'Content-Type': 'application/json' },
  713. body: JSON.stringify({
  714. name: name,
  715. files: playlist
  716. })
  717. });
  718. const result = await response.json();
  719. if (result.success) {
  720. logMessage(result.message);
  721. // Reload the entire list of playlists to reflect changes
  722. loadAllPlaylists();
  723. } else {
  724. logMessage(`Failed to save playlist: ${result.error}`);
  725. }
  726. } catch (err) {
  727. logMessage(`Error saving playlist: ${err}`);
  728. }
  729. }
  730. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  731. // PART C: Deleting a playlist
  732. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  733. async function deletePlaylist(playlistName) {
  734. if (!confirm(`Delete playlist "${playlistName}"? This cannot be undone.`)) {
  735. return;
  736. }
  737. try {
  738. const response = await fetch('/delete_playlist', {
  739. method: 'DELETE',
  740. headers: { 'Content-Type': 'application/json' },
  741. body: JSON.stringify({ name: playlistName })
  742. });
  743. const result = await response.json();
  744. if (result.success) {
  745. logMessage(result.message);
  746. loadAllPlaylists(); // Refresh the UI
  747. } else {
  748. logMessage(`Failed to delete playlist: ${result.error}`);
  749. }
  750. } catch (err) {
  751. logMessage(`Error deleting playlist: ${err}`);
  752. }
  753. }
  754. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  755. // PART D: Local playlist array UI
  756. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  757. // Called when the user clicks "Add File to Playlist"
  758. function addToPlaylist() {
  759. if (!selectedFile) {
  760. logMessage("No file selected to add to the playlist.");
  761. return;
  762. }
  763. // Add the current selectedFile to the local array
  764. playlist.push(selectedFile);
  765. logMessage(`Added "${selectedFile}" to the playlist.`);
  766. refreshPlaylistUI();
  767. }
  768. function refreshPlaylistUI() {
  769. const ul = document.getElementById('playlist_items');
  770. ul.innerHTML = '';
  771. playlist.forEach((file, index) => {
  772. const li = document.createElement('li');
  773. li.textContent = file;
  774. // When you click on a file in the playlist, mark it as selected
  775. li.onclick = () => selectPlaylistItem(index);
  776. // Highlight the currently selected playlist item
  777. if (index === selectedPlaylistIndex) {
  778. li.classList.add('selected');
  779. }
  780. ul.appendChild(li);
  781. });
  782. }
  783. function selectPlaylistItem(index) {
  784. selectedPlaylistIndex = index;
  785. refreshPlaylistUI();
  786. logMessage(`Selected playlist file: ${playlist[index]}`);
  787. }
  788. function movePlaylistItemUp() {
  789. if (selectedPlaylistIndex === null || selectedPlaylistIndex <= 0) return;
  790. const temp = playlist[selectedPlaylistIndex - 1];
  791. playlist[selectedPlaylistIndex - 1] = playlist[selectedPlaylistIndex];
  792. playlist[selectedPlaylistIndex] = temp;
  793. selectedPlaylistIndex--;
  794. refreshPlaylistUI();
  795. }
  796. function movePlaylistItemDown() {
  797. if (selectedPlaylistIndex === null || selectedPlaylistIndex >= playlist.length - 1) return;
  798. const temp = playlist[selectedPlaylistIndex + 1];
  799. playlist[selectedPlaylistIndex + 1] = playlist[selectedPlaylistIndex];
  800. playlist[selectedPlaylistIndex] = temp;
  801. selectedPlaylistIndex++;
  802. refreshPlaylistUI();
  803. }
  804. function removeFromPlaylist() {
  805. if (selectedPlaylistIndex === null) {
  806. logMessage("No item selected in the playlist to remove.");
  807. return;
  808. }
  809. const removedFile = playlist[selectedPlaylistIndex];
  810. playlist.splice(selectedPlaylistIndex, 1);
  811. selectedPlaylistIndex = null;
  812. refreshPlaylistUI();
  813. logMessage(`Removed "${removedFile}" from the playlist.`);
  814. }
  815. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  816. // PART E: Page load initialization
  817. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  818. // Make sure we load the existing playlists list on page load
  819. document.addEventListener('DOMContentLoaded', () => {
  820. loadAllPlaylists();
  821. });
  822. </script>
  823. </body>
  824. </html>