Преглед изворни кода

handle reconnect if disconnected at the start of each pattern

Tuan Nguyen пре 11 месеци
родитељ
комит
b04dfa3516

+ 2 - 2
dune_weaver_flask/app.py

@@ -62,7 +62,7 @@ def disconnect():
         logger.error(f'Failed to disconnect serial: {str(e)}')
         return jsonify({'error': str(e)}), 500
 
-@app.route('/restart_serial', methods=['POST'])
+@app.route('/restart_connection', methods=['POST'])
 def restart():
     port = request.json.get('port')
     if not port:
@@ -71,7 +71,7 @@ def restart():
 
     try:
         logger.info(f"Restarting serial connection on port {port}")
-        connection_manager.restart_serial(port)
+        connection_manager.restart_connection(port)
         return jsonify({'success': True})
     except Exception as e:
         logger.error(f"Failed to restart serial on port {port}: {str(e)}")

+ 36 - 4
dune_weaver_flask/modules/connection/connection_manager.py

@@ -146,6 +146,7 @@ def get_status_response() -> str:
                 return response
         except Exception as e:
             logger.error(f"Error getting status response: {e}")
+            return False
         time.sleep(1)
         
 def parse_machine_position(response: str):
@@ -169,7 +170,7 @@ def parse_machine_position(response: str):
     return None
 
 
-def send_grbl_coordinates(x, y, speed=600, timeout=5, home=False):
+def send_grbl_coordinates(x, y, speed=600, timeout=2, home=False):
     """
     Send a G-code command to FluidNC and wait for an 'ok' response.
     """
@@ -186,10 +187,9 @@ def send_grbl_coordinates(x, y, speed=600, timeout=5, home=False):
                 if response.lower() == "ok":
                     logger.debug("Command execution confirmed.")
                     return
-            logger.warning(f"No 'ok' received for X{x} Y{y}. Retrying in 1s...")
         except Exception as e:
-            logger.error(f"Error sending command: {e}")
-        time.sleep(1)
+            logger.debug(f"No 'ok' received for X{x} Y{y}, speed {speed}. Retrying in 1s...")
+        time.sleep(0.1)
         
 
 def get_machine_steps(timeout=10):
@@ -306,3 +306,35 @@ def get_machine_position(timeout=5):
 def update_machine_position():
     state.machine_x, state.machine_y = get_machine_position()
     state.save()
+
+def restart_connection():
+    """
+    Restart the connection. If a connection exists, close it and attempt to establish a new one.
+    It will try to connect via serial first (if available), otherwise it will fall back to websocket.
+    The new connection is saved to state.conn.
+    
+    Returns:
+        True if the connection was restarted successfully, False otherwise.
+    """
+    try:
+        if state.conn and state.conn.is_connected():
+            logger.info("Closing current connection...")
+            state.conn.close()
+    except Exception as e:
+        logger.error(f"Error while closing connection: {e}")
+
+    # Clear the connection reference.
+    state.conn = None
+
+    logger.info("Attempting to restart connection...")
+    try:
+        connect_device()  # This will set state.conn appropriately.
+        if state.conn and state.conn.is_connected():
+            logger.info("Connection restarted successfully.")
+            return True
+        else:
+            logger.error("Failed to restart connection.")
+            return False
+    except Exception as e:
+        logger.error(f"Error restarting connection: {e}")
+        return False

+ 9 - 0
dune_weaver_flask/modules/core/pattern_manager.py

@@ -188,8 +188,17 @@ def set_speed(new_speed):
 
 def run_theta_rho_file(file_path, schedule_hours=None):
     """Run a theta-rho file by sending data in optimized batches with tqdm ETA tracking."""
+    
+    # Check if connection is still valid, if not, restart
+    if not connection_manager.get_status_response():
+        logger.info('Cannot get status response, restarting connection')
+        connection_manager.restart_connection()
+    if not state.conn and not state.conn.is_connected():
+        logger.error('Connection not established')
+        return
     if not file_path:
         return
+    
     coordinates = parse_theta_rho_file(file_path)
     total_coordinates = len(coordinates)
 

+ 1 - 1
dune_weaver_flask/static/js/main.js

@@ -662,7 +662,7 @@ async function disconnectSerial() {
 
 async function restartSerial() {
     const port = document.getElementById('serial_ports').value;
-    const response = await fetch('/restart_serial', {
+    const response = await fetch('/restart_connection', {
         method: 'POST',
         headers: { 'Content-Type': 'application/json' },
         body: JSON.stringify({ port })