Explorar el Código

add preexec options

Tuan Nguyen hace 1 año
padre
commit
b6e8b4e4a5
Se han modificado 2 ficheros con 71 adiciones y 46 borrados
  1. 35 46
      templates/theta_rho_controller.html
  2. 36 0
      theta_rho_app.py

+ 35 - 46
templates/theta_rho_controller.html

@@ -48,6 +48,17 @@
     <button onclick="restartSerial()">Restart</button>
     <p id="serial_status" class="status">Status: Not connected</p>
 
+    <h2>Pre-Execution Options</h2>
+    <label>
+        <input type="radio" name="clear_action" value="clear_from_in"> Clear from In
+    </label>
+    <label>
+        <input type="radio" name="clear_action" value="clear_from_out"> Clear from Out
+    </label>
+    <label>
+        <input type="radio" name="clear_action" value="none" checked> None
+    </label>
+
     <h2>Theta-Rho Files</h2>
     <ul id="theta_rho_files"></ul>
     <input type="file" id="upload_file">
@@ -57,11 +68,6 @@
     <button id="run_button" disabled>Run Selected File</button>
     <button onclick="stopExecution()">Stop</button>
 
-    <h2>Quick Actions</h2>
-    <button onclick="sendHomeCommand()">Home Device</button>
-    <button onclick="runClearIn()">Clear from in</button>
-    <button onclick="runClearOut()">Clear from out</button>
-
     <div id="status_log">
         <h3>Status Log</h3>
         <!-- Messages will be appended here -->
@@ -137,7 +143,12 @@
 
         async function loadThetaRhoFiles() {
             const response = await fetch('/list_theta_rho_files');
-            const files = await response.json();
+            let files = await response.json();
+
+            // Exclude specific files and sort
+            files = files.filter(file => !['clear_from_in.thr', 'clear_from_out.thr'].includes(file))
+                         .sort();
+
             const ul = document.getElementById('theta_rho_files');
             ul.innerHTML = '';
             files.forEach(file => {
@@ -146,7 +157,7 @@
                 li.onclick = () => selectFile(file, li);
                 ul.appendChild(li);
             });
-            logMessage('Theta-Rho files loaded.');
+            logMessage('Theta-Rho files loaded and sorted.');
         }
 
         function selectFile(file, listItem) {
@@ -180,17 +191,23 @@
         async function runThetaRho() {
             if (!selectedFile) return;
 
-            const response = await fetch('/run_theta_rho', {
-                method: 'POST',
-                headers: { 'Content-Type': 'application/json' },
-                body: JSON.stringify({ file_name: selectedFile })
-            });
-
-            const result = await response.json();
-            if (result.success) {
-                logMessage(`Running Theta-Rho file: ${selectedFile}`);
-            } else {
-                logMessage(`Error starting Theta-Rho execution: ${result.error}`);
+            const clearAction = document.querySelector('input[name="clear_action"]:checked').value;
+
+            try {
+                const response = await fetch('/run_theta_rho_with_action', {
+                    method: 'POST',
+                    headers: { 'Content-Type': 'application/json' },
+                    body: JSON.stringify({ file_name: selectedFile, action: clearAction })
+                });
+
+                const result = await response.json();
+                if (result.success) {
+                    logMessage(`Execution started successfully for file: ${selectedFile}`);
+                } else {
+                    logMessage(`Error during execution: ${result.error}`);
+                }
+            } catch (error) {
+                logMessage(`Error during execution: ${error.message}`);
             }
         }
 
@@ -204,34 +221,6 @@
             }
         }
 
-        async function sendHomeCommand() {
-            const response = await fetch('/send_home', { method: 'POST' });
-            const result = await response.json();
-            if (result.success) {
-                logMessage('HOME command sent successfully.');
-            } else {
-                logMessage('Failed to send HOME command.');
-            }
-        }
-
-        async function runClearIn() {
-            await runFile('clear_from_in.thr');
-        }
-
-        async function runClearOut() {
-            await runFile('clear_from_out.thr');
-        }
-
-        async function runFile(fileName) {
-            const response = await fetch(`/run_theta_rho_file/${fileName}`, { method: 'POST' });
-            const result = await response.json();
-            if (result.success) {
-                logMessage(`Running file: ${fileName}`);
-            } else {
-                logMessage(`Failed to run file: ${fileName}`);
-            }
-        }
-
         // Initial load of serial ports and Theta-Rho files
         loadSerialPorts();
         loadThetaRhoFiles();

+ 36 - 0
theta_rho_app.py

@@ -169,6 +169,8 @@ def restart():
 @app.route('/list_theta_rho_files', methods=['GET'])
 def list_theta_rho_files():
     files = os.listdir(THETA_RHO_DIR)
+    # Exclude clear_from_in.thr and clear_from_out.thr and sort
+    files = sorted(file for file in files if file not in ['clear_from_in.thr', 'clear_from_out.thr'])
     return jsonify(files)
 
 @app.route('/upload_theta_rho', methods=['POST'])
@@ -224,5 +226,39 @@ def download_file(filename):
     """Download a file from the theta-rho directory."""
     return send_from_directory(THETA_RHO_DIR, filename)
 
+@app.route('/run_theta_rho_with_action', methods=['POST'])
+def run_theta_rho_with_action():
+    """Run a theta-rho file with a pre-execution action if specified."""
+    data = request.json
+    file_name = data.get('file_name')
+    action = data.get('action', 'none')  # Default to 'none' if no action is specified
+
+    if not file_name:
+        return jsonify({'error': 'No file name provided'}), 400
+
+    # Handle pre-execution action
+    if action != 'none':
+        action_file_path = os.path.join(THETA_RHO_DIR, f"{action}.thr")
+        if not os.path.exists(action_file_path):
+            return jsonify({'error': f"Action file {action}.thr not found"}), 404
+
+        try:
+            # Run the pre-execution file synchronously
+            run_theta_rho_file(action_file_path)
+        except Exception as e:
+            return jsonify({'error': f"Failed to execute pre-action {action}: {str(e)}"}), 500
+
+    # Run the main Theta-Rho file
+    file_path = os.path.join(THETA_RHO_DIR, file_name)
+    if not os.path.exists(file_path):
+        return jsonify({'error': 'File not found'}), 404
+
+    try:
+        # Start a thread to run the main file asynchronously
+        threading.Thread(target=run_theta_rho_file, args=(file_path,)).start()
+        return jsonify({'success': True})
+    except Exception as e:
+        return jsonify({'error': f"Failed to execute file {file_name}: {str(e)}"}), 500
+
 if __name__ == '__main__':
     app.run(debug=True, host='0.0.0.0', port=8080)