tuanchris пре 3 месеци
родитељ
комит
fc36c9f79c
2 измењених фајлова са 19 додато и 19 уклоњено
  1. 5 5
      main.py
  2. 14 14
      modules/connection/connection_manager.py

+ 5 - 5
main.py

@@ -81,10 +81,10 @@ async def lifespan(app: FastAPI):
     logger.info(f"Initialized process pool with {process_pool_size} workers (detected {cpu_count} cores total)")
     logger.info(f"Initialized process pool with {process_pool_size} workers (detected {cpu_count} cores total)")
     
     
     try:
     try:
-        connection_manager.connect_device()
+        await connection_manager.connect_device()
     except Exception as e:
     except Exception as e:
         logger.warning(f"Failed to auto-connect to serial port: {str(e)}")
         logger.warning(f"Failed to auto-connect to serial port: {str(e)}")
-    
+
     # Check if auto_play mode is enabled and auto-play playlist (right after connection attempt)
     # Check if auto_play mode is enabled and auto-play playlist (right after connection attempt)
     if state.auto_play_enabled and state.auto_play_playlist:
     if state.auto_play_enabled and state.auto_play_playlist:
         logger.info(f"auto_play mode enabled, checking for connection before auto-playing playlist: {state.auto_play_playlist}")
         logger.info(f"auto_play mode enabled, checking for connection before auto-playing playlist: {state.auto_play_playlist}")
@@ -389,13 +389,13 @@ async def list_ports():
 async def connect(request: ConnectRequest):
 async def connect(request: ConnectRequest):
     if not request.port:
     if not request.port:
         state.conn = connection_manager.WebSocketConnection('ws://fluidnc.local:81')
         state.conn = connection_manager.WebSocketConnection('ws://fluidnc.local:81')
-        connection_manager.device_init()
+        await connection_manager.device_init()
         logger.info('Successfully connected to websocket ws://fluidnc.local:81')
         logger.info('Successfully connected to websocket ws://fluidnc.local:81')
         return {"success": True}
         return {"success": True}
 
 
     try:
     try:
         state.conn = connection_manager.SerialConnection(request.port)
         state.conn = connection_manager.SerialConnection(request.port)
-        connection_manager.device_init()
+        await connection_manager.device_init()
         logger.info(f'Successfully connected to serial port {request.port}')
         logger.info(f'Successfully connected to serial port {request.port}')
         return {"success": True}
         return {"success": True}
     except Exception as e:
     except Exception as e:
@@ -420,7 +420,7 @@ async def restart(request: ConnectRequest):
 
 
     try:
     try:
         logger.info(f"Restarting connection on port {request.port}")
         logger.info(f"Restarting connection on port {request.port}")
-        connection_manager.restart_connection()
+        await connection_manager.restart_connection()
         return {"success": True}
         return {"success": True}
     except Exception as e:
     except Exception as e:
         logger.error(f"Failed to restart serial on port {request.port}: {str(e)}")
         logger.error(f"Failed to restart serial on port {request.port}: {str(e)}")

+ 14 - 14
modules/connection/connection_manager.py

@@ -163,11 +163,11 @@ def list_serial_ports():
     logger.debug(f"Available serial ports: {available_ports}")
     logger.debug(f"Available serial ports: {available_ports}")
     return available_ports
     return available_ports
 
 
-def device_init(homing=True):
+async def device_init(homing=True):
     try:
     try:
-        if get_machine_steps():
+        if await asyncio.to_thread(get_machine_steps):
             logger.info(f"x_steps_per_mm: {state.x_steps_per_mm}, y_steps_per_mm: {state.y_steps_per_mm}, gear_ratio: {state.gear_ratio}")
             logger.info(f"x_steps_per_mm: {state.x_steps_per_mm}, y_steps_per_mm: {state.y_steps_per_mm}, gear_ratio: {state.gear_ratio}")
-        else: 
+        else:
             logger.fatal("Failed to get machine steps")
             logger.fatal("Failed to get machine steps")
             state.conn.close()
             state.conn.close()
             return False
             return False
@@ -176,12 +176,12 @@ def device_init(homing=True):
         state.conn.close()
         state.conn.close()
         return False
         return False
 
 
-    machine_x, machine_y = get_machine_position()
+    machine_x, machine_y = await asyncio.to_thread(get_machine_position)
     if machine_x != state.machine_x or machine_y != state.machine_y:
     if machine_x != state.machine_x or machine_y != state.machine_y:
         logger.info(f'x, y; {machine_x}, {machine_y}')
         logger.info(f'x, y; {machine_x}, {machine_y}')
         logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
         logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
         if homing:
         if homing:
-            success = home()
+            success = await asyncio.to_thread(home)
             if not success:
             if not success:
                 logger.error("Homing failed during device initialization")
                 logger.error("Homing failed during device initialization")
     else:
     else:
@@ -190,15 +190,15 @@ def device_init(homing=True):
         logger.info(f'x, y; {machine_x}, {machine_y}')
         logger.info(f'x, y; {machine_x}, {machine_y}')
         logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
         logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
 
 
-    time.sleep(2)  # Allow time for the connection to establish
+    await asyncio.sleep(2)  # Allow time for the connection to establish
 
 
 
 
-def connect_device(homing=True):
+async def connect_device(homing=True):
     if state.wled_ip:
     if state.wled_ip:
         state.led_controller = LEDController(state.wled_ip)
         state.led_controller = LEDController(state.wled_ip)
         effect_loading(state.led_controller)
         effect_loading(state.led_controller)
-        
-    ports = list_serial_ports()
+
+    ports = await asyncio.to_thread(list_serial_ports)
 
 
     if state.port and state.port in ports:
     if state.port and state.port in ports:
         state.conn = SerialConnection(state.port)
         state.conn = SerialConnection(state.port)
@@ -208,8 +208,8 @@ def connect_device(homing=True):
         logger.error("Auto connect failed.")
         logger.error("Auto connect failed.")
         # state.conn = WebSocketConnection('ws://fluidnc.local:81')
         # state.conn = WebSocketConnection('ws://fluidnc.local:81')
     if (state.conn.is_connected() if state.conn else False):
     if (state.conn.is_connected() if state.conn else False):
-        device_init(homing)
-        
+        await device_init(homing)
+
     if state.led_controller:
     if state.led_controller:
         effect_connected(state.led_controller)
         effect_connected(state.led_controller)
 
 
@@ -588,12 +588,12 @@ async def update_machine_position():
             except Exception as e:
             except Exception as e:
                 logger.error(f"Error updating machine position: {e}")
                 logger.error(f"Error updating machine position: {e}")
 
 
-def restart_connection(homing=False):
+async def restart_connection(homing=False):
     """
     """
     Restart the connection. If a connection exists, close it and attempt to establish a new one.
     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.
     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.
     The new connection is saved to state.conn.
-    
+
     Returns:
     Returns:
         True if the connection was restarted successfully, False otherwise.
         True if the connection was restarted successfully, False otherwise.
     """
     """
@@ -609,7 +609,7 @@ def restart_connection(homing=False):
 
 
     logger.info("Attempting to restart connection...")
     logger.info("Attempting to restart connection...")
     try:
     try:
-        connect_device(homing)  # This will set state.conn appropriately.
+        await connect_device(homing)  # This will set state.conn appropriately.
         if (state.conn.is_connected() if state.conn else False):
         if (state.conn.is_connected() if state.conn else False):
             logger.info("Connection restarted successfully.")
             logger.info("Connection restarted successfully.")
             return True
             return True