Skip to content

Commit ea5273a

Browse files
committed
代码重构、注释标准化与性能监控优化
1 parent 363dcb9 commit ea5273a

File tree

2 files changed

+63
-58
lines changed

2 files changed

+63
-58
lines changed
Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,47 @@
11
# -*- coding: utf-8 -*-
22
"""
3-
项目全局配置模块
4-
包含 CARLA 服务器连接设置、传感器参数以及 YOLO 模型路径
3+
Global Configuration for CARLA AutoVision Navigator.
54
"""
65

7-
# CARLA 服务器设置
6+
# ==============================================================================
7+
# -- CARLA Server Settings ----------------------------------------------------
8+
# ==============================================================================
89
CARLA_HOST = '127.0.0.1'
910
CARLA_PORT = 2000
1011
TIMEOUT = 10.0
1112

12-
# 传感器设置
13+
# ==============================================================================
14+
# -- Vehicle & Sensor Settings ------------------------------------------------
15+
# ==============================================================================
16+
VEHICLE_FILTER = 'vehicle.tesla.model3'
17+
SPAWN_POINT_INDEX = 1
18+
1319
CAMERA_WIDTH = 800
1420
CAMERA_HEIGHT = 600
1521
CAMERA_FOV = 90
1622

17-
# 自动驾驶主车设置
18-
VEHICLE_FILTER = 'vehicle.tesla.model3' # 默认生成特斯拉 Model 3
19-
SPAWN_POINT_INDEX = 1 # 默认出生点索引
20-
21-
# YOLO 模型配置 (预留)
23+
# ==============================================================================
24+
# -- YOLOv3 Model Settings ----------------------------------------------------
25+
# ==============================================================================
2226
MODEL_CFG = "models/yolov3.cfg"
2327
MODEL_WEIGHTS = "models/yolov3.weights"
2428
CONFIDENCE_THRESHOLD = 0.5
2529
NMS_THRESHOLD = 0.4
2630

27-
# 路径设置
28-
OUTPUT_PATH = "output/"
29-
30-
# --- 新增:车辆控制参数 (PID Controller) ---
31-
# 纵向控制 (速度)
32-
TARGET_SPEED = 20.0 # 目标时速 km/h
33-
K_P_SPEED = 1.0 # 比例系数
34-
K_I_SPEED = 0.0 # 积分系数
35-
K_D_SPEED = 0.1 # 微分系数
31+
# ==============================================================================
32+
# -- Control & Decision Parameters --------------------------------------------
33+
# ==============================================================================
34+
# Longitudinal Control (PID)
35+
TARGET_SPEED = 20.0
36+
K_P_SPEED = 1.0
37+
K_I_SPEED = 0.0
38+
K_D_SPEED = 0.1
3639

37-
# 横向控制 (转向 - 预留)
40+
# Lateral Control (PID)
3841
K_P_STEER = 0.5
3942
K_I_STEER = 0.0
40-
K_D_STEER = 0.0
43+
K_D_STEER = 0.05
4144

42-
# --- 决策层参数 (Decision Layer) ---
43-
# 触发紧急制动的检测框面积占比阈值 (0.0 到 1.0)
44-
# 如果目标框占画面高度的 30% 以上,说明距离非常近
45+
# Decision Making
4546
DANGER_THRESHOLD_HEIGHT = 0.35
46-
# 避障检测的关注类别
4747
OBSTACLE_CLASSES = ['car', 'truck', 'bus', 'person', 'bicycle', 'motorcycle']

src/CARLA_AutoVision_Navigator/src/carla_client.py

Lines changed: 39 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,58 +1,66 @@
11
# -*- coding: utf-8 -*-
2+
"""
3+
Main entry point for the CARLA AutoVision Navigator system.
4+
Integrated Perception, Decision, and Control loops.
5+
"""
6+
27
import carla
38
import sys
49
import os
510
import cv2
6-
import math
11+
import time
712
import random
813

9-
# 将根目录加入系统路径
1014
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
1115
import config
1216
from utils.geometry import get_speed, get_steer_angle
1317

1418

1519
class CarlaClient:
16-
"""负责管理与 CARLA 服务器的通信以及车辆实体的生命周期"""
20+
"""Manages CARLA server connection and vehicle actor lifecycle."""
1721

1822
def __init__(self):
23+
"""Initializes the client attributes."""
1924
self.client = None
2025
self.world = None
2126
self.blueprint_library = None
2227
self.ego_vehicle = None
2328

2429
def connect(self):
30+
"""Establishes connection to the CARLA simulator server."""
2531
try:
26-
print(f"正在尝试连接至 CARLA Server: {config.CARLA_HOST}:{config.CARLA_PORT}...")
32+
print(f"Connecting to CARLA Server: {config.CARLA_HOST}:{config.CARLA_PORT}")
2733
self.client = carla.Client(config.CARLA_HOST, config.CARLA_PORT)
2834
self.client.set_timeout(config.TIMEOUT)
2935
self.world = self.client.get_world()
3036
self.blueprint_library = self.world.get_blueprint_library()
31-
print("连接状态: 成功!")
37+
print("Connected successfully.")
3238
except Exception as e:
33-
print(f"连接状态: 失败! {e}")
39+
print(f"Failed to connect: {e}")
3440
sys.exit(1)
3541

3642
def spawn_ego_vehicle(self):
43+
"""Spawns the ego vehicle at the configured spawn point."""
3744
bp = self.blueprint_library.find(config.VEHICLE_FILTER)
3845
bp.set_attribute('role_name', 'ego')
3946
spawn_points = self.world.get_map().get_spawn_points()
4047
spawn_point = spawn_points[config.SPAWN_POINT_INDEX] if config.SPAWN_POINT_INDEX < len(
4148
spawn_points) else random.choice(spawn_points)
4249
self.ego_vehicle = self.world.spawn_actor(bp, spawn_point)
43-
print(f"车辆生成成功: ID[{self.ego_vehicle.id}]")
4450
return self.ego_vehicle
4551

4652
def cleanup(self):
53+
"""Destroys actors and cleans up the simulation environment."""
4754
if self.ego_vehicle and self.ego_vehicle.is_alive:
4855
self.ego_vehicle.destroy()
49-
print("已销毁主车,资源清理完毕。")
56+
print("Environment cleaned up.")
57+
5058

5159
if __name__ == "__main__":
5260
from sensor_manager import SensorManager
5361
from object_detector import YOLOv3Detector
5462
from pid_controller import PIDController
55-
from decision_maker import DecisionMaker # 引入决策器
63+
from decision_maker import DecisionMaker
5664

5765
connector = CarlaClient()
5866
sensors = None
@@ -64,56 +72,53 @@ def cleanup(self):
6472
sensors = SensorManager(connector.world, vehicle)
6573
sensors.attach_camera()
6674
detector = YOLOv3Detector()
67-
decision = DecisionMaker() # 初始化决策器
75+
decision = DecisionMaker()
6876

6977
speed_pid = PIDController(config.K_P_SPEED, config.K_I_SPEED, config.K_D_SPEED)
7078
steer_pid = PIDController(config.K_P_STEER, config.K_I_STEER, config.K_D_STEER)
7179

72-
print("全系统启动:感知+决策+控制。按下 'q' 键退出...")
80+
last_time = time.time()
81+
print("System fully integrated. Monitoring performance...")
82+
7383
while True:
74-
frame = sensors.get_current_frame()
75-
current_speed = get_speed(vehicle)
84+
# Performance Monitoring (FPS)
85+
start_time = time.time()
86+
fps = 1.0 / (start_time - last_time + 1e-6)
87+
last_time = start_time
7688

77-
# 1. 感知与检测
78-
detections = []
79-
if frame is not None:
80-
detections = detector.detect(frame)
81-
frame = detector.draw_labels(frame, detections)
89+
# 1. Perception
90+
frame = sensors.get_current_frame()
91+
detections = detector.detect(frame) if frame is not None else []
8292

83-
# 2. 决策层分析
84-
# 根据检测结果判断是否需要紧急刹车
93+
# 2. Decision
8594
is_emergency = decision.process_detections(detections, config.CAMERA_HEIGHT)
8695

87-
# 3. 控制信号计算
96+
# 3. Control
97+
current_speed = get_speed(vehicle)
8898
waypoint = carla_map.get_waypoint(vehicle.get_location()).next(8.0)[0]
8999
angle_error = get_steer_angle(vehicle, waypoint)
90100

91-
# 如果是紧急情况,目标速度设为 0
92101
target_v = 0.0 if is_emergency else config.TARGET_SPEED
93102
speed_signal = speed_pid.run_step(target_v, current_speed)
94103
steer_signal = steer_pid.run_step(0, -angle_error)
95104

96-
# 4. 应用控制
97105
control = vehicle.get_control()
98106
if is_emergency:
99-
control.throttle = 0.0
100-
control.brake = 1.0 # 全力刹车
101-
elif speed_signal >= 0:
102-
control.throttle = speed_signal
103-
control.brake = 0.0
107+
control.throttle, control.brake = 0.0, 1.0
104108
else:
105-
control.throttle = 0.0
106-
control.brake = abs(speed_signal)
109+
control.throttle = max(0, speed_signal)
110+
control.brake = abs(min(0, speed_signal))
107111

108112
control.steer = steer_signal
109113
vehicle.apply_control(control)
110114

111-
# 5. UI 显示
115+
# 4. Visualization & UI
112116
if frame is not None:
117+
frame = detector.draw_labels(frame, detections)
118+
cv2.putText(frame, f"FPS: {int(fps)}", (10, 90), 1, 1.5, (255, 0, 0), 2)
113119
if is_emergency:
114-
cv2.putText(frame, "EMERGENCY BRAKE!", (250, 300),
115-
cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 0, 255), 4)
116-
cv2.imshow("CARLA Full System Integration", frame)
120+
cv2.putText(frame, "AEB ACTIVE", (250, 300), 1, 3, (0, 0, 255), 4)
121+
cv2.imshow("CARLA AutoVision v1.0-RC", frame)
117122

118123
if cv2.waitKey(1) & 0xFF == ord('q'):
119124
break

0 commit comments

Comments
 (0)