RuyiSDK Board Docs

RISC-V ROS2 机器人操作系统编程技术

Source repository

ch20 · 行为树与恢复行为

TextbookProgramming languageEnvironmentLessonLab
RISC-VC++17SpacemiT K3 CoM260 Kit / Bianbu 4.0.6 / Humble, with an x86 Ubuntu 22.04 / Humble / Harmonic course containerRead lessonStart lab
x86PythonUbuntu 22.04 / Humble or Ubuntu 24.04 / JazzyRead lessonStart lab

This document is not yet available in English. The Chinese original is shown below.

第20章 行为树与恢复行为

课程:ROS2 Python 编程
章节:第20章
课时:2 课时(90 分钟)
教学方式:讲授 + 演示


学习目标

本章学习目标包括:理解行为树(Behavior Tree)的基本原理和节点类型,掌握Nav2中NavigateToPose行为树的结构,熟悉各种恢复行为(Spin/Backup/Wait)的配置和使用,能够自定义行为树和恢复行为,掌握行为树的调试和优化方法。

20.1 行为树基础

20.1.1 行为树概述

行为树 (Behavior Tree, BT) 是一种用于控制智能体决策流程的树形结构模型。相比传统的有限状态机 (FSM),行为树具有更好的模块化、可读性和可扩展性。

**行为树的起源:**最初用于游戏AI(Halo 2, 2005),后被引入机器人领域(Nav2, 2019),现已成为机器人任务编排的标准工具。

行为树 vs 有限状态机:

特性 行为树 (BT) 有限状态机 (FSM)
状态表示 树形节点 状态图
控制流 显式(树结构) 隐式(转换条件)
模块化 高(节点可独立) 低(转换耦合)
可重用性 节点可跨树重用 状态难重用
调试 可视化XML 日志跟踪
扩展性 添加新节点即可 需修改所有转换
容错 自然支持(Fallback) 需显式设计

20.1.2 节点类型

行为树包含四种核心节点类型:

控制节点:

Sequence (→): 
  顺序执行子节点
  - 全部返回SUCCESS → 返回SUCCESS
  - 任一返回FAILURE → 停止并返回FAILURE
  - 常用于"必须全部完成的步骤序列"

Fallback (?):
  尝试子节点(优先选择)
  - 任一返回SUCCESS → 返回SUCCESS
  - 全部返回FAILURE → 返回FAILURE
  - 常用于"尝试多种方法的备选方案"

Parallel (⇉):
  并行执行所有子节点
  - 达到成功阈值 → 返回SUCCESS
  - 达到失败阈值 → 返回FAILURE
  - 常用于"同时执行多项任务"

Decorator (装饰节点):
  修改子节点的行为
  - Inverter: 反转结果
  - Repeater: 重复执行
  - RateController: 控制执行频率
  - Timeout: 超时控制

执行节点:

Action (动作节点):
  执行具体任务
  - 导航、旋转、后退、等待
  - 返回 SUCCESS / FAILURE / RUNNING

Condition (条件节点):
  检查条件
  - 电池电量、障碍物检测、是否到达
  - 返回 SUCCESS / FAILURE(不会返回RUNNING)

20.1.3 节点状态

行为树节点执行后返回三种状态:

状态 含义 后续处理
SUCCESS 节点执行成功 继续执行下一个节点
FAILURE 节点执行失败 触发Fallback或终止
RUNNING 节点正在执行 下次tick继续执行
执行示例:
Sequence → Step1(SUCCESS) → Step2(RUNNING) → ...
         → Step1(SUCCESS) → Step2(SUCCESS) → 返回SUCCESS

Fallback → Option1(FAILURE) → Option2(SUCCESS) → 返回SUCCESS
         → Option1(FAILURE) → Option2(FAILURE) → Option3(FAILURE) → 返回FAILURE

20.1.4 官方要点——BehaviorTree.CPP 官方文档:控制流节点与黑板机制

本节内容综合翻译自 BehaviorTree.CPP 官方文档(behaviortree.dev 的 Tutorials 与 Principal Concepts 页面)、Nav2 官方文档的 Behavior Tree 页面与 nav2_behavior_tree 包源码,另参考 The Construct 的行为树课程与 Robotics Back-End 的恢复行为教程。原文均为英文,此处为中文编译,供课后巩固与进阶阅读。

behaviortree.dev 的教程将节点分为两种:执行实际工作的叶节点(Action、Condition)与组合逻辑的控制节点。官方强调树不是"目标导向"的自动机,而是每个 tick(默认 10 Hz,由 bt_navigator 的 bt_loop_duration 决定)从根节点按序执行的决策结构:Sequence 从左到右全部成功才算成功(对应"先检查电量再导航"的练习 2 题),Fallback 逐个尝试直到一个成功(恢复行为的主干),Decorator 则包装单节点添加重试、超时、反转等语义。子树间通过黑板(Blackboard)传递数据——目标位姿、路径、失败次数等都是黑板上带类型的键值。

20.2 Nav2行为树架构

20.2.1 NavigateToPose行为树

Nav2默认的导航到目标行为树 navigate_to_pose.xml:

<!-- navigate_to_pose.xml (完整版) -->
<root main_tree_to_execute="MainTree">
  <BehaviorTree ID="MainTree">
    <PipelineSequence name="NavigateWithRecovery">
      
      <!-- 全局规划阶段 -->
      <RateController hz="1.0">
        <RecoveryNode number_of_retries="1" name="ComputePathToPose">
          <ComputePathToPose 
            goal="{goal}" 
            path="{path}" 
            planner_id="GridBased"
            error_code="{error_code}"/>
          <ClearEntireCostmap 
            service_name="global_costmap/clear_entirely"/>
        </RecoveryNode>
      </RateController>
      
      <!-- 路径跟踪阶段 -->
      <RateController hz="10.0">
        <RecoveryNode number_of_retries="1" name="FollowPath">
          <FollowPath 
            path="{path}" 
            controller_id="FollowPath"
            error_code="{error_code}"/>
          <Sequence name="RecoveryActions">
            <Spin spin_dist="1.57"/>
            <Wait wait_duration="1.0"/>
            <BackUp backup_dist="0.15" 
                    backup_speed="0.05"/>
            <ClearEntireCostmap 
              service_name="local_costmap/clear_entirely"/>
          </Sequence>
        </RecoveryNode>
      </RateController>
      
      <!-- 全局重规划阶段 -->
      <RateController hz="1.0">
        <RecoveryNode number_of_retries="1" name="GlobalReplan">
          <ComputePathToPose 
            goal="{goal}" 
            path="{replan_path}" 
            planner_id="GridBased"
            error_code="{error_code}"/>
          <Sequence name="GlobalRecoveryActions">
            <ClearEntireCostmap 
              service_name="global_costmap/clear_entirely"/>
            <ClearEntireCostmap 
              service_name="local_costmap/clear_entirely"/>
          </Sequence>
        </RecoveryNode>
      </RateController>
      
    </PipelineSequence>
  </BehaviorTree>
</root>

20.2.2 行为树执行流程

打开nav2_params.yaml选择行为树:
bt_navigator:
  ros__parameters:
    default_bt_xml_filename: "navigate_to_pose.xml"  # 默认树
    default_server_timeout: 20                        # Action超时(s)
    plugin_lib_names:                                 # 行为树插件库
      - nav2_compute_path_to_pose_action_bt_node
      - nav2_follow_path_action_bt_node
      - nav2_spin_action_bt_node
      - nav2_back_up_action_bt_node
      - nav2_wait_action_bt_node
      - nav2_clear_costmap_service_bt_node
      - nav2_recovery_node_bt_node
      - nav2_pipeline_sequence_bt_node
      - nav2_rate_controller_bt_node
# 指定使用特定行为树
ros2 service call /bt_navigator/change_behavior_tree \
  nav2_msgs/srv/ChangeBehaviorTree \
  "{behavior_tree: 'navigate_to_pose.xml'}"

20.2.3 行为树节点连接

import rclpy
from rclpy.node import Node
from nav2_msgs.action import NavigateToPose
from rclpy.action import ActionClient
 
class BehaviorTreeClient(Node):
    """行为树Action客户端"""
    def __init__(self):
        super().__init__('bt_client')
        
        self.navigate_client = ActionClient(
            self, NavigateToPose, 'navigate_to_pose')
            
        # 检查可用行为树
        self.bt_list_client = self.create_client(
            nav2_msgs/srv/GetBehaviors, '/bt_navigator/get_behavior_tree_list')
            
    def get_available_bt(self) -> list:
        """获取可用的行为树列表"""
        while not self.bt_list_client.wait_for_service(timeout_sec=1.0):
            self.get_logger().info('等待BT列表服务...')
            
        future = self.bt_list_client.call_async(
            nav2_msgs/srv/GetBehaviors.Request())
        rclpy.spin_until_future_complete(self, future)
        return future.result().behaviors.trees
    
    def navigate_with_bt(self, x: float, y: float, yaw: float,
                          bt_file: str = ''):
        """使用指定行为树导航"""
        goal = NavigateToPose.Goal()
        goal.pose.header.frame_id = 'map'
        goal.pose.pose.position.x = x
        goal.pose.pose.position.y = y
        goal.pose.pose.orientation.z = math.sin(yaw / 2.0)
        goal.pose.pose.orientation.w = math.cos(yaw / 2.0)
        
        if bt_file:
            goal.behavior_tree = bt_file
            
        self.navigate_client.wait_for_server()
        self.send_goal_future = self.navigate_client.send_goal_async(
            goal, feedback_callback=self.feedback_callback)
        self.send_goal_future.add_done_callback(
            self.goal_response_callback)

20.3 恢复行为详解

20.3.1 恢复行为概述

当导航过程出现异常时,Nav2会触发恢复行为尝试解决问题:

**恢复行为的触发条件:**一是路径规划失败(无可行路径);二是路径跟踪失败(被障碍物卡住);三是目标不可达(被障碍物包围);四是代价地图异常(动态障碍物快速变化)。

默认恢复行为序列:

RecoveryNode(最多重试次数)
├── 主行为(ComputePathToPose / FollowPath)
└── 恢复序列(当主行为失败时)
    ├── Spin(原地旋转)
    ├── Wait(等待)
    ├── BackUp(后退)
    └── ClearEntireCostmap(清除代价地图)

20.3.2 Spin恢复行为

Spin让机器人原地旋转一定角度,重新感知周围环境:

import rclpy
from rclpy.action import ActionClient
from nav2_msgs.action import Spin
from geometry_msgs.msg import Quaternion
import math
 
class SpinRecovery:
    """Spin恢复行为"""
    def __init__(self, node):
        self.action_client = ActionClient(node, Spin, '/spin')
        
    def send_spin(self, target_yaw: float = 1.57,
                   time_allowance: float = 5.0) -> bool:
        """
        发送旋转命令
        
        参数:
            target_yaw: 目标旋转角度 (rad)
            time_allowance: 允许执行时间 (s)
        """
        goal = Spin.Goal()
        goal.target.yaw = target_yaw
        goal.time_allowance = rclpy.duration.Duration(
            seconds=time_allowance).to_msg()
        
        self.action_client.wait_for_server()
        future = self.action_client.send_goal_async(goal)
        rclpy.spin_until_future_complete(None, future)
        
        goal_handle = future.result()
        if not goal_handle.accepted:
            return False
            
        result_future = goal_handle.get_result_async()
        rclpy.spin_until_future_complete(None, result_future)
        
        result = result_future.result()
        return result.status == 4  # SUCCEEDED

Spin配置:

behavior_server:
  ros__parameters:
    behavior_plugins: ["spin", "backup", "drive_on_heading", "wait"]
    
    spin:
      plugin: "nav2_behaviors/Spin"
      simulate_ahead_time: 2.0        # 前向模拟时间(s)
      max_rotational_vel: 1.0         # 最大旋转速度(rad/s)
      min_rotational_vel: 0.1         # 最小旋转速度(rad/s)
      rotational_acc_lim: 3.0         # 旋转加速度(rad/s²)
      ctrl_rad_step: 0.01             # 控制步长(rad)

20.3.3 BackUp恢复行为

BackUp让机器人沿直线后退一段距离:

from nav2_msgs.action import BackUp
 
class BackUpRecovery:
    """BackUp恢复行为"""
    def __init__(self, node):
        self.action_client = ActionClient(node, BackUp, '/backup')
        
    def send_backup(self, distance: float = 0.15,
                     speed: float = 0.05) -> bool:
        """
        发送后退命令
        
        参数:
            distance: 后退距离 (m)
            speed: 后退速度 (m/s)
        """
        goal = BackUp.Goal()
        goal.target.x = -distance      # 负值表示后退
        goal.speed = speed
        goal.time_allowance = rclpy.duration.Duration(
            seconds=distance / speed + 1.0).to_msg()
        
        self.action_client.wait_for_server()
        future = self.action_client.send_goal_async(goal)
        rclpy.spin_until_future_complete(None, future)
        
        goal_handle = future.result()
        if not goal_handle.accepted:
            return False
            
        result_future = goal_handle.get_result_async()
        rclpy.spin_until_future_complete(None, result_future)
        
        result = result_future.result()
        return result.status == 4

BackUp配置:

backup:
  plugin: "nav2_behaviors/BackUp"
  simulate_ahead_time: 2.0
  max_linear_vel: 0.1           # 最大后退速度(m/s)
  min_linear_vel: 0.05          # 最小后退速度(m/s)
  linear_acc_lim: 0.5           # 加速度(m/s²)
  ctrl_rad_step: 0.01

20.3.4 Wait和Drive on Heading

Wait(等待):

wait:
  plugin: "nav2_behaviors/Wait"
  simulate_ahead_time: 2.0
  max_linear_vel: 0.0
  max_rotational_vel: 0.0

Drive on Heading(沿当前方向前进):

drive_on_heading:
  plugin: "nav2_behaviors/DriveOnHeading"
  simulate_ahead_time: 2.0
  max_linear_vel: 0.1
  min_linear_vel: 0.05
  linear_acc_lim: 0.5

20.3.5 手动触发恢复行为

# 触发Spin (旋转1.57 rad)
ros2 action send_goal /spin nav2_msgs/action/Spin \
  "{target: {yaw: 1.57}}"
 
# 触发Backup (后退0.3m)
ros2 action send_goal /backup nav2_msgs/action/BackUp \
  "{target: {x: -0.3}, speed: 0.05}"
 
# 清除全局代价地图
ros2 service call /global_costmap/clear_entirely \
  nav2_msgs/srv/ClearEntireCostmap
 
# 清除局部代价地图
ros2 service call /local_costmap/clear_entirely \
  nav2_msgs/srv/ClearEntireCostmap

20.3.6 官方要点——Nav2 默认恢复树:官方 XML 的恢复顺序逻辑

"为什么先 Spin 再 BackUp 最后清除代价地图"(练习第 4 题)的答案就在官方默认树文件 nav2_navigate_to_pose_behavior_tree.xml 中:导航失败后进入一个以 Fallback 为根、包裹 RecoveryNode 的恢复分支——ClearCostmap 作为最便宜且无位姿扰动的操作优先执行(避免自损);Spin 用于小范围环境感知,代价是原地旋转可能碰上动态障碍;BackUp 通过后退创造新视野,但依赖可用空间。三者通常被安排为"ClearCostmap → Spin/BackUp → 重规划"的循环,且每次失败计数通过黑板 RetryCount 累计,超过上限后直接上报失败给人形干预——这与练习第 6 题的分层故障设计完全同构。

20.4 自定义行为树

20.4.1 创建自定义XML行为树

<!-- custom_navigation.xml -->
<root main_tree_to_execute="MainTree">
  <BehaviorTree ID="MainTree">
    <Sequence name="CompleteNavigation">
      
      <!-- 步骤1: 检查电池电量 -->
      <BatteryCheck 
        min_battery_level="0.2"
        battery_topic="/battery_status"/>
      
      <!-- 步骤2: 计算全局路径 -->
      <ComputePathToPose 
        goal="{goal}" 
        path="{path}"/>
      
      <!-- 步骤3: 执行路径跟踪(带恢复) -->
      <RecoveryNode number_of_retries="2">
        <FollowPath path="{path}"/>
        <Sequence>
          <!-- 恢复策略1: 后退清除 -->
          <BackUp backup_dist="0.2"/>
          <ClearEntireCostmap 
            service_name="local_costmap/clear_entirely"/>
          <!-- 恢复策略2: 旋转扫描 -->
          <Spin spin_dist="3.14"/>
          <ClearEntireCostmap 
            service_name="local_costmap/clear_entirely"/>
          <!-- 恢复策略3: 重规划 -->
          <ClearEntireCostmap 
            service_name="global_costmap/clear_entirely"/>
          <ComputePathToPose 
            goal="{goal}" 
            path="{path}"/>
        </Sequence>
      </RecoveryNode>
      
      <!-- 步骤4: 到达后执行任务 -->
      <Sequence name="PostArrival">
        <Wait wait_duration="2.0"/>
        <!-- 到达后发通知 -->
        <PublishTopic topic="/arrival_signal" message="arrived"/>
      </Sequence>
      
    </Sequence>
  </BehaviorTree>
</root>

20.4.2 Python自定义行为树

import py_trees
import py_trees_ros
 
class BatteryCheck(py_trees.behaviour.Behaviour):
    """自定义行为:电池电量检查"""
    def __init__(self, name: str = "BatteryCheck",
                 min_level: float = 0.2,
                 topic: str = "/battery_status"):
        super().__init__(name)
        self.min_level = min_level
        self.topic = topic
        self.battery_level = None
        
    def setup(self, **kwargs):
        """设置订阅"""
        self.blackboard = py_trees.blackboard.Blackboard()
        
    def initialise(self):
        """初始化(每次执行时调用)"""
        self.battery_level = self.blackboard.get(self.topic)
        
    def update(self) -> py_trees.common.Status:
        """执行检查"""
        if self.battery_level is None:
            return py_trees.common.Status.FAILURE
            
        if self.battery_level > self.min_level:
            self.logger.info(f'电池电量充足: {self.battery_level:.1%}')
            return py_trees.common.Status.SUCCESS
        else:
            self.logger.warning(f'电池电量不足: {self.battery_level:.1%}')
            return py_trees.common.Status.FAILURE
            
    def terminate(self, new_status):
        """清理"""
        pass
 
 
class NavigateToPoseAction(py_trees_ros.actions.ActionClient):
    """导航动作客户端包装"""
    def __init__(self, name: str = "NavigateToPose"):
        super().__init__(
            name=name,
            action_type=NavigateToPose,
            action_name="navigate_to_pose",
            action_goal=NavigateToPose.Goal()
        )
 
 
def create_custom_behavior_tree() -> py_trees.trees.BehaviourTree:
    """创建自定义行为树"""
    root = py_trees.composites.Sequence("MainSequence", memory=True)
    
    # 电池检查
    battery_check = BatteryCheck()
    root.add_child(battery_check)
    
    # 导航(带恢复的备选)
    navigation = py_trees.composites.Selector("Navigation", memory=True)
    
    # 正常导航
    normal_nav = py_trees.composites.Sequence("NormalNav", memory=True)
    normal_nav.add_child(NavigateToPoseAction("GoToGoal"))
    
    # 恢复导航(清除代价地图后重试)
    recovery_nav = py_trees.composites.Sequence("RecoveryNav", memory=True)
    recovery_nav.add_child(
        py_trees_ros.actions.ServiceClient(
            name="ClearCostmap",
            service_type=ClearEntireCostmap,
            service_name="/global_costmap/clear_entirely"
        )
    )
    recovery_nav.add_child(NavigateToPoseAction("GoToGoalRetry"))
    
    navigation.add_child(normal_nav)
    navigation.add_child(recovery_nav)
    
    root.add_child(navigation)
    
    return py_trees.trees.BehaviourTree(root)
 
 
def run_custom_bt():
    """运行自定义行为树"""
    tree = create_custom_behavior_tree()
    tree.setup(timeout=10)
    
    running = True
    while running:
        tree.tick()
        py_trees.console.log_snapshot_ascii(tree)
        time.sleep(0.1)

20.4.3 装饰节点使用

<!-- 装饰节点应用示例 -->
<BehaviorTree>
  <Sequence>
    <!-- 带超时控制的导航 -->
    <Timeout msec="30000">
      <ComputePathToPose goal="{goal}" path="{path}"/>
    </Timeout>
    
    <!-- 带频率控制的路径跟踪 -->
    <RateController hz="10.0">
      <FollowPath path="{path}"/>
    </RateController>
    
    <!-- 重复检查直到成功 -->
    <RepeatUntilSuccess num_attempts="5">
      <Condition condition="is_goal_reached"/>
    </RepeatUntilSuccess>
    
    <!-- 反转条件 -->
    <Inverter>
      <Condition condition="obstacle_detected"/>
    </Inverter>
  </Sequence>
</BehaviorTree>

20.4.4 官方要点——自定义节点:nav2_behavior_tree 的 50 个内置节点与插件注册

Nav2 官方文档指出,nav2_behavior_tree 内置约 50 个 ROS 感知节点(IsPathValid、GoalUpdated、NavigateToPose、Wait、RateController 等),绝大多数业务无需自研。若要写练习第 3 题的 SpiralSearch,官方开发指南给出三步:继承 BT::ActionNodeBase(或 Nav2 的 RosActionNode 模板复用 Action 接口),实现 tick() 返回 SUCCESS/FAILURE/RUNNING 三态;在 CMake 里用 BT_PLUGIN_EXPORT 导出为动态库插件;在 XML 头部声明 <root main_tree_to_execute="..."> 并指定插件名(BT-Navigator 的 plugin_lib_names 参数),即可被 bt_navigator 热加载。

20.5 恢复行为配置与优化

20.5.1 恢复行为配置完整示例

behavior_server:
  ros__parameters:
    behavior_plugins: [
      "spin", "backup", "drive_on_heading", 
      "wait", "assisted_teleop"
    ]
    local_costmap_topic: "/local_costmap/costmap"
    global_costmap_topic: "/global_costmap/costmap"
    cycle_frequency: 10.0
    
    spin:
      plugin: "nav2_behaviors/Spin"
      simulate_ahead_time: 2.0
      max_rotational_vel: 1.0
      min_rotational_vel: 0.1
      rotational_acc_lim: 3.0
    
    backup:
      plugin: "nav2_behaviors/BackUp"
      simulate_ahead_time: 2.0
      max_linear_vel: 0.1
      min_linear_vel: 0.05
      linear_acc_lim: 0.5
    
    drive_on_heading:
      plugin: "nav2_behaviors/DriveOnHeading"
      simulate_ahead_time: 2.0
      max_linear_vel: 0.1
      min_linear_vel: 0.05
    
    wait:
      plugin: "nav2_behaviors/Wait"
      simulate_ahead_time: 2.0
    
    assisted_teleop:
      plugin: "nav2_behaviors/AssistedTeleop"
      simulate_ahead_time: 2.0
      max_linear_vel: 0.1

20.5.2 恢复行为策略

class RecoveryStrategy:
    """恢复策略管理器"""
    def __init__(self, node):
        self.node = node
        self.spin_client = ActionClient(node, Spin, '/spin')
        self.backup_client = ActionClient(node, BackUp, '/backup')
        self.recovery_sequence = [
            {'name': 'spin', 'angle': 1.57},
            {'name': 'wait', 'duration': 1.0},
            {'name': 'backup', 'distance': 0.15},
            {'name': 'spin', 'angle': 3.14},
            {'name': 'backup', 'distance': 0.3},
            {'name': 'wait', 'duration': 2.0},
        ]
        self.current_step = 0
        
    def attempt_recovery(self) -> bool:
        """执行恢复序列"""
        for step in self.recovery_sequence:
            success = self._execute_step(step)
            if success:
                self.node.get_logger().info(
                    f'恢复成功: {step["name"]}')
                self.current_step = 0
                return True
                
        self.node.get_logger().error('所有恢复行为失败')
        return False
    
    def _execute_step(self, step: dict) -> bool:
        """执行单个恢复步骤"""
        self.node.get_logger().info(
            f'执行恢复: {step["name"]}')
        
        if step['name'] == 'spin':
            return self._do_spin(step['angle'])
        elif step['name'] == 'backup':
            return self._do_backup(step['distance'])
        elif step['name'] == 'wait':
            return self._do_wait(step['duration'])
            
        return False
    
    def _do_spin(self, angle: float) -> bool:
        goal = Spin.Goal()
        goal.target.yaw = angle
        self.spin_client.wait_for_server()
        future = self.spin_client.send_goal_async(goal)
        # ... (等待结果)
        return True
    
    def _do_backup(self, distance: float) -> bool:
        goal = BackUp.Goal()
        goal.target.x = -distance
        self.backup_client.wait_for_server()
        future = self.backup_client.send_goal_async(goal)
        return True
    
    def _do_wait(self, duration: float) -> bool:
        self.node.get_logger().info(f'等待 {duration}s')
        time.sleep(duration)
        return True

20.5.3 恢复行为触发条件优化

# 代价地图清除配置
global_costmap:
  global_costmap:
    ros__parameters:
      # 当机器人位置与已知地图的代价超过阈值时触发清除
      footprint_padding: 0.01
      always_send_full_costmap: true
      
local_costmap:
  local_costmap:
    ros__parameters:
      # 滚动窗口的清除策略
      rolling_window: true
      width: 4
      height: 4

20.5.4 行为树调试

# 查看当前行为树状态
ros2 topic echo /bt_navigator/bt_status
 
# 查看导航状态(包括恢复行为执行情况)
ros2 topic echo /navigate_to_pose/_action/status
 
# 查看行为树节点执行日志
ros2 run rqt_bt_monitor rqt_bt_monitor
 
# 手动切换行为树
ros2 param set /bt_navigator \
  default_bt_xml_filename "custom_navigation.xml"

20.5.5 官方要点——Groot 可视化:编辑与在线调试

BehaviorTree.CPP 官方配套的 Groot(现 Groot2)是一款可视化编辑器:左侧拖拽节点搭树、右侧实时显示每个节点的状态颜色(运行中绿色、成功/失败红蓝),还能通过 zmq 与运行中的 bt_navigator 连接,把练习第 5 题"卡住观察"变成直观的树状态录像。The Construct 的课程演示了"先 Groot 建模 → 再导出 XML → 放入 Nav2 启动"的工业流程;Robotics Back-End 则展示了在树里插入日志节点定位卡死节点的排障方法——行为树调试不再是打印语句,而是树内状态审计。

20.6 实战案例

20.6.1 机器人巡逻行为树

<!-- patrol_bt.xml -->
<root main_tree_to_execute="MainTree">
  <BehaviorTree ID="MainTree">
    <Sequence>
      <!-- 全局重定位 -->
      <GlobalLocalization/>
      
      <!-- 巡逻循环 -->
      <Repeat num_cycles="-1">  <!-- 无限循环 -->
        <Sequence>
          <!-- 前往航点1 -->
          <ComputePathToPose goal="{waypoint1}" path="{path}"/>
          <FollowPath path="{path}"/>
          
          <!-- 到达后停留 -->
          <Wait wait_duration="5.0"/>
          
          <!-- 前往航点2 -->
          <ComputePathToPose goal="{waypoint2}" path="{path}"/>
          <FollowPath path="{path}"/>
          
          <Wait wait_duration="5.0"/>
          
          <!-- 返回航点1 -->
          <ComputePathToPose goal="{waypoint1}" path="{path}"/>
          <FollowPath path="{path}"/>
        </Sequence>
      </Repeat>
    </Sequence>
  </BehaviorTree>
</root>

20.6.2 多机器人调度集成

import rclpy
from rclpy.node import Node
from nav2_msgs.action import NavigateToPose
import yaml
 
class MultiRobotScheduler(Node):
    """多机器人调度器 - 集成行为树"""
    def __init__(self):
        super().__init__('multi_robot_scheduler')
        
        # 注册机器人客户端
        self.robots = {}
        robot_names = ['robot1', 'robot2', 'robot3']
        for name in robot_names:
            self.robots[name] = ActionClient(
                self, NavigateToPose, f'/{name}/navigate_to_pose')
        
        # 任务队列
        self.task_queue = []
        self.load_tasks('tasks.yaml')
        
    def load_tasks(self, task_file: str):
        """加载任务配置"""
        with open(task_file, 'r') as f:
            tasks = yaml.safe_load(f)
            self.task_queue = tasks['tasks']
            
    def dispatch_task(self, robot_name: str, task: dict):
        """派发任务到机器人"""
        if robot_name not in self.robots:
            return
            
        goal = NavigateToPose.Goal()
        goal.pose.header.frame_id = 'map'
        goal.pose.pose.position.x = task['x']
        goal.pose.pose.position.y = task['y']
        
        # 选择行为树
        if task.get('recovery_strategy') == 'aggressive':
            goal.behavior_tree = 'aggressive_recovery.xml'
        else:
            goal.behavior_tree = 'default_navigation.xml'
            
        client = self.robots[robot_name]
        client.wait_for_server()
        client.send_goal_async(goal)
        
        self.get_logger().info(
            f'派发任务给 {robot_name}: ({task["x"]}, {task["y"]})')

课后练习

  1. 原理题: 说明行为树中Sequence和Fallback节点的区别,列举在实际导航中哪些场景适合用Sequence、哪些适合用Fallback。

  2. 配置题: 编写一个自定义的行为树XML,实现以下功能:先检查电池电量,若电量充足则直接导航,若电量不足则先前往充电桩充电再导航。

  3. 编程题: 实现一个Python自定义恢复行为"SpiralSearch":当导航失败时,机器人以螺旋轨迹搜索周围环境,尝试找到可行路径。

  4. 分析题: 分析Nav2默认行为树的恢复策略设计,说明为什么先Spin再BackUp最后清除代价地图,解释这种恢复顺序的合理性。

  5. 操作题: 在仿真环境中制造导航卡住场景(如障碍物包围),观察恢复行为的执行过程,记录每种恢复行为的执行效果和耗时。

  6. 设计题: 设计一个分层的恢复行为策略:轻度故障(一次规划失败)→ 快速Spin重试,中度故障(连续失败)→ BackUp+重规划,重度故障(多次失败)→ 完全停止+请求人工干预。


仿真结合实例(当前仓库):Nav2 行为树组件与恢复服务

目标与知识点对应

在真实 Nav2 组件上观察 bt_navigator、规划器、控制器和 behavior_server 的启动关系,并通过服务列表确认恢复行为接口。

运行步骤

source /opt/ros/jazzy/setup.bash
source install/setup.bash
ros2 launch navigation_sim_demo_ros2 nav2_demo.launch.py \
  use_gazebo:=true use_rviz:=true gz_headless:=false
ros2 node info /bt_navigator
ros2 node info /behavior_server
ros2 service list | grep -E 'clear|spin|backup|wait'

观察结果

启动日志能显示行为树导航器和恢复行为服务器被加载;在 RViz 中发送目标后,可结合节点日志观察规划失败或控制器恢复路径。

源码与边界

Nav2 启动文件位于 src/navigation_sim_demo_ros2/launch/nav2_demo.launch.py,参数文件位于 src/navigation_sim_demo_ros2/params/nav2_params.yaml,生命周期启动脚本位于 src/navigation_sim_demo_ros2/navigation_sim_demo_ros2/nav2_lifecycle_runner.py。

本仓库没有专门的恢复行为故障注入演示;服务存在不等于某个恢复分支已经被触发。

学习材料: