ROS1从入门到精通 17:多机器人系统 - 协作与通信
·
ROS1从入门到精通:第17篇 多机器人系统 - 协作与通信
引言
在现代机器人应用中,单个机器人的能力往往是有限的。通过多个机器人的协作,可以完成更复杂的任务、提高系统的鲁棒性和效率。多机器人系统(Multi-Robot Systems, MRS)在搜索救援、环境监测、物流配送、协同制造等领域有着广泛的应用前景。
本文将深入探讨ROS1中的多机器人系统实现,包括通信架构、协调机制、任务分配、编队控制、分布式SLAM等核心技术。通过理论讲解和实践代码,帮助读者掌握多机器人系统的设计和开发方法。
一、多机器人系统架构
1.1 系统架构模式
多机器人系统的架构模式主要包括:
1.1.1 集中式架构
- 中央控制器:所有决策由中央节点完成
- 优点:全局最优、易于协调
- 缺点:单点故障、可扩展性差、通信瓶颈
1.1.2 分布式架构
- 自主决策:每个机器人独立决策
- 优点:鲁棒性强、可扩展性好
- 缺点:难以达到全局最优、协调复杂
1.1.3 混合架构
- 分层控制:结合集中式和分布式的优点
- 局部自主:底层分布式控制
- 全局协调:高层集中式规划
1.2 ROS多机器人命名空间
在ROS中,使用命名空间来区分不同的机器人:
# multi_robot.launch
<launch>
<!-- Robot 1 -->
<group ns="robot1">
<param name="robot_id" value="1"/>
<param name="robot_name" value="robot1"/>
<!-- 加载机器人模型 -->
<param name="robot_description"
command="$(find xacro)/xacro '$(find robot_description)/urdf/robot.xacro'"/>
<!-- 启动机器人节点 -->
<node name="robot_controller" pkg="robot_control" type="controller_node">
<remap from="/cmd_vel" to="cmd_vel"/>
<remap from="/odom" to="odom"/>
</node>
</group>
<!-- Robot 2 -->
<group ns="robot2">
<param name="robot_id" value="2"/>
<param name="robot_name" value="robot2"/>
<param name="robot_description"
command="$(find xacro)/xacro '$(find robot_description)/urdf/robot.xacro'"/>
<node name="robot_controller" pkg="robot_control" type="controller_node">
<remap from="/cmd_vel" to="cmd_vel"/>
<remap from="/odom" to="odom"/>
</node>
</group>
<!-- 多机器人协调器 -->
<node name="multi_robot_coordinator" pkg="multi_robot" type="coordinator_node">
<param name="num_robots" value="2"/>
<param name="robot_namespaces" value="[robot1, robot2]"/>
</node>
</launch>
1.3 通信拓扑
多机器人系统的通信拓扑结构:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import rospy
import networkx as nx
import numpy as np
from std_msgs.msg import String, Header
from geometry_msgs.msg import PoseStamped
from multi_robot_msgs.msg import RobotStatus, TeamStatus
class CommunicationTopology:
"""多机器人通信拓扑管理"""
def __init__(self):
rospy.init_node('communication_topology', anonymous=True)
# 机器人配置
self.num_robots = rospy.get_param('~num_robots', 3)
self.robot_id = rospy.get_param('~robot_id', 0)
self.comm_range = rospy.get_param('~comm_range', 10.0)
# 通信图
self.comm_graph = nx.Graph()
self.robot_positions = {}
self.neighbor_list = []
# 通信模式
self.topology_type = rospy.get_param('~topology_type', 'dynamic')
# 初始化通信图
self.init_communication_graph()
# ROS通信
self.status_pub = rospy.Publisher(
'/team/status', TeamStatus, queue_size=10
)
self.neighbor_pub = rospy.Publisher(
f'/robot{self.robot_id}/neighbors', String, queue_size=10
)
# 订阅其他机器人的状态
self.robot_status_subs = []
for i in range(self.num_robots):
sub = rospy.Subscriber(
f'/robot{i}/status', RobotStatus,
self.robot_status_callback, callback_args=i
)
self.robot_status_subs.append(sub)
# 定时更新通信拓扑
self.update_timer = rospy.Timer(
rospy.Duration(1.0), self.update_topology
)
rospy.loginfo(f"Communication topology initialized for robot {self.robot_id}")
def init_communication_graph(self):
"""初始化通信图"""
# 添加所有机器人节点
for i in range(self.num_robots):
self.comm_graph.add_node(i, pos=(0, 0))
self.robot_positions[i] = np.array([0, 0])
if self.topology_type == 'full':
# 全连接拓扑
self.create_full_topology()
elif self.topology_type == 'ring':
# 环形拓扑
self.create_ring_topology()
elif self.topology_type == 'star':
# 星形拓扑
self.create_star_topology()
elif self.topology_type == 'dynamic':
# 动态拓扑(基于距离)
pass
else:
rospy.logwarn(f"Unknown topology type: {self.topology_type}")
def create_full_topology(self):
"""创建全连接拓扑"""
for i in range(self.num_robots):
for j in range(i + 1, self.num_robots):
self.comm_graph.add_edge(i, j, weight=1.0)
def create_ring_topology(self):
"""创建环形拓扑"""
for i in range(self.num_robots):
j = (i + 1) % self.num_robots
self.comm_graph.add_edge(i, j, weight=1.0)
def create_star_topology(self):
"""创建星形拓扑(robot0为中心)"""
for i in range(1, self.num_robots):
self.comm_graph.add_edge(0, i, weight=1.0)
def robot_status_callback(self, msg, robot_id):
"""机器人状态回调"""
# 更新机器人位置
self.robot_positions[robot_id] = np.array([
msg.pose.position.x,
msg.pose.position.y
])
# 如果是动态拓扑,更新连接
if self.topology_type == 'dynamic':
self.update_dynamic_topology()
def update_dynamic_topology(self):
"""更新动态拓扑(基于距离)"""
# 清除现有边
self.comm_graph.clear_edges()
# 根据距离添加边
for i in range(self.num_robots):
for j in range(i + 1, self.num_robots):
distance = np.linalg.norm(
self.robot_positions[i] - self.robot_positions[j]
)
if distance <= self.comm_range:
# 在通信范围内,添加边
weight = 1.0 / (1.0 + distance) # 距离越近,权重越大
self.comm_graph.add_edge(i, j, weight=weight)
def update_topology(self, event):
"""定期更新拓扑"""
# 获取当前机器人的邻居
self.neighbor_list = list(self.comm_graph.neighbors(self.robot_id))
# 发布邻居信息
neighbor_msg = String()
neighbor_msg.data = ','.join(map(str, self.neighbor_list))
self.neighbor_pub.publish(neighbor_msg)
# 计算拓扑特性
self.analyze_topology()
def analyze_topology(self):
"""分析拓扑特性"""
if self.comm_graph.number_of_edges() == 0:
return
try:
# 连通性
is_connected = nx.is_connected(self.comm_graph)
# 平均度
avg_degree = np.mean([d for n, d in self.comm_graph.degree()])
# 网络直径(最长最短路径)
if is_connected:
diameter = nx.diameter(self.comm_graph)
else:
diameter = -1
# 聚类系数
clustering_coeff = nx.average_clustering(self.comm_graph)
rospy.loginfo(f"Topology Analysis - Connected: {is_connected}, "
f"Avg Degree: {avg_degree:.2f}, "
f"Diameter: {diameter}, "
f"Clustering: {clustering_coeff:.3f}")
except Exception as e:
rospy.logwarn(f"Topology analysis failed: {e}")
def get_shortest_path(self, source, target):
"""获取最短路径"""
try:
path = nx.shortest_path(self.comm_graph, source, target)
return path
except nx.NetworkXNoPath:
return None
def broadcast_message(self, message, hop_limit=3):
"""广播消息(洪泛算法)"""
visited = set()
queue = [(self.robot_id, 0, message)]
while queue:
robot_id, hops, msg = queue.pop(0)
if robot_id in visited or hops > hop_limit:
continue
visited.add(robot_id)
# 发送消息给邻居
for neighbor in self.comm_graph.neighbors(robot_id):
if neighbor not in visited:
queue.append((neighbor, hops + 1, msg))
self.send_to_robot(neighbor, msg)
def send_to_robot(self, target_id, message):
"""发送消息给特定机器人"""
msg_pub = rospy.Publisher(
f'/robot{target_id}/inbox', String, queue_size=1
)
msg_pub.publish(message)
class ConsensusProtocol:
"""分布式一致性协议"""
def __init__(self):
self.robot_id = rospy.get_param('~robot_id', 0)
self.num_robots = rospy.get_param('~num_robots', 3)
# 状态变量
self.state = 0.0
self.neighbor_states = {}
# 一致性参数
self.consensus_rate = rospy.get_param('~consensus_rate', 0.1)
# 通信
self.state_pub = rospy.Publisher(
f'/robot{self.robot_id}/consensus_state',
Float64, queue_size=10
)
# 订阅邻居状态
self.state_subs = []
for i in range(self.num_robots):
if i != self.robot_id:
sub = rospy.Subscriber(
f'/robot{i}/consensus_state', Float64,
self.neighbor_state_callback, callback_args=i
)
self.state_subs.append(sub)
# 一致性更新定时器
self.consensus_timer = rospy.Timer(
rospy.Duration(0.1), self.consensus_update
)
def neighbor_state_callback(self, msg, robot_id):
"""邻居状态回调"""
self.neighbor_states[robot_id] = msg.data
def consensus_update(self, event):
"""一致性更新"""
if not self.neighbor_states:
return
# 平均一致性算法
state_sum = self.state
for neighbor_state in self.neighbor_states.values():
state_sum += self.consensus_rate * (neighbor_state - self.state)
self.state = state_sum
# 发布更新后的状态
self.state_pub.publish(self.state)
二、任务分配与协调
2.1 任务分配算法
实现多种任务分配算法:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import rospy
import numpy as np
from scipy.optimize import linear_sum_assignment
from multi_robot_msgs.msg import Task, TaskList, RobotCapability
from geometry_msgs.msg import Point
import pulp
class TaskAllocator:
"""多机器人任务分配器"""
def __init__(self):
rospy.init_node('task_allocator', anonymous=True)
# 配置参数
self.num_robots = rospy.get_param('~num_robots', 3)
self.allocation_method = rospy.get_param('~allocation_method', 'hungarian')
# 任务和机器人信息
self.tasks = []
self.robot_capabilities = {}
self.robot_positions = {}
self.robot_status = {}
# 分配结果
self.task_assignments = {}
# ROS通信
self.task_sub = rospy.Subscriber(
'/tasks', TaskList, self.tasks_callback
)
# 订阅机器人能力和状态
for i in range(self.num_robots):
rospy.Subscriber(
f'/robot{i}/capability', RobotCapability,
self.capability_callback, callback_args=i
)
rospy.Subscriber(
f'/robot{i}/position', Point,
self.position_callback, callback_args=i
)
# 发布分配结果
self.assignment_pub = rospy.Publisher(
'/task_assignments', TaskAssignments, queue_size=10
)
rospy.loginfo(f"Task allocator initialized with {self.allocation_method} method")
def tasks_callback(self, msg):
"""任务列表回调"""
self.tasks = msg.tasks
# 执行任务分配
if self.allocation_method == 'hungarian':
self.hungarian_assignment()
elif self.allocation_method == 'auction':
self.auction_based_assignment()
elif self.allocation_method == 'market':
self.market_based_assignment()
elif self.allocation_method == 'swarm':
self.swarm_assignment()
else:
rospy.logwarn(f"Unknown allocation method: {self.allocation_method}")
def capability_callback(self, msg, robot_id):
"""机器人能力回调"""
self.robot_capabilities[robot_id] = msg
def position_callback(self, msg, robot_id):
"""机器人位置回调"""
self.robot_positions[robot_id] = np.array([msg.x, msg.y, msg.z])
def hungarian_assignment(self):
"""匈牙利算法任务分配"""
if len(self.tasks) == 0 or len(self.robot_positions) == 0:
return
# 构建成本矩阵
num_tasks = len(self.tasks)
num_robots = len(self.robot_positions)
# 确保矩阵是方阵
matrix_size = max(num_tasks, num_robots)
cost_matrix = np.full((matrix_size, matrix_size), 1e6)
for i, task in enumerate(self.tasks):
task_pos = np.array([task.position.x, task.position.y, 0])
for j, robot_id in enumerate(self.robot_positions.keys()):
# 计算成本(距离 + 能力匹配度)
distance = np.linalg.norm(
self.robot_positions[robot_id] - task_pos
)
# 能力匹配度
capability_cost = self.compute_capability_cost(task, robot_id)
# 总成本
cost_matrix[i][j] = distance + capability_cost
# 执行匈牙利算法
row_ind, col_ind = linear_sum_assignment(cost_matrix)
# 生成分配结果
self.task_assignments = {}
for i, j in zip(row_ind, col_ind):
if i < num_tasks and j < num_robots:
task_id = self.tasks[i].id
robot_id = list(self.robot_positions.keys())[j]
self.task_assignments[task_id] = robot_id
self.publish_assignments()
rospy.loginfo(f"Hungarian assignment completed: {self.task_assignments}")
def auction_based_assignment(self):
"""基于拍卖的任务分配"""
if not self.tasks:
return
# 初始化
task_bids = {task.id: {} for task in self.tasks}
assigned_robots = set()
# 第一轮:机器人对任务出价
for task in self.tasks:
for robot_id in self.robot_positions.keys():
if robot_id not in assigned_robots:
bid = self.compute_bid(task, robot_id)
task_bids[task.id][robot_id] = bid
# 第二轮:任务选择最高出价者
self.task_assignments = {}
for task_id, bids in task_bids.items():
if bids:
# 选择出价最高的机器人
winner = max(bids, key=bids.get)
self.task_assignments[task_id] = winner
assigned_robots.add(winner)
self.publish_assignments()
rospy.loginfo(f"Auction assignment completed: {self.task_assignments}")
def compute_bid(self, task, robot_id):
"""计算机器人对任务的出价"""
# 基于距离的成本
task_pos = np.array([task.position.x, task.position.y, 0])
distance = np.linalg.norm(
self.robot_positions[robot_id] - task_pos
)
distance_cost = 1.0 / (1.0 + distance)
# 基于能力的收益
capability_score = self.compute_capability_score(task, robot_id)
# 出价 = 收益 - 成本
bid = capability_score * 10.0 - distance_cost
return max(0, bid)
def market_based_assignment(self):
"""基于市场机制的任务分配"""
# 使用线性规划求解
prob = pulp.LpProblem("TaskAllocation", pulp.LpMaximize)
# 决策变量:x[i][j] = 1 表示任务i分配给机器人j
x = {}
for i, task in enumerate(self.tasks):
for j in range(self.num_robots):
x[i, j] = pulp.LpVariable(f"x_{i}_{j}", cat='Binary')
# 目标函数:最大化总收益
total_profit = 0
for i, task in enumerate(self.tasks):
for j in range(self.num_robots):
profit = self.compute_profit(task, j)
total_profit += profit * x[i, j]
prob += total_profit
# 约束条件
# 1. 每个任务最多分配给一个机器人
for i in range(len(self.tasks)):
prob += pulp.lpSum([x[i, j] for j in range(self.num_robots)]) <= 1
# 2. 每个机器人最多执行有限个任务
max_tasks_per_robot = 3
for j in range(self.num_robots):
prob += pulp.lpSum([x[i, j] for i in range(len(self.tasks))]) <= max_tasks_per_robot
# 求解
prob.solve(pulp.PULP_CBC_CMD(msg=0))
# 提取结果
self.task_assignments = {}
for i, task in enumerate(self.tasks):
for j in range(self.num_robots):
if x[i, j].varValue == 1:
self.task_assignments[task.id] = j
self.publish_assignments()
rospy.loginfo(f"Market-based assignment completed: {self.task_assignments}")
def swarm_assignment(self):
"""群体智能任务分配"""
# 基于响应阈值模型
response_threshold = 0.5
self.task_assignments = {}
assigned_robots = set()
for task in self.tasks:
task_stimulus = task.priority # 任务刺激强度
best_response = -1
best_robot = None
for robot_id in self.robot_positions.keys():
if robot_id not in assigned_robots:
# 计算响应概率
response = self.compute_response_probability(
task, robot_id, task_stimulus, response_threshold
)
if response > best_response:
best_response = response
best_robot = robot_id
if best_robot is not None:
self.task_assignments[task.id] = best_robot
assigned_robots.add(best_robot)
self.publish_assignments()
rospy.loginfo(f"Swarm assignment completed: {self.task_assignments}")
def compute_response_probability(self, task, robot_id, stimulus, threshold):
"""计算响应概率(响应阈值模型)"""
# 基于距离的适应度
task_pos = np.array([task.position.x, task.position.y, 0])
distance = np.linalg.norm(
self.robot_positions[robot_id] - task_pos
)
distance_factor = 1.0 / (1.0 + distance)
# 响应概率
prob = (stimulus ** 2) / (stimulus ** 2 + threshold ** 2)
return prob * distance_factor
def compute_capability_cost(self, task, robot_id):
"""计算能力匹配成本"""
if robot_id not in self.robot_capabilities:
return 10.0 # 高成本表示不匹配
capability = self.robot_capabilities[robot_id]
# 检查任务需求和机器人能力的匹配度
cost = 0.0
# 速度需求
if task.required_speed > capability.max_speed:
cost += (task.required_speed - capability.max_speed) * 2.0
# 负载需求
if task.required_payload > capability.max_payload:
cost += (task.required_payload - capability.max_payload) * 3.0
# 技能需求
for skill in task.required_skills:
if skill not in capability.skills:
cost += 5.0
return cost
def compute_capability_score(self, task, robot_id):
"""计算能力匹配分数"""
if robot_id not in self.robot_capabilities:
return 0.0
capability = self.robot_capabilities[robot_id]
score = 10.0
# 速度匹配
if task.required_speed <= capability.max_speed:
score += 2.0
else:
score -= (task.required_speed - capability.max_speed)
# 负载匹配
if task.required_payload <= capability.max_payload:
score += 3.0
else:
score -= (task.required_payload - capability.max_payload) * 2.0
# 技能匹配
matched_skills = 0
for skill in task.required_skills:
if skill in capability.skills:
matched_skills += 1
score += matched_skills * 2.0
return max(0, score)
def compute_profit(self, task, robot_id):
"""计算利润(市场机制)"""
# 任务收益
task_revenue = task.reward
# 执行成本
task_pos = np.array([task.position.x, task.position.y, 0])
if robot_id in self.robot_positions:
distance = np.linalg.norm(
self.robot_positions[robot_id] - task_pos
)
travel_cost = distance * 0.1 # 旅行成本
else:
travel_cost = 10.0
# 时间成本
time_cost = task.estimated_duration * 0.05
# 利润 = 收益 - 成本
profit = task_revenue - travel_cost - time_cost
return max(0, profit)
def publish_assignments(self):
"""发布任务分配结果"""
# 为每个机器人发布其任务
for task_id, robot_id in self.task_assignments.items():
task_pub = rospy.Publisher(
f'/robot{robot_id}/assigned_task', Task, queue_size=1
)
# 查找任务详情
for task in self.tasks:
if task.id == task_id:
task_pub.publish(task)
break
三、编队控制
3.1 编队控制算法
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import rospy
import numpy as np
from geometry_msgs.msg import Twist, PoseStamped, Point
from nav_msgs.msg import Odometry
from std_msgs.msg import String
import tf.transformations as tf
class FormationController:
"""多机器人编队控制器"""
def __init__(self):
rospy.init_node('formation_controller', anonymous=True)
# 机器人配置
self.robot_id = rospy.get_param('~robot_id', 0)
self.num_robots = rospy.get_param('~num_robots', 3)
self.is_leader = rospy.get_param('~is_leader', False)
# 编队参数
self.formation_type = rospy.get_param('~formation_type', 'triangle')
self.formation_scale = rospy.get_param('~formation_scale', 2.0)
# 控制参数
self.kp_pos = rospy.get_param('~kp_pos', 2.0)
self.kp_vel = rospy.get_param('~kp_vel', 1.0)
self.kp_formation = rospy.get_param('~kp_formation', 1.5)
# 状态变量
self.current_pose = None
self.current_velocity = np.zeros(2)
self.desired_position = None
self.leader_pose = None
self.neighbor_poses = {}
# 编队配置
self.formation_positions = self.get_formation_positions()
# ROS通信
self.cmd_vel_pub = rospy.Publisher(
f'/robot{self.robot_id}/cmd_vel', Twist, queue_size=10
)
self.odom_sub = rospy.Subscriber(
f'/robot{self.robot_id}/odom', Odometry, self.odom_callback
)
if not self.is_leader:
# 跟随者订阅领导者位置
self.leader_sub = rospy.Subscriber(
'/robot0/pose', PoseStamped, self.leader_callback
)
# 订阅邻居位置
for i in range(self.num_robots):
if i != self.robot_id:
rospy.Subscriber(
f'/robot{i}/pose', PoseStamped,
self.neighbor_callback, callback_args=i
)
# 控制定时器
self.control_timer = rospy.Timer(
rospy.Duration(0.1), self.control_loop
)
rospy.loginfo(f"Formation controller initialized for robot {self.robot_id}")
def get_formation_positions(self):
"""获取编队位置配置"""
positions = {}
if self.formation_type == 'line':
# 直线编队
for i in range(self.num_robots):
positions[i] = np.array([
-i * self.formation_scale, 0
])
elif self.formation_type == 'triangle':
# 三角形编队
if self.num_robots >= 3:
positions[0] = np.array([0, 0])
positions[1] = np.array([-self.formation_scale, -self.formation_scale])
positions[2] = np.array([-self.formation_scale, self.formation_scale])
# 额外的机器人排成第二排
for i in range(3, self.num_robots):
row = (i - 3) // 3 + 1
col = (i - 3) % 3
positions[i] = np.array([
-self.formation_scale * (row + 1),
(col - 1) * self.formation_scale
])
elif self.formation_type == 'diamond':
# 菱形编队
if self.num_robots >= 4:
positions[0] = np.array([0, 0])
positions[1] = np.array([-self.formation_scale, -self.formation_scale])
positions[2] = np.array([-2*self.formation_scale, 0])
positions[3] = np.array([-self.formation_scale, self.formation_scale])
elif self.formation_type == 'circle':
# 圆形编队
angle_step = 2 * np.pi / self.num_robots
for i in range(self.num_robots):
angle = i * angle_step
positions[i] = np.array([
self.formation_scale * np.cos(angle),
self.formation_scale * np.sin(angle)
])
elif self.formation_type == 'v':
# V字形编队
for i in range(self.num_robots):
side = 1 if i % 2 == 0 else -1
offset = i // 2 + 1
positions[i] = np.array([
-offset * self.formation_scale,
side * offset * self.formation_scale * 0.5
])
else:
rospy.logwarn(f"Unknown formation type: {self.formation_type}")
# 默认直线编队
for i in range(self.num_robots):
positions[i] = np.array([-i * self.formation_scale, 0])
return positions
def odom_callback(self, msg):
"""里程计回调"""
self.current_pose = msg.pose.pose
self.current_velocity = np.array([
msg.twist.twist.linear.x,
msg.twist.twist.linear.y
])
def leader_callback(self, msg):
"""领导者位置回调"""
self.leader_pose = msg.pose
def neighbor_callback(self, msg, robot_id):
"""邻居位置回调"""
self.neighbor_poses[robot_id] = msg.pose
def control_loop(self, event):
"""控制循环"""
if self.current_pose is None:
return
if self.is_leader:
# 领导者控制
self.leader_control()
else:
# 跟随者控制
self.follower_control()
def leader_control(self):
"""领导者控制逻辑"""
# 领导者可以跟踪预定义路径或接收外部命令
cmd = Twist()
# 示例:圆形轨迹
t = rospy.Time.now().to_sec()
radius = 5.0
omega = 0.2
cmd.linear.x = radius * omega
cmd.angular.z = omega
self.cmd_vel_pub.publish(cmd)
def follower_control(self):
"""跟随者控制逻辑"""
if self.leader_pose is None:
return
# 计算期望位置(相对于领导者)
leader_pos = np.array([
self.leader_pose.position.x,
self.leader_pose.position.y
])
# 获取领导者朝向
quaternion = [
self.leader_pose.orientation.x,
self.leader_pose.orientation.y,
self.leader_pose.orientation.z,
self.leader_pose.orientation.w
]
_, _, leader_yaw = tf.euler_from_quaternion(quaternion)
# 旋转编队位置到世界坐标系
rotation_matrix = np.array([
[np.cos(leader_yaw), -np.sin(leader_yaw)],
[np.sin(leader_yaw), np.cos(leader_yaw)]
])
local_offset = self.formation_positions[self.robot_id]
global_offset = rotation_matrix @ local_offset
desired_position = leader_pos + global_offset
# 当前位置
current_pos = np.array([
self.current_pose.position.x,
self.current_pose.position.y
])
# 位置误差
position_error = desired_position - current_pos
# 基于一致性的编队保持
consensus_vel = self.compute_consensus_velocity()
# 控制律
control_vel = (
self.kp_pos * position_error +
self.kp_formation * consensus_vel
)
# 避免碰撞
avoidance_vel = self.compute_collision_avoidance()
control_vel += avoidance_vel
# 转换为Twist消息
cmd = Twist()
cmd.linear.x = control_vel[0]
cmd.linear.y = control_vel[1]
# 计算角速度以保持朝向
desired_yaw = np.arctan2(control_vel[1], control_vel[0])
current_yaw = self.get_yaw_from_quaternion(self.current_pose.orientation)
yaw_error = self.normalize_angle(desired_yaw - current_yaw)
cmd.angular.z = 2.0 * yaw_error
self.cmd_vel_pub.publish(cmd)
def compute_consensus_velocity(self):
"""计算基于一致性的速度"""
consensus_vel = np.zeros(2)
for neighbor_id, neighbor_pose in self.neighbor_poses.items():
# 计算与邻居的相对位置
neighbor_pos = np.array([
neighbor_pose.position.x,
neighbor_pose.position.y
])
current_pos = np.array([
self.current_pose.position.x,
self.current_pose.position.y
])
# 期望的相对位置
desired_relative = (
self.formation_positions[self.robot_id] -
self.formation_positions[neighbor_id]
)
# 实际的相对位置
actual_relative = current_pos - neighbor_pos
# 相对位置误差
relative_error = desired_relative - actual_relative
consensus_vel += 0.1 * relative_error
return consensus_vel
def compute_collision_avoidance(self):
"""计算避撞速度"""
avoidance_vel = np.zeros(2)
safety_distance = 1.0
current_pos = np.array([
self.current_pose.position.x,
self.current_pose.position.y
])
for neighbor_pose in self.neighbor_poses.values():
neighbor_pos = np.array([
neighbor_pose.position.x,
neighbor_pose.position.y
])
# 计算距离
relative_pos = current_pos - neighbor_pos
distance = np.linalg.norm(relative_pos)
if distance < safety_distance and distance > 0.01:
# 斥力
repulsive_force = (
(1.0 / distance - 1.0 / safety_distance) *
(1.0 / distance ** 2) *
relative_pos / distance
)
avoidance_vel += repulsive_force * 10.0
return avoidance_vel
def get_yaw_from_quaternion(self, quaternion):
"""从四元数提取yaw角"""
q = [quaternion.x, quaternion.y, quaternion.z, quaternion.w]
_, _, yaw = tf.euler_from_quaternion(q)
return yaw
def normalize_angle(self, angle):
"""角度归一化"""
while angle > np.pi:
angle -= 2 * np.pi
while angle < -np.pi:
angle += 2 * np.pi
return angle
四、分布式SLAM
4.1 多机器人SLAM系统
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import rospy
import numpy as np
from nav_msgs.msg import OccupancyGrid, Odometry
from sensor_msgs.msg import LaserScan, PointCloud2
from geometry_msgs.msg import PoseWithCovarianceStamped, PoseArray
from multi_robot_msgs.msg import Map, MapMergeRequest
import tf2_ros
import cv2
from sklearn.neighbors import NearestNeighbors
class DistributedSLAM:
"""分布式SLAM系统"""
def __init__(self):
rospy.init_node('distributed_slam', anonymous=True)
# 机器人配置
self.robot_id = rospy.get_param('~robot_id', 0)
self.num_robots = rospy.get_param('~num_robots', 3)
# SLAM参数
self.map_resolution = rospy.get_param('~map_resolution', 0.05)
self.map_size = rospy.get_param('~map_size', 2000)
# 地图数据
self.local_map = np.ones((self.map_size, self.map_size)) * 0.5
self.global_map = np.ones((self.map_size, self.map_size)) * 0.5
self.other_maps = {}
# 位姿数据
self.current_pose = None
self.trajectory = []
self.other_trajectories = {}
# 特征数据(用于地图匹配)
self.local_features = []
self.global_features = []
# TF
self.tf_buffer = tf2_ros.Buffer()
self.tf_listener = tf2_ros.TransformListener(self.tf_buffer)
# ROS通信
self.map_pub = rospy.Publisher(
f'/robot{self.robot_id}/map', OccupancyGrid, queue_size=1
)
self.merged_map_pub = rospy.Publisher(
'/merged_map', OccupancyGrid, queue_size=1
)
self.scan_sub = rospy.Subscriber(
f'/robot{self.robot_id}/scan', LaserScan, self.scan_callback
)
self.odom_sub = rospy.Subscriber(
f'/robot{self.robot_id}/odom', Odometry, self.odom_callback
)
# 订阅其他机器人的地图
for i in range(self.num_robots):
if i != self.robot_id:
rospy.Subscriber(
f'/robot{i}/map', OccupancyGrid,
self.other_map_callback, callback_args=i
)
# 地图合并定时器
self.merge_timer = rospy.Timer(
rospy.Duration(5.0), self.merge_maps
)
rospy.loginfo(f"Distributed SLAM initialized for robot {self.robot_id}")
def scan_callback(self, msg):
"""激光扫描回调"""
if self.current_pose is None:
return
# 将激光数据转换为地图更新
self.update_local_map(msg)
# 提取特征点
features = self.extract_features(msg)
self.local_features.extend(features)
def odom_callback(self, msg):
"""里程计回调"""
self.current_pose = msg.pose.pose
self.trajectory.append(self.current_pose)
def other_map_callback(self, msg, robot_id):
"""其他机器人地图回调"""
# 将OccupancyGrid转换为numpy数组
map_data = np.array(msg.data).reshape((msg.info.height, msg.info.width))
self.other_maps[robot_id] = {
'data': map_data,
'info': msg.info,
'timestamp': msg.header.stamp
}
def update_local_map(self, scan):
"""更新局部地图"""
# 获取机器人在地图中的位置
robot_x = int(self.current_pose.position.x / self.map_resolution + self.map_size / 2)
robot_y = int(self.current_pose.position.y / self.map_resolution + self.map_size / 2)
# 获取机器人朝向
quaternion = [
self.current_pose.orientation.x,
self.current_pose.orientation.y,
self.current_pose.orientation.z,
self.current_pose.orientation.w
]
_, _, robot_yaw = tf.euler_from_quaternion(quaternion)
# 更新地图
angle = scan.angle_min
for i, range_val in enumerate(scan.ranges):
if scan.range_min < range_val < scan.range_max:
# 计算激光点在地图中的位置
world_angle = robot_yaw + angle
endpoint_x = robot_x + int(range_val * np.cos(world_angle) / self.map_resolution)
endpoint_y = robot_y + int(range_val * np.sin(world_angle) / self.map_resolution)
# 使用Bresenham算法更新地图
self.bresenham_update(robot_x, robot_y, endpoint_x, endpoint_y)
angle += scan.angle_increment
# 发布局部地图
self.publish_map(self.local_map, f"robot{self.robot_id}_map")
def bresenham_update(self, x0, y0, x1, y1):
"""Bresenham直线算法更新地图"""
dx = abs(x1 - x0)
dy = abs(y1 - y0)
sx = 1 if x0 < x1 else -1
sy = 1 if y0 < y1 else -1
err = dx - dy
while True:
# 更新地图单元
if 0 <= x0 < self.map_size and 0 <= y0 < self.map_size:
if x0 == x1 and y0 == y1:
# 障碍物
self.local_map[y0, x0] = min(self.local_map[y0, x0] + 0.1, 1.0)
else:
# 自由空间
self.local_map[y0, x0] = max(self.local_map[y0, x0] - 0.02, 0.0)
if x0 == x1 and y0 == y1:
break
e2 = 2 * err
if e2 > -dy:
err -= dy
x0 += sx
if e2 < dx:
err += dx
y0 += sy
def extract_features(self, scan):
"""从激光扫描中提取特征点"""
features = []
# 简单的角点检测
ranges = np.array(scan.ranges)
valid_indices = np.where(
(ranges > scan.range_min) & (ranges < scan.range_max)
)[0]
if len(valid_indices) > 10:
# 计算相邻点的距离变化
for i in range(1, len(valid_indices) - 1):
idx = valid_indices[i]
if idx > 0 and idx < len(ranges) - 1:
diff = abs(ranges[idx] - ranges[idx-1]) + abs(ranges[idx+1] - ranges[idx])
if diff > 0.5: # 阈值
# 这是一个特征点
angle = scan.angle_min + idx * scan.angle_increment
feature = {
'range': ranges[idx],
'angle': angle,
'pose': self.current_pose,
'descriptor': self.compute_feature_descriptor(ranges, idx)
}
features.append(feature)
return features
def compute_feature_descriptor(self, ranges, index, window=5):
"""计算特征描述子"""
start = max(0, index - window)
end = min(len(ranges), index + window + 1)
descriptor = ranges[start:end]
# 归一化
if len(descriptor) > 0:
descriptor = descriptor / np.linalg.norm(descriptor)
return descriptor
def merge_maps(self, event):
"""合并多个机器人的地图"""
if not self.other_maps:
return
# 初始化全局地图
merged_map = self.local_map.copy()
for robot_id, map_data in self.other_maps.items():
# 寻找地图之间的变换
transform = self.find_map_alignment(
self.local_map, map_data['data']
)
if transform is not None:
# 应用变换并合并
aligned_map = self.transform_map(map_data['data'], transform)
merged_map = self.fuse_maps(merged_map, aligned_map)
self.global_map = merged_map
# 发布合并后的地图
self.publish_map(self.global_map, "merged_map")
def find_map_alignment(self, map1, map2):
"""寻找两个地图之间的对齐变换"""
# 使用特征匹配或ICP算法
# 这里简化为使用OpenCV的模板匹配
# 转换为图像格式
img1 = (map1 * 255).astype(np.uint8)
img2 = (map2 * 255).astype(np.uint8)
# 特征检测
orb = cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(img1, None)
kp2, des2 = orb.detectAndCompute(img2, None)
if des1 is None or des2 is None:
return None
# 特征匹配
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(des1, des2)
if len(matches) < 10:
return None
# 计算变换矩阵
src_pts = np.float32([kp1[m.queryIdx].pt for m in matches]).reshape(-1, 1, 2)
dst_pts = np.float32([kp2[m.trainIdx].pt for m in matches]).reshape(-1, 1, 2)
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
return M
def transform_map(self, map_data, transform):
"""应用变换到地图"""
if transform is None:
return map_data
# 应用透视变换
img = (map_data * 255).astype(np.uint8)
transformed = cv2.warpPerspective(
img, transform, (self.map_size, self.map_size)
)
return transformed.astype(np.float32) / 255.0
def fuse_maps(self, map1, map2, weight1=0.6, weight2=0.4):
"""融合两个地图"""
# 加权平均
fused = weight1 * map1 + weight2 * map2
# 归一化到[0, 1]
fused = np.clip(fused, 0.0, 1.0)
return fused
def publish_map(self, map_data, frame_id):
"""发布地图"""
msg = OccupancyGrid()
msg.header.stamp = rospy.Time.now()
msg.header.frame_id = frame_id
msg.info.resolution = self.map_resolution
msg.info.width = self.map_size
msg.info.height = self.map_size
msg.info.origin.position.x = -self.map_size * self.map_resolution / 2
msg.info.origin.position.y = -self.map_size * self.map_resolution / 2
msg.info.origin.orientation.w = 1.0
# 转换为占用概率
occupancy = (map_data * 100).astype(np.int8)
msg.data = occupancy.flatten().tolist()
if frame_id == "merged_map":
self.merged_map_pub.publish(msg)
else:
self.map_pub.publish(msg)
五、实践案例
5.1 多机器人巡逻系统
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import rospy
import numpy as np
from geometry_msgs.msg import Point, Twist, PoseStamped
from nav_msgs.msg import Path
from std_msgs.msg import String, Bool
from multi_robot_msgs.msg import PatrolTask, PatrolStatus
import networkx as nx
class MultiRobotPatrol:
"""多机器人巡逻系统"""
def __init__(self):
rospy.init_node('multi_robot_patrol', anonymous=True)
# 系统配置
self.num_robots = rospy.get_param('~num_robots', 3)
self.patrol_area = rospy.get_param('~patrol_area', [
[0, 0], [10, 0], [10, 10], [0, 10]
])
# 巡逻点
self.patrol_points = self.generate_patrol_points()
self.patrol_graph = self.create_patrol_graph()
# 机器人状态
self.robot_status = {}
self.robot_assignments = {}
# 巡逻策略
self.patrol_strategy = rospy.get_param('~patrol_strategy', 'partition')
# ROS通信
self.init_ros_communication()
# 任务分配定时器
self.allocation_timer = rospy.Timer(
rospy.Duration(10.0), self.allocate_patrol_tasks
)
rospy.loginfo("Multi-robot patrol system initialized")
def init_ros_communication(self):
"""初始化ROS通信"""
# 为每个机器人创建发布者
self.task_publishers = {}
self.path_publishers = {}
for i in range(self.num_robots):
self.task_publishers[i] = rospy.Publisher(
f'/robot{i}/patrol_task', PatrolTask, queue_size=10
)
self.path_publishers[i] = rospy.Publisher(
f'/robot{i}/patrol_path', Path, queue_size=10
)
# 订阅机器人状态
rospy.Subscriber(
f'/robot{i}/patrol_status', PatrolStatus,
self.status_callback, callback_args=i
)
def generate_patrol_points(self):
"""生成巡逻点"""
points = []
# 网格化巡逻区域
x_min, y_min = self.patrol_area[0]
x_max, y_max = self.patrol_area[2]
grid_size = 2.0
x_steps = int((x_max - x_min) / grid_size)
y_steps = int((y_max - y_min) / grid_size)
for i in range(x_steps + 1):
for j in range(y_steps + 1):
x = x_min + i * grid_size
y = y_min + j * grid_size
points.append({'id': len(points), 'position': [x, y], 'priority': 1.0})
return points
def create_patrol_graph(self):
"""创建巡逻图"""
G = nx.Graph()
# 添加节点
for point in self.patrol_points:
G.add_node(point['id'], pos=point['position'])
# 添加边(连接相邻的巡逻点)
for i, p1 in enumerate(self.patrol_points):
for j, p2 in enumerate(self.patrol_points):
if i < j:
dist = np.linalg.norm(
np.array(p1['position']) - np.array(p2['position'])
)
if dist < 3.0: # 连接距离阈值
G.add_edge(p1['id'], p2['id'], weight=dist)
return G
def status_callback(self, msg, robot_id):
"""机器人状态回调"""
self.robot_status[robot_id] = {
'position': [msg.current_position.x, msg.current_position.y],
'is_patrolling': msg.is_patrolling,
'visited_points': msg.visited_points,
'battery_level': msg.battery_level
}
def allocate_patrol_tasks(self, event):
"""分配巡逻任务"""
if self.patrol_strategy == 'partition':
self.partition_based_allocation()
elif self.patrol_strategy == 'tsp':
self.tsp_based_allocation()
elif self.patrol_strategy == 'auction':
self.auction_based_allocation()
else:
rospy.logwarn(f"Unknown patrol strategy: {self.patrol_strategy}")
def partition_based_allocation(self):
"""基于区域划分的任务分配"""
# 将巡逻区域划分给不同的机器人
points_per_robot = len(self.patrol_points) // self.num_robots
for i in range(self.num_robots):
start_idx = i * points_per_robot
end_idx = start_idx + points_per_robot
if i == self.num_robots - 1:
# 最后一个机器人负责剩余的点
end_idx = len(self.patrol_points)
assigned_points = self.patrol_points[start_idx:end_idx]
self.robot_assignments[i] = assigned_points
# 生成巡逻路径
path = self.generate_patrol_path(i, assigned_points)
# 发送任务
self.send_patrol_task(i, assigned_points, path)
def tsp_based_allocation(self):
"""基于TSP的任务分配"""
# 为每个机器人求解TSP问题
for i in range(self.num_robots):
# 选择机器人负责的点
robot_points = []
for j, point in enumerate(self.patrol_points):
if j % self.num_robots == i:
robot_points.append(point)
self.robot_assignments[i] = robot_points
# 求解TSP
if robot_points:
tsp_path = self.solve_tsp(robot_points)
self.send_patrol_task(i, robot_points, tsp_path)
def solve_tsp(self, points):
"""求解旅行商问题"""
n = len(points)
if n <= 1:
return points
# 使用最近邻算法(简化版)
visited = [False] * n
path = []
current = 0
visited[current] = True
path.append(points[current])
for _ in range(n - 1):
next_point = -1
min_dist = float('inf')
for j in range(n):
if not visited[j]:
dist = np.linalg.norm(
np.array(points[current]['position']) -
np.array(points[j]['position'])
)
if dist < min_dist:
min_dist = dist
next_point = j
if next_point != -1:
visited[next_point] = True
path.append(points[next_point])
current = next_point
return path
def auction_based_allocation(self):
"""基于拍卖的任务分配"""
# 每个巡逻点进行拍卖
for point in self.patrol_points:
best_bid = -float('inf')
best_robot = None
for robot_id in range(self.num_robots):
bid = self.compute_patrol_bid(robot_id, point)
if bid > best_bid:
best_bid = bid
best_robot = robot_id
if best_robot is not None:
if best_robot not in self.robot_assignments:
self.robot_assignments[best_robot] = []
self.robot_assignments[best_robot].append(point)
# 为每个机器人生成路径
for robot_id, points in self.robot_assignments.items():
if points:
path = self.generate_patrol_path(robot_id, points)
self.send_patrol_task(robot_id, points, path)
def compute_patrol_bid(self, robot_id, point):
"""计算巡逻点的出价"""
bid = 10.0 # 基础出价
# 考虑距离
if robot_id in self.robot_status:
robot_pos = self.robot_status[robot_id]['position']
distance = np.linalg.norm(
np.array(robot_pos) - np.array(point['position'])
)
bid -= distance * 0.5
# 考虑电池
battery = self.robot_status[robot_id].get('battery_level', 1.0)
bid *= battery
# 考虑优先级
bid *= point['priority']
return bid
def generate_patrol_path(self, robot_id, points):
"""生成巡逻路径"""
if not points:
return []
# 使用图算法生成路径
path_points = []
for i in range(len(points)):
start = points[i]['id']
end = points[(i + 1) % len(points)]['id']
try:
# 使用Dijkstra算法找最短路径
shortest_path = nx.shortest_path(
self.patrol_graph, start, end, weight='weight'
)
for node_id in shortest_path:
pos = self.patrol_graph.nodes[node_id]['pos']
path_points.append(pos)
except nx.NetworkXNoPath:
# 没有路径,直接连接
path_points.append(points[i]['position'])
return path_points
def send_patrol_task(self, robot_id, points, path):
"""发送巡逻任务"""
# 创建任务消息
task = PatrolTask()
task.robot_id = robot_id
task.patrol_points = []
for point in points:
p = Point()
p.x = point['position'][0]
p.y = point['position'][1]
p.z = 0
task.patrol_points.append(p)
task.priority = 1.0
task.patrol_mode = "continuous"
self.task_publishers[robot_id].publish(task)
# 创建路径消息
path_msg = Path()
path_msg.header.frame_id = "map"
path_msg.header.stamp = rospy.Time.now()
for pos in path:
pose = PoseStamped()
pose.pose.position.x = pos[0]
pose.pose.position.y = pos[1]
pose.pose.orientation.w = 1.0
path_msg.poses.append(pose)
self.path_publishers[robot_id].publish(path_msg)
if __name__ == '__main__':
try:
patrol_system = MultiRobotPatrol()
rospy.spin()
except rospy.ROSInterruptException:
pass
六、故障处理与优化
6.1 通信故障处理
class CommunicationMonitor:
"""通信监控器"""
def __init__(self):
self.robot_id = rospy.get_param('~robot_id', 0)
self.heartbeat_timeout = rospy.get_param('~heartbeat_timeout', 5.0)
# 邻居心跳记录
self.neighbor_heartbeats = {}
self.neighbor_status = {}
# 心跳发布
self.heartbeat_pub = rospy.Publisher(
f'/robot{self.robot_id}/heartbeat', Header, queue_size=1
)
# 心跳定时器
self.heartbeat_timer = rospy.Timer(
rospy.Duration(1.0), self.send_heartbeat
)
# 检查定时器
self.check_timer = rospy.Timer(
rospy.Duration(2.0), self.check_neighbors
)
def send_heartbeat(self, event):
"""发送心跳"""
msg = Header()
msg.stamp = rospy.Time.now()
msg.frame_id = f"robot{self.robot_id}"
self.heartbeat_pub.publish(msg)
def heartbeat_callback(self, msg, robot_id):
"""心跳回调"""
self.neighbor_heartbeats[robot_id] = msg.stamp
self.neighbor_status[robot_id] = 'online'
def check_neighbors(self, event):
"""检查邻居状态"""
current_time = rospy.Time.now()
for robot_id, last_heartbeat in self.neighbor_heartbeats.items():
time_diff = (current_time - last_heartbeat).to_sec()
if time_diff > self.heartbeat_timeout:
if self.neighbor_status.get(robot_id) == 'online':
rospy.logwarn(f"Robot {robot_id} communication lost")
self.neighbor_status[robot_id] = 'offline'
self.handle_communication_failure(robot_id)
def handle_communication_failure(self, failed_robot_id):
"""处理通信故障"""
# 重新分配失败机器人的任务
# 更新通信拓扑
# 触发备份协议
pass
6.2 性能优化建议
-
通信优化
- 使用消息压缩减少带宽
- 实现优先级队列
- 采用事件驱动通信
-
计算优化
- 分布式计算负载均衡
- 使用近似算法
- 缓存频繁计算结果
-
协调优化
- 减少同步需求
- 使用局部信息决策
- 实现自适应协调策略
七、总结
本文深入探讨了ROS1中的多机器人系统实现,涵盖了从基础架构到高级应用的各个方面。主要内容包括:
- 系统架构:介绍了集中式、分布式和混合架构,以及ROS命名空间管理
- 通信拓扑:实现了动态通信图和一致性协议
- 任务分配:详细讲解了匈牙利算法、拍卖机制、市场机制等分配方法
- 编队控制:实现了多种编队形状和控制算法
- 分布式SLAM:介绍了多机器人地图构建和融合技术
- 实践案例:提供了完整的多机器人巡逻系统实现
通过本文的学习,读者应该能够:
- 理解多机器人系统的基本原理
- 掌握ROS多机器人编程技术
- 实现各种协作算法
- 设计和开发多机器人应用
多机器人系统是机器人技术发展的重要方向,随着5G、边缘计算等技术的发展,多机器人协作将在更多领域发挥重要作用。建议读者在掌握基础知识后,继续关注群体智能、深度强化学习等前沿技术在多机器人系统中的应用。
参考资料
- Multi-Robot Systems: From Swarms to Intelligent Automata
- Distributed Robotic Systems - MIT Press
- ROS Multi-Robot Documentation
- Cooperative Control of Multi-Agent Systems
- Swarm Intelligence: From Natural to Artificial Systems
更多推荐


所有评论(0)