index.html 40 KB

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