# Test DirectML specifically
if 'DmlExecutionProvider' in available_providers:
logging.info("DirectML is available - good for AMD GPUs")
else:
logging.warning("DirectML not available - falling back to CPU")
return available_providers
except Exception as e:
logging.error(f"Error checking ONNX providers: {e}")
return []
def validate_model_file(model_path):
"""Validate that the ONNX model file exists and is readable."""
import os
try:
if not os.path.exists(model_path):
logging.error(f"Model file not found: {model_path}")
return False
code
if not os.access(model_path, os.R_OK):
logging.error(f"Model file not readable: {model_path}")
return False
file_size = os.path.getsize(model_path)
if file_size < 1024: # Less than 1KB is suspicious
logging.error(f"Model file suspiciously small: {model_path} ({file_size} bytes)")
return False
logging.info(f"Model file validated: {model_path} ({file_size} bytes)")
return True
except Exception as e:
logging.error(f"Error validating model file {model_path}: {e}")
return False
def optimize_detection_settings():
"""Return optimized detection settings for AMD systems."""
return {
'confidence': 0.25, # Lower threshold for better detection
'fov_radius': 200, # Larger FOV for better coverage
'nms_threshold': 0.4, # Slightly higher for less aggressive NMS
'max_detections': 50, # More detections allowed
'frame_skip': 1, # Process every frame
'input_size': 640, # Standard YOLO input size
}
# Log system information
import platform
import sys
logging.info(f"System: {platform.system()} {platform.release()}")
logging.info(f"Python: {sys.version}")
try:
import torch
logging.info(f"PyTorch: {torch.__version__}")
except:
logging.warning("PyTorch not available")
try:
import onnxruntime as ort
logging.info(f"ONNX Runtime: {ort.__version__}")
except:
logging.error("ONNX Runtime not available")
Usage example and initialization
if name == "main":
# Setup logging
setup_logging()
code
# Test ONNX providers
test_onnx_providers()
# Validate model files
model_paths = [
"models/BestMain.onnx",
# Add more model paths as needed
]
for model_path in model_paths:
validate_model_file(model_path)
# Example usage with optimized settings
optimized_settings = optimize_detection_settings()
logging.info(f"Using optimized settings: {optimized_settings}")
# Initialize detection system
# detection_thread = DetectionThread(optimized_settings)
# detection_thread.start()
class AimAssistThread(QtCore.QThread):
aim_active_signal = QtCore.pyqtSignal(bool)
code
Thanks for sharing your detailed code! The overall structure looks solid, but since you mentioned it doesn't detect anything on AMD GPUs on Windows, and that it’s designed to use ONNX Runtime with DirectML provider (which is recommended for AMD GPUs), I will focus on the GPU detection issues and provider setup.
Likely Reasons for No Detection / No GPU Usage:
DmlExecutionProvider is not correctly applied to ONNX sessions
Your _load_models() builds a providers list like:
python
providers = []
if 'DmlExecutionProvider' in ort.get_available_providers():
providers.append(('DmlExecutionProvider', {...}))
providers.append(('CPUExecutionProvider', {...}))
However, ExecutionProviders should be passed as a list of strings or a list of tuples with config dictionaries, but when you provide tuples with config dictionaries, it must be a list of either strings or dictionaries describing providers. Currently, you mix and append tuples with dicts that might not be recognized properly.
ONNXRuntime's DmlExecutionProvider config options might be ignored
The options you give in providers.append(('DmlExecutionProvider', {...})) may not be applied as you expect, since DmlExecutionProvider options in ONNX Runtime are limited. You can try first to just specify providers by name: ['DmlExecutionProvider', 'CPUExecutionProvider'], without options.
You do not verify actual provider in use after session creation accurately. session.get_providers() returns the list of active provider names (strings). Your code:
python
providers_used = [provider.get_provider_name() for provider in session.get_providers()]
will fail because session.get_providers() returns strings, not objects.
Model path and loading issues
Your model name is "models/yolo11n.onnx" inside DetectionThread, but in the usage example, you validate "models/BestMain.onnx".
If the loaded model is missing or corrupted, no detection will happen.
Suggested Fixes to Try
1. Fix how InferenceSession providers are specified
Simplify provider spec to just strings (the usual):
python
providers = []
available_providers = ort.get_available_providers()
if 'DmlExecutionProvider' in available_providers:
providers.append('DmlExecutionProvider')
logging.info("Using DirectML execution provider")
else:
logging.warning("DmlExecutionProvider not available, using CPUExecutionProvider")
providers.append('CPUExecutionProvider') # fallback
session = ort.InferenceSession(onnx_path, sess_options, providers=providers)
Remove the dict config for providers, because for DML, ONNX Runtime expects just provider names.
2. Correct logging of active providers:
Change:
python
providers_used = [provider.get_provider_name() for provider in session.get_providers()]
to:
python
providers_used = session.get_providers() # This is a list of strings
logging.info(f"Loaded ONNX model: {onnx_path} (imgsz={imgsz}) using providers: {providers_used}")
3. Confirm the model is correctly loaded
Before starting inference, call your validate_model_file() on the exact model path you are actually loading (e.g., "models/yolo11n.onnx"). If that is missing or corrupted, nothing will detect anything.
4. Confirm DirectML is available on your machine
Run the helper function test_onnx_providers() from your script and check logs:
Confirm DirectML is working with a minimal sample script (outside your app).
5. For troubleshooting, force CPUExecutionProvider only
Try forcing CPU provider only first as a baseline, and confirm detections happen (potentially slowing down but it confirms the model and pre/postprocessing works):
If detection works, problem is likely with GPU provider configuration.
6. Small housekeeping for consistent usage:
Import and define ort as import onnxruntime as ort at the top
Make sure logging, cv2, torch, numpy, etc. are imported
Your predict() converts boxes etc. to PyTorch tensors but torch is optional; consider using numpy if you want lighter dependency.
Minimal example of fixed _load_models snippet:
python
def _load_models(self, models_config):
for model_path, imgsz in models_config:
try:
onnx_path = model_path if model_path.endswith(".onnx") else model_path.replace('.pt', '.onnx')
if not os.path.isfile(onnx_path):
logging.error(f"Model file not found: {onnx_path}")
continue
providers = []
available_providers = ort.get_available_providers()
if 'DmlExecutionProvider' in available_providers:
providers.append('DmlExecutionProvider')
logging.info(f"DmlExecutionProvider available for model {onnx_path}")
providers.append('CPUExecutionProvider') # fallback provider
sess_options = ort.SessionOptions()
sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
session = ort.InferenceSession(onnx_path, sess_options, providers=providers)
input_name = session.get_inputs()[0].name
input_shape = session.get_inputs()[0].shape
providers_used = session.get_providers()
logging.info(f"Loaded model '{onnx_path}' with providers: {providers_used}")
self.models.append({
'session': session,
'input_name': input_name,
'imgsz': imgsz,
'input_shape': input_shape
})
except Exception as e:
logging.error(f"Failed to load model {model_path}: {e}")
Summary:
Pass providers as list of strings without config dicts in InferenceSession.
Fix logging of active providers by directly using session.get_providers().
Validate model file path and existence carefully.
Test which providers are available on your system.
Try CPU-only mode as a baseline to isolate GPU issues.
If after these fixes the detection still doesn't work or doesn't find objects:
Double-check your models — try a known good ONNX model.
Double-check preprocessing/postprocessing shapes and normalization.
Add debug logs inside preprocessing / postprocessing to verify inputs/outputs.
Try a very simple ONNX detection example outside your application to verify the environmental setup.
If you want, I can also provide a minimal standalone example ONNX runtime inference snippet using DmlExecutionProvider on AMD Windows to verify your environment — just say the word!
Not yet included in a published release.
def __init__(self, settings):
super().__init__()
self.settings = settings
self.running = False
self.frame_lock = threading.Lock()
# BitBlt setup variables
self.user32 = ctypes.windll.user32
self.gdi32 = ctypes.windll.gdi32
self.dc = None
self.memdc = None
self.bitmap = None
self.bitmapinfo = None
# Enhanced tracker settings
self.tracker = Sort(max_age=30, min_hits=2, iou_threshold=0.3)
self.frame_skip = 0
self.last_detection_time = 0
# Screen info
self.screen_width = 0
self.screen_height = 0
self.center_x = 0
self.center_y = 0
# Model configuration
model_paths = [
("models/yolo11n.onnx", 256), # Increased input size for better detection
]
# Enhanced class names for better detection
class_names = {
0: 'person',
1: 'bicycle',
2: 'car',
3: 'motorcycle',
4: 'airplane',
5: 'bus',
6: 'train',
7: 'truck'
}
# ONNX + DirectML model ensemble singleton instance
self.yolo_ensemble = YOLOEnsemble.get_instance(model_paths, class_names)
def setup_bitblt(self):
"""Enhanced BitBlt setup with better error handling."""
try:
hwnd = self.user32.GetDesktopWindow()
self.dc = self.user32.GetDC(hwnd)
if not self.dc:
raise Exception("Failed to get desktop DC")
self.memdc = self.gdi32.CreateCompatibleDC(self.dc)
if not self.memdc:
raise Exception("Failed to create compatible DC")
class BITMAPINFOHEADER(ctypes.Structure):
_fields_ = [
("biSize", ctypes.c_uint32),
("biWidth", ctypes.c_int),
("biHeight", ctypes.c_int),
("biPlanes", ctypes.c_short),
("biBitCount", ctypes.c_short),
("biCompression", ctypes.c_uint32),
("biSizeImage", ctypes.c_uint32),
("biXPelsPerMeter", ctypes.c_int),
("biYPelsPerMeter", ctypes.c_int),
("biClrUsed", ctypes.c_uint32),
("biClrImportant", ctypes.c_uint32)
]
self.bitmapinfo = BITMAPINFOHEADER()
self.bitmapinfo.biSize = ctypes.sizeof(BITMAPINFOHEADER)
self.bitmapinfo.biPlanes = 1
self.bitmapinfo.biBitCount = 32
self.bitmapinfo.biCompression = 0
logging.info("BitBlt setup completed successfully")
return True
except Exception as e:
logging.error(f"BitBlt setup failed: {e}")
self.cleanup_bitblt()
return False
def capture_screen_region(self, x, y, width, height):
"""Enhanced screen capture with better error handling."""
try:
# Validate input parameters
if width <= 0 or height <= 0:
logging.warning(f"Invalid capture dimensions: {width}x{height}")
return None
self.bitmapinfo.biWidth = width
self.bitmapinfo.biHeight = -height # top-down bitmap
self.bitmapinfo.biSizeImage = width * height * 4
# Create bitmap
self.bitmap = self.gdi32.CreateCompatibleBitmap(self.dc, width, height)
if not self.bitmap:
raise Exception("Failed to create compatible bitmap")
# Select bitmap into memory DC
old_bitmap = self.gdi32.SelectObject(self.memdc, self.bitmap)
if not old_bitmap:
raise Exception("Failed to select bitmap into memory DC")
# Perform BitBlt operation
result = self.gdi32.BitBlt(
self.memdc, 0, 0, width, height,
self.dc, x, y, 0x00CC0020 # SRCCOPY
)
if not result:
raise Exception("BitBlt operation failed")
# Get bitmap data
buf_size = width * height * 4
buffer = (ctypes.c_byte * buf_size)()
result = self.gdi32.GetDIBits(
self.memdc, self.bitmap, 0, height, buffer,
ctypes.byref(self.bitmapinfo), 0
)
if not result:
raise Exception("GetDIBits failed")
# Convert to numpy array
array = np.frombuffer(buffer, dtype=np.uint8)
array = array.reshape(height, width, 4)
# Clean up bitmap
self.gdi32.DeleteObject(self.bitmap)
self.bitmap = None
return array
except Exception as e:
logging.error(f"BitBlt capture failed: {e}")
if self.bitmap:
self.gdi32.DeleteObject(self.bitmap)
self.bitmap = None
return None
def cleanup_bitblt(self):
"""Enhanced cleanup with better error handling."""
try:
if self.bitmap:
self.gdi32.DeleteObject(self.bitmap)
self.bitmap = None
if self.memdc:
self.gdi32.DeleteDC(self.memdc)
self.memdc = None
if self.dc:
self.user32.ReleaseDC(None, self.dc)
self.dc = None
except Exception as e:
logging.error(f"BitBlt cleanup failed: {e}")
def fast_nms(self, boxes, scores, iou_threshold=0.25):
"""Enhanced NMS implementation."""
if len(boxes) == 0:
return []
boxes = np.asarray(boxes, dtype=np.float32)
scores = np.asarray(scores, dtype=np.float32)
# Remove invalid boxes
valid_mask = (boxes[:, 2] > boxes[:, 0]) & (boxes[:, 3] > boxes[:, 1])
boxes = boxes[valid_mask]
scores = scores[valid_mask]
if len(boxes) == 0:
return []
indices = np.argsort(scores)[::-1]
keep = []
while indices.size > 0:
current = indices[0]
keep.append(current)
if indices.size == 1:
break
remaining = indices[1:]
current_box = boxes[current]
remaining_boxes = boxes[remaining]
# Vectorized IoU calculation
x1 = np.maximum(current_box[0], remaining_boxes[:, 0])
y1 = np.maximum(current_box[1], remaining_boxes[:, 1])
x2 = np.minimum(current_box[2], remaining_boxes[:, 2])
y2 = np.minimum(current_box[3], remaining_boxes[:, 3])
inter_area = np.maximum(0, x2 - x1) * np.maximum(0, y2 - y1)
current_area = (current_box[2] - current_box[0]) * (current_box[3] - current_box[1])
rem_area = (remaining_boxes[:, 2] - remaining_boxes[:, 0]) * (remaining_boxes[:, 3] - remaining_boxes[:, 1])
union = current_area + rem_area - inter_area
iou = inter_area / np.maximum(union, 1e-8)
indices = remaining[iou <= iou_threshold]
return keep
def transform_coordinates(self, boxes, crop_x, crop_y, scale_x, scale_y):
"""Enhanced coordinate transformation."""
transformed = []
for box in boxes:
x1, y1, x2, y2 = box
x1_screen = int(x1 * scale_x + crop_x)
y1_screen = int(y1 * scale_y + crop_y)
x2_screen = int(x2 * scale_x + crop_x)
y2_screen = int(y2 * scale_y + crop_y)
# Ensure valid coordinates
x1_screen = max(0, min(x1_screen, self.screen_width - 1))
y1_screen = max(0, min(y1_screen, self.screen_height - 1))
x2_screen = max(0, min(x2_screen, self.screen_width))
y2_screen = max(0, min(y2_screen, self.screen_height))
if x2_screen > x1_screen and y2_screen > y1_screen:
transformed.append((x1_screen, y1_screen, x2_screen, y2_screen))
return transformed
def run(self):
"""Enhanced main detection loop."""
self.running = True
if not self.yolo_ensemble.models:
logging.error("No models loaded - detection cannot start")
return
if not self.setup_bitblt():
logging.error("BitBlt setup failed - detection cannot start")
return
self.screen_width = self.user32.GetSystemMetrics(0)
self.screen_height = self.user32.GetSystemMetrics(1)
self.center_x = self.screen_width >> 1
self.center_y = self.screen_height >> 1
logging.info(f"Detection started on {self.screen_width}x{self.screen_height} screen")
last_time = time.perf_counter()
frame_count = 0
detection_count = 0
try:
while self.running:
current_time = time.perf_counter()
frame_count += 1
# Get FOV settings
fov_radius = clamp(
self.settings.get('fov_radius', 200),
100,
min(self.screen_width, self.screen_height) >> 1
)
# Calculate crop region
crop_x = max(self.center_x - fov_radius, 0)
crop_y = max(self.center_y - fov_radius, 0)
crop_width = min(fov_radius * 2, self.screen_width - crop_x)
crop_height = min(fov_radius * 2, self.screen_height - crop_y)
if crop_width < 200 or crop_height < 200:
logging.warning(f"Crop region too small: {crop_width}x{crop_height}")
continue
# Capture screen region
frame = self.capture_screen_region(crop_x, crop_y, crop_width, crop_height)
if frame is None or frame.size == 0:
continue
# Prepare frame for detection
frame = np.ascontiguousarray(frame)
frame = cv2.cvtColor(frame, cv2.COLOR_BGRA2RGB)
# Get confidence threshold
conf_thres = clamp(self.settings.get('confidence', 0.3), 0.1, 0.9)
# Run detection
all_results = self.yolo_ensemble.predict(frame, conf_thres=conf_thres)
# Process detections
detections = []
for results in all_results:
if not hasattr(results, 'boxes') or not results.boxes.xyxy.shape[0]:
continue
boxes = results.boxes.xyxy.cpu().numpy()
confs = results.boxes.conf.cpu().numpy()
classes = results.boxes.cls.cpu().numpy()
scale_x = getattr(results, 'scale_x', crop_width / 640)
scale_y = getattr(results, 'scale_y', crop_height / 640)
screen_boxes = self.transform_coordinates(boxes, crop_x, crop_y, scale_x, scale_y)
for i, (box, conf, cls) in enumerate(zip(screen_boxes, confs, classes)):
if conf < conf_thres:
continue
x1_s, y1_s, x2_s, y2_s = box
if x1_s >= x2_s or y1_s >= y2_s:
continue
class_id = int(cls)
class_name = self.yolo_ensemble.names.get(class_id, f"class_{class_id}")
# Distance check from center for FOV radius
det_center_x = (x1_s + x2_s) >> 1
det_center_y = (y1_s + y2_s) >> 1
dx = det_center_x - self.center_x
dy = det_center_y - self.center_y
dist_sq = dx*dx + dy*dy
if dist_sq <= fov_radius * fov_radius:
detections.append((x1_s, y1_s, x2_s, y2_s, float(conf), class_name))
# Sort by confidence and apply NMS
detections.sort(key=lambda x: x[4], reverse=True)
if detections:
boxes = [(d[0], d[1], d[2], d[3]) for d in detections]
confidences = [d[4] for d in detections]
labels = [d[5] for d in detections]
# Apply NMS
selected_indices = self.fast_nms(boxes, confidences, iou_threshold=0.4)
boxes = [boxes[i] for i in selected_indices]
labels = [labels[i] for i in selected_indices]
confidences = [confidences[i] for i in selected_indices]
detection_count += len(boxes)
else:
boxes, labels, confidences = [], [], []
# Tracking
dets_for_sort = np.array([[*box, conf] for box, conf in zip(boxes, confidences)]) if boxes else np.empty((0,5))
tracked_objects = self.tracker.update(dets_for_sort)
tracked_boxes = []
track_ids = []
for obj in tracked_objects:
x1t, y1t, x2t, y2t, track_id = obj
x1t, y1t, x2t, y2t = map(int, (x1t, y1t, x2t, y2t))
# Validate tracked box
if (x1t < x2t and y1t < y2t and
0 <= x1t < self.screen_width and 0 <= y1t < self.screen_height and
x2t <= self.screen_width and y2t <= self.screen_height):
tracked_boxes.append((x1t, y1t, x2t, y2t))
track_ids.append(int(track_id))
# Emit detection signal
self.detection_signal.emit(tracked_boxes, labels, confidences, labels, track_ids)
# Performance logging
self.frame_skip += 1
if self.frame_skip >= 100:
elapsed = current_time - last_time
fps = self.frame_skip / elapsed if elapsed > 0 else 0
avg_detections = detection_count / self.frame_skip if self.frame_skip > 0 else 0
logging.info(f"Performance - FPS: {fps:.1f}, Avg Detections: {avg_detections:.1f}, Total Frames: {frame_count}")
self.frame_skip = 0
detection_count = 0
last_time = current_time
# Small delay to prevent excessive CPU usage
time.sleep(0.001)
except Exception as e:
logging.error(f"Detection error: {e}")
import traceback
traceback.print_exc()
finally:
self.cleanup_bitblt()
logging.info("Detection stopped")
def stop(self):
"""Stop the detection thread."""
self.running = False
self.cleanup_bitblt()
logging.info("Detection stop requested")
def __init__(self, settings, get_targets_func, get_fov_center_func):
super().__init__()
self.settings = settings
self.get_targets = get_targets_func
self.get_fov_center = get_fov_center_func
self.running = False
self.aim_active = False
self.lock = threading.Lock()
# Tracking settings
self.locked_track_id = None
self.target_acquired = False
# Performance settings
self.aim_fps = 1000 # Increased for faster response
self.frame_time = 1.0 / self.aim_fps
self.last_aim_time = 0
# Anti-recoil settings
self.recoil_control = True
self.recoil_strength = 1.3 # Adjust as needed
self.recoil_recovery = 0.90 # Recovery rate
self.current_recoil = 0
# Aim settings
self.aim_smoothing = 0.73 # Lower = faster aim
self.max_speed = 8 # Increased max speed
self.deadzone = 1.0 # Reduced deadzone
# Toggle controls
self.toggle_key = 'p'
self.aim_toggled_on = False
self.last_toggle_time = 0
self.toggle_cooldown = 0.15 # Faster toggle response
def calculate_aim_point(self, x1, y1, x2, y2):
"""Fast aim point calculation with height-based targeting"""
center_x = (x1 + x2) >> 1
height = y2 - y1
# Aim higher for distant targets (smaller height)
aim_height = 0.2 if height < 100 else 0.3
center_y = y1 + int(height * aim_height) # Aim at upper chest/head
return center_x, center_y
def apply_anti_recoil(self, dy):
"""Apply dynamic anti-recoil compensation"""
if not self.recoil_control:
return dy
if dy > 0: # Only apply when aiming down
self.current_recoil = min(self.current_recoil + 0.2, self.recoil_strength)
else:
self.current_recoil *= self.recoil_recovery
return dy - (self.current_recoil * 2.0)
def calculate_movement(self, target_pos, fc_x, fc_y):
"""Optimized movement calculation with anti-recoil"""
if not target_pos:
return 0, 0
dx = target_pos[0] - fc_x
dy = target_pos[1] - fc_y
# Apply deadzone
if abs(dx) <= self.deadzone and abs(dy) <= self.deadzone:
return 0, 0
# Calculate base movement
move_x = dx * self.aim_smoothing
move_y = dy * self.aim_smoothing
# Apply anti-recoil to vertical movement
move_y = self.apply_anti_recoil(move_y)
# Speed limiting
move_x = clamp(move_x, -self.max_speed, self.max_speed)
move_y = clamp(move_y, -self.max_speed, self.max_speed)
return int(move_x), int(move_y)
def get_best_target(self, targets, fc_x, fc_y, fov_radius):
"""Fast target selection with priority system"""
if not targets:
return None, None
best_target = None
best_score = float('inf')
fov_radius_sq = fov_radius * fov_radius
for target in targets:
if len(target) < 4:
continue
x1, y1, x2, y2 = target[:4]
track_id = target[5] if len(target) > 5 else None
# Fast center calculation
center_x, center_y = self.calculate_aim_point(x1, y1, x2, y2)
# Quick distance check
dx = center_x - fc_x
dy = center_y - fc_y
dist_sq = dx*dx + dy*dy
if dist_sq >= fov_radius_sq:
continue
# Prioritize current target
if track_id == self.locked_track_id:
return (center_x, center_y), target
# Score based on distance and size
target_size = (x2-x1) * (y2-y1)
score = dist_sq / (target_size + 1)
if score < best_score:
best_score = score
best_target = ((center_x, center_y), target)
return best_target if best_target else (None, None)
def run(self):
"""High-performance aim assist loop"""
self.running = True
sleep_time = 0.0001 # Minimal sleep
while self.running:
try:
current_time = time.perf_counter()
if current_time - self.last_aim_time < self.frame_time:
time.sleep(sleep_time)
continue
self.last_aim_time = current_time
# Fast toggle check
if keyboard.is_pressed(self.toggle_key):
if current_time - self.last_toggle_time > self.toggle_cooldown:
self.aim_toggled_on = not self.aim_toggled_on
self.last_toggle_time = current_time
aim_active = False
if self.aim_toggled_on and self.settings.get('aim_enabled', True):
with self.lock:
targets = self.get_targets()
fov_center = self.get_fov_center()
if targets and fov_center:
fc_x, fc_y = (fov_center.x(), fov_center.y()) if hasattr(fov_center, "x") else fov_center
fov_radius = self.settings.get('fov_radius', 200)
target_pos, target_data = self.get_best_target(targets, fc_x, fc_y, fov_radius)
if target_pos:
if not self.target_acquired:
self.target_acquired = True
if target_data and len(target_data) > 5:
self.locked_track_id = target_data[5]
mdx, mdy = self.calculate_movement(target_pos, fc_x, fc_y)
if mdx != 0 or mdy != 0:
move_mouse_relative(mdx, mdy)
aim_active = True
else:
self.target_acquired = False
self.locked_track_id = None
self.current_recoil = 0
if aim_active != self.aim_active:
self.aim_active = aim_active
self.aim_active_signal.emit(self.aim_active)
except Exception as e:
logging.error(f"AimAssist error: {e}")
time.sleep(sleep_time)
def stop(self):
"""Clean shutdown"""
self.running = False
self.target_acquired = False
self.locked_track_id = None
self.current_recoil = 0