1
0

index.html 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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>Sand Table 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>Sand Table 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>
  28. <div class="section">
  29. <h2>Quick Actions</h2>
  30. <div class="button-group">
  31. <button onclick="sendHomeCommand()">Home Device</button>
  32. <button onclick="moveToCenter()">Move to Center</button>
  33. <button onclick="moveToPerimeter()">Move to Perimeter</button>
  34. <button onclick="runClearIn()">Clear from In</button>
  35. <button onclick="runClearOut()">Clear from Out</button>
  36. <button onclick="runSideway()">Clear Sideway</button>
  37. <button onclick="stopExecution()" class="delete-button">Stop</button>
  38. </div>
  39. <div class="coordinate-input button-group">
  40. <label for="theta_input">θ:</label>
  41. <input type="number" id="theta_input" placeholder="Theta">
  42. <label for="rho_input">ρ:</label>
  43. <input type="number" id="rho_input" placeholder="Rho">
  44. <button class="small-button" onclick="sendCoordinate()">Send to coordinate</button>
  45. </div>
  46. </div>
  47. <div class="section">
  48. <h2>Preview</h2>
  49. <canvas id="patternPreviewCanvas" style="width: 100%;"></canvas>
  50. <p id="first_coordinate">First Coordinate: Not available</p>
  51. <p id="last_coordinate">Last Coordinate: Not available</p>
  52. </div>
  53. </div>
  54. <!-- Right Column -->
  55. <div class="right-column">
  56. <div class="section">
  57. <h2>Pattern Files</h2>
  58. <input type="text" id="search_pattern" placeholder="Search files..." oninput="searchPatternFiles()">
  59. <ul id="theta_rho_files"></ul>
  60. <div class="pre-execution-toggles">
  61. <h3>Pre-Execution Action</h3>
  62. <label>
  63. <input type="radio" name="pre_execution" value="clear_in" id="clear_in"> Clear from In
  64. </label>
  65. <label>
  66. <input type="radio" name="pre_execution" value="clear_out" id="clear_out"> Clear from Out
  67. </label>
  68. <label>
  69. <input type="radio" name="pre_execution" value="clear_sideway" id="clear_out"> Clear sideway
  70. </label>
  71. <label>
  72. <input type="radio" name="pre_execution" value="none" id="no_action" checked> None
  73. </label>
  74. </div>
  75. <div class="button-group">
  76. <button id="run_button" disabled>Run Selected Pattern</button>
  77. </div>
  78. </div>
  79. <div class="section">
  80. <h2>Upload new files</h2>
  81. <div class="button-group">
  82. <input type="file" id="upload_file">
  83. <div class="button-group">
  84. <button onclick="uploadThetaRho()">Upload</button>
  85. <button id="delete_selected_button" class="delete-button" onclick="deleteSelectedFile()" disabled>Delete Selected File</button>
  86. </div>
  87. </div>
  88. </div>
  89. </div>
  90. <div class="footer">
  91. <div id="github">
  92. <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>
  93. <a href="https://github.com/tuanchris/dune-weaver/issues" target="_blank">
  94. <img src="https://img.shields.io/github/issues/tuanchris/dune-weaver?style=flat-square" alt="GitHub Issues">
  95. </a>
  96. </div>
  97. <button id="debug_button" class="small-button" onclick="toggleDebugLog()">
  98. Show Debug log
  99. </button>
  100. </div>
  101. <div id="status_log">
  102. <!-- Messages will be appended here -->
  103. </div>
  104. </div>
  105. <script>
  106. let selectedFile = null;
  107. function logMessage(message) {
  108. const log = document.getElementById('status_log');
  109. const entry = document.createElement('p');
  110. entry.textContent = message;
  111. log.appendChild(entry);
  112. log.scrollTop = log.scrollHeight; // Keep log scrolled to the bottom
  113. }
  114. async function selectFile(file, listItem) {
  115. selectedFile = file;
  116. // Highlight the selected file
  117. document.querySelectorAll('#theta_rho_files li').forEach(li => li.classList.remove('selected'));
  118. listItem.classList.add('selected');
  119. // Enable buttons
  120. document.getElementById('run_button').disabled = false;
  121. document.getElementById('delete_selected_button').disabled = false;
  122. logMessage(`Selected file: ${file}`);
  123. // Fetch and preview the selected file
  124. await previewPattern(file);
  125. }
  126. async function uploadThetaRho() {
  127. const fileInput = document.getElementById('upload_file');
  128. const file = fileInput.files[0];
  129. if (!file) {
  130. logMessage('No file selected for upload.');
  131. return;
  132. }
  133. logMessage(`Uploading file: ${file.name}...`);
  134. const formData = new FormData();
  135. formData.append('file', file);
  136. const response = await fetch('/upload_theta_rho', {
  137. method: 'POST',
  138. body: formData
  139. });
  140. const result = await response.json();
  141. if (result.success) {
  142. logMessage(`File uploaded successfully: ${file.name}`);
  143. await loadThetaRhoFiles();
  144. } else {
  145. logMessage(`Failed to upload file: ${file.name}`);
  146. }
  147. }
  148. async function deleteSelectedFile() {
  149. if (!selectedFile) {
  150. logMessage("No file selected for deletion.");
  151. return;
  152. }
  153. const userConfirmed = confirm(`Are you sure you want to delete the selected file "${selectedFile}"?`);
  154. if (!userConfirmed) return;
  155. logMessage(`Deleting file: ${selectedFile}...`);
  156. const response = await fetch('/delete_theta_rho_file', {
  157. method: 'POST',
  158. headers: { 'Content-Type': 'application/json' },
  159. body: JSON.stringify({ file_name: selectedFile }),
  160. });
  161. const result = await response.json();
  162. if (result.success) {
  163. const ul = document.getElementById('theta_rho_files');
  164. const selectedItem = Array.from(ul.children).find(li => li.classList.contains('selected'));
  165. if (selectedItem) selectedItem.remove();
  166. selectedFile = null;
  167. document.getElementById('run_button').disabled = true;
  168. document.getElementById('delete_selected_button').disabled = true;
  169. logMessage(`File deleted successfully: ${result.file_name}`);
  170. } else {
  171. logMessage(`Failed to delete file: ${selectedFile}`);
  172. }
  173. }
  174. async function runThetaRho() {
  175. if (!selectedFile) {
  176. logMessage("No file selected to run.");
  177. return;
  178. }
  179. // Get the selected pre-execution action
  180. const preExecutionAction = document.querySelector('input[name="pre_execution"]:checked').value;
  181. logMessage(`Running file: ${selectedFile} with pre-execution action: ${preExecutionAction}...`);
  182. const response = await fetch('/run_theta_rho', {
  183. method: 'POST',
  184. headers: { 'Content-Type': 'application/json' },
  185. body: JSON.stringify({ file_name: selectedFile, pre_execution: preExecutionAction })
  186. });
  187. const result = await response.json();
  188. if (result.success) {
  189. logMessage(`File running: ${selectedFile}`);
  190. } else {
  191. logMessage(`Failed to run file: ${selectedFile}`);
  192. }
  193. }
  194. async function stopExecution() {
  195. logMessage('Stopping execution...');
  196. const response = await fetch('/stop_execution', { method: 'POST' });
  197. const result = await response.json();
  198. if (result.success) {
  199. logMessage('Execution stopped.');
  200. } else {
  201. logMessage('Failed to stop execution.');
  202. }
  203. }
  204. async function loadSerialPorts() {
  205. const response = await fetch('/list_serial_ports');
  206. const ports = await response.json();
  207. const select = document.getElementById('serial_ports');
  208. select.innerHTML = '';
  209. ports.forEach(port => {
  210. const option = document.createElement('option');
  211. option.value = port;
  212. option.textContent = port;
  213. select.appendChild(option);
  214. });
  215. logMessage('Serial ports loaded.');
  216. }
  217. async function connectSerial() {
  218. const port = document.getElementById('serial_ports').value;
  219. const response = await fetch('/connect_serial', {
  220. method: 'POST',
  221. headers: { 'Content-Type': 'application/json' },
  222. body: JSON.stringify({ port })
  223. });
  224. const result = await response.json();
  225. if (result.success) {
  226. logMessage(`Connected to serial port: ${port}`);
  227. // Refresh the status
  228. await checkSerialStatus();
  229. } else {
  230. logMessage(`Error connecting to serial port: ${result.error}`);
  231. }
  232. }
  233. async function disconnectSerial() {
  234. const response = await fetch('/disconnect_serial', { method: 'POST' });
  235. const result = await response.json();
  236. if (result.success) {
  237. logMessage('Serial port disconnected.');
  238. // Refresh the status
  239. await checkSerialStatus();
  240. } else {
  241. logMessage(`Error disconnecting: ${result.error}`);
  242. }
  243. }
  244. async function restartSerial() {
  245. const port = document.getElementById('serial_ports').value;
  246. const response = await fetch('/restart_serial', {
  247. method: 'POST',
  248. headers: { 'Content-Type': 'application/json' },
  249. body: JSON.stringify({ port })
  250. });
  251. const result = await response.json();
  252. if (result.success) {
  253. document.getElementById('serial_status').textContent = `Restarted connection to ${port}`;
  254. logMessage('Serial connection restarted.');
  255. // No need to change visibility for restart
  256. } else {
  257. logMessage(`Error restarting serial connection: ${result.error}`);
  258. }
  259. }
  260. async function sendHomeCommand() {
  261. const response = await fetch('/send_home', { method: 'POST' });
  262. const result = await response.json();
  263. if (result.success) {
  264. logMessage('HOME command sent successfully.');
  265. } else {
  266. logMessage('Failed to send HOME command.');
  267. }
  268. }
  269. let allFiles = []; // Store all files for filtering
  270. async function loadThetaRhoFiles() {
  271. logMessage('Loading Theta-Rho files...');
  272. const response = await fetch('/list_theta_rho_files');
  273. let files = await response.json();
  274. // Filter only .thr files
  275. files = files.filter(file => file.endsWith('.thr'));
  276. // Separate files into categories
  277. const customPatternsFiles = files.filter(file => file.startsWith('custom_patterns/'));
  278. const otherFiles = files.filter(file => !file.startsWith('custom_patterns/'));
  279. // Sort the files
  280. const sortedFiles = [
  281. ...customPatternsFiles.sort(), // Custom patterns first
  282. ...otherFiles.sort() // Remaining files sorted alphabetically
  283. ];
  284. allFiles = sortedFiles; // Store the sorted list of files
  285. displayFiles(allFiles); // Display the sorted files
  286. logMessage('Theta-Rho files loaded successfully.');
  287. }
  288. function displayFiles(files) {
  289. const ul = document.getElementById('theta_rho_files');
  290. ul.innerHTML = ''; // Clear current list
  291. files.forEach(file => {
  292. const li = document.createElement('li');
  293. li.textContent = file;
  294. // Highlight the selected file when clicked
  295. li.onclick = () => selectFile(file, li);
  296. ul.appendChild(li);
  297. });
  298. }
  299. function searchPatternFiles() {
  300. const searchInput = document.getElementById('search_pattern').value.toLowerCase();
  301. const filteredFiles = allFiles.filter(file => file.toLowerCase().includes(searchInput));
  302. displayFiles(filteredFiles); // Display only matching files
  303. }
  304. async function moveToCenter() {
  305. logMessage('Moving to center...');
  306. const response = await fetch('/move_to_center', { method: 'POST' });
  307. const result = await response.json();
  308. if (result.success) {
  309. logMessage('Moved to center successfully.');
  310. } else {
  311. logMessage(`Failed to move to center: ${result.error}`);
  312. }
  313. }
  314. async function moveToPerimeter() {
  315. logMessage('Moving to perimeter...');
  316. const response = await fetch('/move_to_perimeter', { method: 'POST' });
  317. const result = await response.json();
  318. if (result.success) {
  319. logMessage('Moved to perimeter successfully.');
  320. } else {
  321. logMessage(`Failed to move to perimeter: ${result.error}`);
  322. }
  323. }
  324. async function sendCoordinate() {
  325. const theta = parseFloat(document.getElementById('theta_input').value);
  326. const rho = parseFloat(document.getElementById('rho_input').value);
  327. if (isNaN(theta) || isNaN(rho)) {
  328. logMessage('Invalid input: θ and ρ must be numbers.');
  329. return;
  330. }
  331. logMessage(`Sending coordinate: θ=${theta}, ρ=${rho}...`);
  332. const response = await fetch('/send_coordinate', {
  333. method: 'POST',
  334. headers: { 'Content-Type': 'application/json' },
  335. body: JSON.stringify({ theta, rho })
  336. });
  337. const result = await response.json();
  338. if (result.success) {
  339. logMessage(`Coordinate executed successfully: θ=${theta}, ρ=${rho}`);
  340. } else {
  341. logMessage(`Failed to execute coordinate: ${result.error}`);
  342. }
  343. }
  344. async function previewPattern(fileName) {
  345. logMessage(`Fetching data to preview file: ${fileName}...`);
  346. const response = await fetch('/preview_thr', {
  347. method: 'POST',
  348. headers: { 'Content-Type': 'application/json' },
  349. body: JSON.stringify({ file_name: fileName })
  350. });
  351. const result = await response.json();
  352. if (result.success) {
  353. const coordinates = result.coordinates;
  354. // Update coordinates display
  355. if (coordinates.length > 0) {
  356. const firstCoord = coordinates[0];
  357. const lastCoord = coordinates[coordinates.length - 1];
  358. document.getElementById('first_coordinate').textContent = `First Coordinate: θ=${firstCoord[0]}, ρ=${firstCoord[1]}`;
  359. document.getElementById('last_coordinate').textContent = `Last Coordinate: θ=${lastCoord[0]}, ρ=${lastCoord[1]}`;
  360. } else {
  361. document.getElementById('first_coordinate').textContent = 'First Coordinate: Not available';
  362. document.getElementById('last_coordinate').textContent = 'Last Coordinate: Not available';
  363. }
  364. renderPattern(coordinates);
  365. } else {
  366. logMessage(`Failed to fetch preview for file: ${result.error}`);
  367. // Clear the coordinate display on error
  368. document.getElementById('first_coordinate').textContent = 'First Coordinate: Not available';
  369. document.getElementById('last_coordinate').textContent = 'Last Coordinate: Not available';
  370. }
  371. }
  372. function renderPattern(coordinates) {
  373. const canvas = document.getElementById('patternPreviewCanvas');
  374. const ctx = canvas.getContext('2d');
  375. // Make canvas full screen
  376. canvas.width = window.innerWidth;
  377. canvas.height = window.innerHeight;
  378. // Clear the canvas
  379. ctx.clearRect(0, 0, canvas.width, canvas.height);
  380. // Convert polar to Cartesian and draw the pattern
  381. const centerX = canvas.width / 2;
  382. const centerY = canvas.height / 2;
  383. const maxRho = Math.max(...coordinates.map(coord => coord[1]));
  384. const scale = Math.min(canvas.width, canvas.height) / (2 * maxRho); // Scale to fit within the screen
  385. ctx.beginPath();
  386. coordinates.forEach(([theta, rho], index) => {
  387. const x = centerX + rho * Math.cos(theta) * scale;
  388. const y = centerY - rho * Math.sin(theta) * scale; // Invert y-axis for canvas
  389. if (index === 0) {
  390. ctx.moveTo(x, y);
  391. } else {
  392. ctx.lineTo(x, y);
  393. }
  394. });
  395. ctx.closePath();
  396. ctx.stroke();
  397. logMessage('Pattern preview rendered at full screen.');
  398. }
  399. function toggleDebugLog() {
  400. const statusLog = document.getElementById('status_log');
  401. const debugButton = document.getElementById('debug_button');
  402. if (statusLog.style.display === 'block') {
  403. statusLog.style.display = 'none';
  404. debugButton.textContent = 'Show Debug Log'; // Update the button label
  405. } else {
  406. statusLog.style.display = 'block';
  407. debugButton.textContent = 'Hide Debug Log'; // Update the button label
  408. statusLog.scrollIntoView({ behavior: 'smooth', block: 'start' }); // Smooth scrolling to the log
  409. }
  410. }
  411. async function checkSerialStatus() {
  412. const response = await fetch('/serial_status');
  413. const status = await response.json();
  414. const statusElement = document.getElementById('serial_status');
  415. const serialPortsContainer = document.getElementById('serial_ports_container');
  416. const connectButton = document.querySelector('button[onclick="connectSerial()"]');
  417. const disconnectButton = document.querySelector('button[onclick="disconnectSerial()"]');
  418. const restartButton = document.querySelector('button[onclick="restartSerial()"]');
  419. if (status.connected) {
  420. const port = status.port || 'Unknown'; // Fallback if port is undefined
  421. statusElement.textContent = `Connected to ${port}`;
  422. statusElement.classList.add('connected');
  423. statusElement.classList.remove('not-connected');
  424. logMessage(`Reconnected to serial port: ${port}`);
  425. // Hide Available Ports and show disconnect/restart buttons
  426. serialPortsContainer.style.display = 'none';
  427. connectButton.style.display = 'none';
  428. disconnectButton.style.display = 'inline-block';
  429. restartButton.style.display = 'inline-block';
  430. } else {
  431. statusElement.textContent = 'Not connected';
  432. statusElement.classList.add('not-connected');
  433. statusElement.classList.remove('connected');
  434. logMessage('No active serial connection.');
  435. // Show Available Ports and the connect button
  436. serialPortsContainer.style.display = 'block';
  437. connectButton.style.display = 'inline-block';
  438. disconnectButton.style.display = 'none';
  439. restartButton.style.display = 'none';
  440. // Attempt to auto-load available ports
  441. await loadSerialPorts();
  442. }
  443. }
  444. async function runFile(fileName) {
  445. const response = await fetch(`/run_theta_rho_file/${fileName}`, { method: 'POST' });
  446. const result = await response.json();
  447. if (result.success) {
  448. logMessage(`Running file: ${fileName}`);
  449. } else {
  450. logMessage(`Failed to run file: ${fileName}`);
  451. }
  452. }
  453. async function runClearIn() {
  454. await runFile('clear_from_in.thr');
  455. }
  456. async function runClearOut() {
  457. await runFile('clear_from_out.thr');
  458. }
  459. async function runSideway() {
  460. await runFile('clear_sideway.thr');
  461. }
  462. // Call this function on page load
  463. checkSerialStatus();
  464. // Initial load of serial ports and Theta-Rho files
  465. loadSerialPorts();
  466. loadThetaRhoFiles();
  467. document.getElementById('run_button').onclick = runThetaRho;
  468. </script>
  469. </body>
  470. </html>