Skip to content

15 · Behavior trees

⏱ 40 min · Level: intermediate · Script: isaac/15_behavior_tree.py · ROS: navigation.launch.py, patrol

Goal. Learn behavior trees, the way Nav2 and many robots organise their decisions. First read the tree that runs inside Nav2 and watch it work. Then write your own tree with py_trees: a patrol of the lime_room that is interrupted when the (pretend) battery runs low, and carries on after charging. Tutorial 16 uses the same building blocks for a much longer job.

The patrol: lookouts 1–3, where the robot looks around at each. On the way to lookout 4, the battery drops below 30 %: the tree interrupts the patrol, the robot charges in the west, finishes the patrol and comes home. It never touches the traffic cone.

Why a tree?

Tutorial 13's mission is a script: step 1, step 2, step 3, and if anything fails, stop. That is fine for one banana. A longer job needs more:

  • try again when something fails (the grasp missed);
  • try something else (that lookout can't be reached: skip it);
  • interrupt what you are doing for something more important (the battery is low), and carry on afterwards.

Written with ifs and flags, this becomes hard to read quickly. A behavior tree gives each of these patterns a name, and the mission becomes a tree of small, reusable pieces.

Concepts

The tree is ticked, about 10 times a second. A tick starts at the root and goes down to the behaviours that have work to do. Every behaviour that is ticked answers with one of three words:

Status Meaning
SUCCESS done, it worked
FAILURE done, it didn't work
RUNNING not done yet: tick me again

The leaves do the work (drive to the charger) or check something (is the battery low?). The nodes above them decide which leaf to tick:

Node Symbol What it does
Sequence → ticks its children in order; fails as soon as one fails. "Do this, then that."
Selector (Nav2: Fallback) ? ticks its children in order; succeeds as soon as one succeeds. "Try this, else that."
Decorator ◇ changes what its one child says: Retry (try again after a failure), Repeat, Inverter (swap SUCCESS and FAILURE), ForEach (once per item of a list), ...

The children's order is their priority. With memory, a Sequence or Selector continues with the child that was RUNNING at the last tick. Without memory, it starts again from its first child on every tick: a higher-priority child that now succeeds (the battery is low) can interrupt a lower one that was running (drive to the lookout). That is how a tree reacts.

Behaviours share data through the blackboard, a dictionary that every behaviour can read and write: the battery level, the next lookout, the thing to pick up.

Part 1: the tree inside Nav2

You have used a behavior tree since tutorial 11: Nav2's bt_navigator runs one for every goal. It is written in XML for BehaviorTree.CPP, and Jazzy ships several. The default one for NavigateToPose is navigate_to_pose_w_replanning_and_recovery.xml:

flowchart TD
  root{{"RecoveryNode · 6 retries<br/>NavigateRecovery"}} --> pipe["PipelineSequence<br/>NavigateWithReplanning"]
  root --> rec["Sequence → ReactiveFallback<br/>(only if a recovery can help)"]
  pipe --> rate["RateController · 1 Hz"] --> plan["ComputePathToPose<br/>(planner_server)"]
  pipe --> follow["FollowPath<br/>(controller_server, MPPI)"]
  rec --> rr["RoundRobin: one per failure"]
  rr --> c1["clear both costmaps"]
  rr --> c2["Spin 90°"]
  rr --> c3["Wait 5 s"]
  rr --> c4["BackUp 30 cm"]
  • PipelineSequence ticks the planner and the controller together: FollowPath keeps the robot moving along the current path while the RateController lets ComputePathToPose plan a new one once a second. That is why Nav2 steers round the traffic cone of tutorial 11 as soon as the LiDAR sees it.
  • RecoveryNode is a decorator-like node with two children: if the first fails, it ticks the second (a recovery) and then tries the first again, up to 6 times.
  • RoundRobin picks the next recovery each time: first clear the costmaps, then spin, then wait, then back up.
The XML: nav2_bt_navigator/behavior_trees/navigate_to_pose_w_replanning_and_recovery.xml
<!--
  This Behavior Tree replans the global path periodically at 1 Hz and it also has
  recovery actions specific to planning / control as well as general system issues.
  This will be continuous if a kinematically valid planner is selected.
-->
<root BTCPP_format="4" main_tree_to_execute="MainTree">
  <BehaviorTree ID="MainTree">
    <RecoveryNode number_of_retries="6" name="NavigateRecovery">
      <PipelineSequence name="NavigateWithReplanning">
        <ControllerSelector selected_controller="{selected_controller}" default_controller="FollowPath" topic_name="controller_selector"/>
        <PlannerSelector selected_planner="{selected_planner}" default_planner="GridBased" topic_name="planner_selector"/>
        <RateController hz="1.0">
          <RecoveryNode number_of_retries="1" name="ComputePathToPose">
            <ComputePathToPose goal="{goal}" path="{path}" planner_id="{selected_planner}" error_code_id="{compute_path_error_code}"/>
            <Sequence>
              <WouldAPlannerRecoveryHelp error_code="{compute_path_error_code}"/>
              <ClearEntireCostmap name="ClearGlobalCostmap-Context" service_name="global_costmap/clear_entirely_global_costmap"/>
            </Sequence>
          </RecoveryNode>
        </RateController>
        <RecoveryNode number_of_retries="1" name="FollowPath">
          <FollowPath path="{path}" controller_id="{selected_controller}" error_code_id="{follow_path_error_code}"/>
          <Sequence>
            <WouldAControllerRecoveryHelp error_code="{follow_path_error_code}"/>
            <ClearEntireCostmap name="ClearLocalCostmap-Context" service_name="local_costmap/clear_entirely_local_costmap"/>
          </Sequence>
        </RecoveryNode>
      </PipelineSequence>
      <Sequence>
        <Fallback>
          <WouldAControllerRecoveryHelp error_code="{follow_path_error_code}"/>
          <WouldAPlannerRecoveryHelp error_code="{compute_path_error_code}"/>
        </Fallback>
        <ReactiveFallback name="RecoveryFallback">
          <GoalUpdated/>
          <RoundRobin name="RecoveryActions">
            <Sequence name="ClearingActions">
              <ClearEntireCostmap name="ClearLocalCostmap-Subtree" service_name="local_costmap/clear_entirely_local_costmap"/>
              <ClearEntireCostmap name="ClearGlobalCostmap-Subtree" service_name="global_costmap/clear_entirely_global_costmap"/>
            </Sequence>
            <Spin spin_dist="1.57" error_code_id="{spin_error_code}"/>
            <Wait wait_duration="5.0"/>
            <BackUp backup_dist="0.30" backup_speed="0.15" error_code_id="{backup_code_id}"/>
          </RoundRobin>
        </ReactiveFallback>
      </Sequence>
    </RecoveryNode>
  </BehaviorTree>
</root>

Watch it tick

bt_navigator publishes every change of status on /behavior_tree_log. Start tutorial 11 (Isaac Sim and navigation.launch.py), and in a third terminal:

./docker/run_ros.sh ros2 topic echo /behavior_tree_log nav2_msgs/msg/BehaviorTreeLog

Send tutorial 11's goal and watch the nodes change. Each message lists the nodes whose status changed in one tick; abridged to node: before → after, the first second looks like this:

# t = 12.77 s   the goal arrives
NavigateRecovery         IDLE     -> RUNNING
RateController           IDLE     -> RUNNING
ComputePathToPose        IDLE     -> RUNNING      (the planner starts)
NavigateWithReplanning   IDLE     -> RUNNING
# t = 12.80 s
ComputePathToPose        RUNNING  -> SUCCESS      (a path)
RateController           RUNNING  -> SUCCESS
FollowPath               IDLE     -> RUNNING      (the controller starts driving)
# t = 13.77 s   one second later
ComputePathToPose        IDLE     -> RUNNING      (plan again, while FollowPath keeps RUNNING)
# t = 13.78 s
ComputePathToPose        RUNNING  -> SUCCESS

That is the PipelineSequence at work: FollowPath stays RUNNING the whole way, and once a second the RateController lets ComputePathToPose run again. (There are two nodes named ComputePathToPose: the RecoveryNode round it has the same name.) The topic needs the message type on the command line when it is not published yet.

Seeing the tree

Groot2 (a free download from BehaviorTree.CPP's authors) opens these XML files as diagrams and lets you edit them. Nav2 can also run your XML: put its path in the goal's behavior_tree field, or set default_nav_to_pose_bt_xml in nav2_params.yaml.

Part 2: your own tree with py_trees

Nav2's tree drives the robot to one goal. Above it, the mission decides which goals, in which order, and what to do when something goes wrong. Missions change more often than navigation, so we write them in Python with py_trees (the ROS 2 Jazzy package ros-jazzy-py-trees, already in the container).

The job: visit four lookouts and come home. The Lime's battery is pretend: it loses 5 % per metre driven. When it is below 30 %, the robot interrupts the patrol, drives to the charger, charges, and carries on.

flowchart TD
  root["→ Lime patrol<br/>(Sequence, no memory)"] --> bat(["Battery<br/>writes the level"])
  root --> what["? What now?<br/>(Selector, no memory)"]
  what --> then{{"◇ Then go on<br/>(SuccessIsRunning)"}} --> rech["→ Recharge"]
  rech --> low(["Battery below 30 %?"])
  rech --> gocharge(["Go to the charger<br/>Nav2"])
  rech --> charge(["Charge"])
  what --> patrol["→ Patrol"]
  patrol --> each{{"◇ Every lookout<br/>(ForEach)"}} --> visit["? Visit it"]
  visit --> been(["Been there already?"])
  visit --> go["→ Go there"]
  go --> nav(["Go to the lookout<br/>Nav2"])
  go --> look(["Look around<br/>turn once"])
  go --> off(["Check it off"])
  patrol --> home(["Go home<br/>Nav2"])

Read it from the top, the way the tree is ticked:

  1. Battery runs on every tick and writes the battery level to the blackboard. It is a sensor, not a decision: it always says SUCCESS.
  2. What now? is a Selector without memory: on every tick it asks its children again, from the left. Recharge comes first, so it has priority. As long as the battery is fine, Battery below 30 %? fails, so Recharge fails and the Selector goes on to Patrol.
  3. Patrol visits every lookout (ForEach puts one after the other on the blackboard as lookout), then goes home.
  4. When the battery drops below 30 %, Recharge succeeds at its first child and says RUNNING. The Selector switches to it and stops the running patrol: py_trees calls terminate() on Go to the lookout, which cancels its Nav2 goal.
  5. After charging, Recharge succeeds. Then go on turns that SUCCESS into RUNNING, so the tree is not finished: on the next tick the Selector asks again, Recharge fails (battery full), and Patrol starts again from its first lookout. Been there already? skips the lookouts that are checked off, so the patrol continues where it was interrupted.

Long actions: a thread per action

A tick must be quick, but driving to a lookout takes a minute. So every long action (Action) runs in a background thread: the first tick starts it, every later tick asks "done yet?" (RUNNING until it is), and terminate() asks it to stop when the tree interrupts it.

Action, TurnAround and NavigateTo in lime_isaac_bringup/scripts/lime_bt.py

class Action(py_trees.behaviour.Behaviour):
    """A long action, in a background thread. Subclasses write run(): return True for success, False for
    failure, and look at self.stop_requested now and then to stop early when the tree interrupts them."""

    robot = threading.Lock()  # one robot: one action at a time

    def __init__(self, name):
        super().__init__(name)
        self.thread, self.result, self.stop_requested = None, None, False

    def initialise(self):  # first tick: start the action
        self.result, self.stop_requested = None, False
        self.thread = threading.Thread(target=self._run, daemon=True)
        self.thread.start()

    def _run(self):
        try:
            with Action.robot:  # an interrupted action may still be stopping (cancelling its Nav2 goal)
                self.result = bool(self.run())
        except Exception as e:  # an exception is a failure, not a crash of the whole tree
            self.feedback_message = f"{type(e).__name__}: {e}"
            self.result = False

    def update(self):  # every tick: done yet?
        if self.thread.is_alive():
            return Status.RUNNING
        return Status.SUCCESS if self.result else Status.FAILURE

    def terminate(self, new_status):  # finished, or interrupted by the tree (new_status = INVALID)
        if new_status == Status.INVALID and self.thread is not None and self.thread.is_alive():
            self.stop_requested = True
            self.thread.join()

    def run(self) -> bool:
        raise NotImplementedError
class TurnAround(Action):
    """Turn round once on the spot, in four quarter turns (with tutorial 13's turn_to(), odometry)."""

    def __init__(self, name, lime):
        super().__init__(name)
        self.lime = lime

    def run(self):
        _, _, yaw = self.lime.pose()
        for k in range(1, 5):
            if self.stop_requested:
                return False
            self.lime.turn_to(yaw + k * math.pi / 2)
        return True


class NavigateTo(Action):
    """Drive to a pose (x, y, yaw) in the map frame with Nav2. The pose comes from the blackboard (key) or is
    fixed (pose). Interrupted, it cancels the Nav2 goal."""

    def __init__(self, name, lime, key=None, pose=None):
        super().__init__(name)
        self.lime, self.pose = lime, pose
        if key:
            self.key = key
            self.blackboard = self.attach_blackboard_client(name=name)
            self.blackboard.register_key(key=key, access=py_trees.common.Access.READ)

    def run(self):
        x, y, yaw = self.pose if self.pose else self.blackboard.get(self.key)
        goal = PoseStamped()
        goal.header.frame_id = "map"
        goal.header.stamp = self.lime.nav.get_clock().now().to_msg()
        goal.pose.position.x, goal.pose.position.y = float(x), float(y)
        goal.pose.orientation.z, goal.pose.orientation.w = math.sin(yaw / 2), math.cos(yaw / 2)
        if not self.lime.nav.goToPose(goal):
            return False
        while not self.lime.nav.isTaskComplete():  # spins the node for up to 0.1 s
            if self.stop_requested:
                self.lime.nav.cancelTask()
                return False
        return self.lime.nav.getResult() == TaskResult.SUCCEEDED

The battery and the lookouts are small behaviours that finish in one tick:

Battery, Charge, BeenThere, CheckOff in patrol.py

class Battery(py_trees.behaviour.Behaviour):
    """Writes the battery level to the blackboard on every tick. The Lime's battery is pretend: it runs down by
    DRAIN % per metre driven (measured with odometry). Always SUCCESS: it is a sensor, not a decision."""

    def __init__(self, lime):
        super().__init__("Battery")
        self.lime, self.last = lime, None
        self.blackboard = self.attach_blackboard_client(name="Battery")
        self.blackboard.register_key(key="battery", access=Access.WRITE)
        self.blackboard.battery = 100.0

    def update(self):
        x, y, _ = self.lime.pose()
        if self.last is not None:
            self.blackboard.battery = max(0.0, self.blackboard.battery - DRAIN * math.hypot(x - self.last[0], y - self.last[1]))
        self.last = (x, y)
        self.feedback_message = f"{self.blackboard.battery:.0f} %"
        return Status.SUCCESS


class Charge(py_trees.behaviour.Behaviour):
    """Charge until full: +20 % per second. RUNNING while charging."""

    def __init__(self, log):
        super().__init__("Charge")
        self.log = log
        self.blackboard = self.attach_blackboard_client(name="Charge")
        self.blackboard.register_key(key="battery", access=Access.WRITE)

    def update(self):
        self.blackboard.battery = min(100.0, self.blackboard.battery + 2.0)  # one tick = 0.1 s
        if self.blackboard.battery < 100.0:
            return Status.RUNNING
        self.log.info("battery full")
        return Status.SUCCESS
class BeenThere(py_trees.behaviour.Behaviour):
    """Condition: is the current lookout checked off already? (After a recharge the patrol starts again
    from the first lookout, and skips the ones it has visited.)"""

    def __init__(self):
        super().__init__("Been there already?")
        self.blackboard = self.attach_blackboard_client(name=self.name)
        self.blackboard.register_key(key="lookout", access=Access.READ)
        self.blackboard.register_key(key="visited", access=Access.READ)

    def update(self):
        return Status.SUCCESS if self.blackboard.lookout in self.blackboard.visited else Status.FAILURE


class CheckOff(py_trees.behaviour.Behaviour):
    def __init__(self, log):
        super().__init__("Check it off")
        self.log = log
        self.blackboard = self.attach_blackboard_client(name=self.name)
        self.blackboard.register_key(key="lookout", access=Access.READ)
        self.blackboard.register_key(key="visited", access=Access.WRITE)
        self.blackboard.register_key(key="battery", access=Access.READ)

    def update(self):
        self.blackboard.visited = self.blackboard.visited + [self.blackboard.lookout]
        x, y, _ = self.blackboard.lookout
        self.log.info(f"lookout ({x}, {y}) checked, battery {self.blackboard.battery:.0f} %")
        return Status.SUCCESS

And the tree itself, exactly as drawn above:

def build_tree(lime, log):
    blackboard = py_trees.blackboard.Client(name="patrol")
    for key in ("lookouts", "visited"):
        blackboard.register_key(key=key, access=Access.WRITE)
    blackboard.lookouts, blackboard.visited = LOOKOUTS, []

    battery_low = py_trees.behaviours.CheckBlackboardVariableValue(
        name=f"Battery below {LOW:.0f} %?", check=ComparisonExpression(variable="battery", value=LOW, operator=operator.lt)
    )
    recharge = py_trees.composites.Sequence("Recharge", memory=True, children=[
        battery_low,
        NavigateTo("Go to the charger", lime, pose=CHARGER),
        Charge(log),
    ])
    visit = py_trees.composites.Selector("Visit it", memory=False, children=[
        BeenThere(),
        py_trees.composites.Sequence("Go there", memory=True, children=[
            NavigateTo("Go to the lookout", lime, key="lookout"),
            TurnAround("Look around", lime),
            CheckOff(log),
        ]),
    ])
    patrol = py_trees.composites.Sequence("Patrol", memory=True, children=[
        py_trees.decorators.ForEach("Every lookout", visit, source_key="lookouts", target_key="lookout"),
        NavigateTo("Go home", lime, pose=HOME),
    ])
    what_now = py_trees.composites.Selector("What now?", memory=False, children=[
        py_trees.decorators.SuccessIsRunning("Then go on", recharge),  # after charging: carry on patrolling
        patrol,
    ])
    return py_trees.composites.Sequence("Lime patrol", memory=False, children=[Battery(lime), what_now])

run_tree() ticks it 10 times a second until the root succeeds or fails, and prints every behaviour that starts (...), succeeds (ok), fails (FAIL) or is interrupted by the tree (stop):

run_tree() in lime_bt.py
def run_tree(root, log, period=0.1):
    """Tick the tree until it succeeds or fails. Print every behaviour that starts (...), succeeds (ok), fails
    (FAIL) or is interrupted by the tree (stop)."""
    tree = py_trees.trees.BehaviourTree(root)
    tree.setup(timeout=15.0)
    log.info("the tree:\n" + py_trees.display.unicode_tree(root))
    before, started = {}, {}
    while True:
        tree.tick()
        for b in root.iterate():
            if isinstance(b, (py_trees.composites.Composite, py_trees.decorators.Decorator)) or b.status == before.get(b.id):
                continue
            if b.status == Status.RUNNING:
                started[b.id] = time.time()
                log.info(f"[bt] ... {b.name}")
            elif b.status in (Status.SUCCESS, Status.FAILURE):
                begin = started.pop(b.id, None)
                took = f" ({time.time() - begin:.0f} s)" if begin and time.time() - begin > 1 else ""
                # say why an action failed, or what a decision of ours chose (not py_trees' own condition messages)
                ours = not type(b).__module__.startswith("py_trees")
                why = f": {b.feedback_message}" if ours and b.feedback_message and (b.status == Status.FAILURE) == isinstance(b, Action) else ""
                log.info(f"[bt] {'ok  ' if b.status == Status.SUCCESS else 'FAIL'} {b.name}{took}{why}")
            elif b.status == Status.INVALID and before.get(b.id) == Status.RUNNING:
                started.pop(b.id, None)
                log.info(f"[bt] stop {b.name} (interrupted)")
            before[b.id] = b.status
        if root.status in (Status.SUCCESS, Status.FAILURE):
            log.info("the tree at the end:\n" + py_trees.display.unicode_tree(root, show_status=True))
            return root.status
        time.sleep(period)

Run it

Terminal 1, Isaac Sim (tutorial 11's world: the mapped room and the traffic cone):

source scripts/isaac_env.sh
python isaac/15_behavior_tree.py

Terminal 2, Nav2 + RViz (tutorial 11, unchanged):

./scripts/build_ws.sh lime_isaac_bringup     # once: installs the patrol
./docker/run_ros.sh ros2 launch lime_isaac_bringup navigation.launch.py

Terminal 3, the patrol (wait for "Managed nodes are active" in terminal 2):

./docker/run_ros.sh ros2 run lime_isaac_bringup patrol

The patrol prints the tree once at the start (py_trees' symbols: [-] Sequence, [o] Selector, {-} Sequence with memory, -^- decorator, --> behaviour), then every behaviour that starts (...), succeeds (ok), fails (FAIL) or is interrupted (stop):

[-] Lime patrol
    --> Battery
    [o] What now?
        -^- Then go on
            {-} Recharge
                --> Battery below 30 %?
                --> Go to the charger
                --> Charge
        {-} Patrol
            -^- Every lookout
                [o] Visit it
                    --> Been there already?
                    {-} Go there
                        --> Go to the lookout
                        --> Look around
                        --> Check it off
            --> Go home
[bt] ok   Battery: 100 %
[bt] FAIL Battery below 30 %?
[bt] FAIL Been there already?
[bt] ... Go to the lookout
[bt] ok   Go to the lookout (20 s)
[bt] ... Look around
lookout (3.2, -1.8) checked, battery 80 %
[bt] ok   Look around (20 s)
[bt] ok   Check it off
[bt] ... Go to the lookout
[bt] ok   Go to the lookout (16 s)
[bt] ... Look around
lookout (3.3, 1.9) checked, battery 62 %
[bt] ok   Look around (20 s)
[bt] ok   Check it off
[bt] ... Go to the lookout
[bt] ok   Go to the lookout (30 s)
[bt] ... Look around
lookout (0.5, 1.9) checked, battery 40 %
[bt] ok   Look around (19 s)
[bt] ok   Check it off
[bt] ... Go to the lookout
[bt] ok   Battery below 30 %?
[bt] ... Go to the charger
[bt] stop Go to the lookout (interrupted)
[bt] ok   Go to the charger (8 s)
[bt] ... Charge
battery full
[bt] ok   Charge (4 s)
[bt] FAIL Battery below 30 %?
[bt] ok   Been there already?
[bt] FAIL Been there already?
[bt] ... Go to the lookout
[bt] ok   Go to the lookout (10 s)
[bt] ... Look around
lookout (-1.3, -1.8) checked, battery 91 %
[bt] ok   Look around (19 s)
[bt] ok   Check it off
[bt] ... Go home
[bt] ok   Go home (13 s)
patrol complete

Follow the interruption: on the way to lookout 4, Battery below 30 %? succeeds. The Selector switches to Recharge, and the running Go to the lookout is stopped (its Nav2 goal is cancelled). After charging, the patrol starts again from the first lookout: Been there already? succeeds for lookouts 1–3 (one per tick; the log shows a status only when it changes), fails for lookout 4, and the robot drives there.

Automatic check

python isaac/15_behavior_tree.py --headless --test follows the patrol with the simulation's ground truth: it notes every lookout and the charger the robot comes to, and checks the order. tools/run_all_checks.sh 15 starts Nav2 and the patrol:

[15] at lookout 1, t = 29 s
[15] at lookout 2, t = 63 s
[15] at lookout 3, t = 108 s
[15] at charger, t = 146 s
[15] at lookout 4, t = 160 s
[15] back home, t = 192 s
[15][check] ok   the four lookouts in order (lookout 1, lookout 2, lookout 3, charger, lookout 4)
[15][check] ok   one stop at the charger, between two lookouts
[15][check] ok   back home at the end
[15][check] ok   cone not touched (moved 0.0 cm)
[15][test] PASS
Isaac Sim side: isaac/15_behavior_tree.py
# SPDX-FileCopyrightText: 2026 An (an-robotics)
# SPDX-License-Identifier: Apache-2.0

"""Tutorial 15 - Behavior trees: a patrol with Nav2, interrupted by a (pretend) low battery.

    source scripts/isaac_env.sh
    python isaac/15_behavior_tree.py

    # ROS 2 container: Nav2 + RViz (tutorial 11), then the patrol - a behavior tree
    ./docker/run_ros.sh ros2 launch lime_isaac_bringup navigation.launch.py
    ./docker/run_ros.sh ros2 run lime_isaac_bringup patrol

The world of tutorial 11: the lime_room as it was mapped, plus the traffic cone that is not in the map.
Nothing new on the Isaac Sim side: the behavior tree runs in ROS 2 and only sends Nav2 goals.
--test follows the patrol with the simulation's ground truth: the four lookouts in order, one stop at the
charger, back home, and the cone not touched.
"""

import sys

from common.cli import parse_args

args = parse_args(__doc__.splitlines()[0])

from isaacsim import SimulationApp

simulation_app = SimulationApp({"headless": args.headless, "width": 1280, "height": 720})

import isaacsim.core.experimental.utils.app as app_utils
import isaacsim.core.experimental.utils.stage as stage_utils
import numpy as np
from common import graphs, lime, sensors
from common.scene import add_traffic_cone, build_lime_room
from isaacsim.core.experimental.prims import Articulation, XformPrim
from isaacsim.core.simulation_manager import SimulationManager

graphs.enable_ros2_realtime(simulation_app)

stage = stage_utils.create_new_stage(template="empty")
build_lime_room(stage, with_objects=False)  # tutorial 11: the room as it was mapped
cone = add_traffic_cone(stage)  # ... and the traffic cone that is not in the map
while stage_utils.is_stage_loading():
    simulation_app.update()
robot_path = "/World/turtlebot3_lime"
articulation_root = lime.add_lime(robot_path)

graphs.create_clock_graph()  # 06
graphs.create_drive_graph(articulation_root)  # 06  /cmd_vel
graphs.create_odom_tf_joint_states_graph(articulation_root)  # 07  /odom /tf /joint_states
graphs.create_lidar_graph(sensors.add_lds_lidar(robot_path))  # 09  /scan

recorder = None
if args.record:
    from common.recorder import Recorder

    recorder = Recorder(args.record, eye=(1.0, -4.6, 4.6), target=(0.9, 0.0, 0.0), every_n=12, fps=20)

SimulationManager.setup_simulation(dt=1.0 / 60.0)
app_utils.play()
simulation_app.update()
robot = Articulation(articulation_root)
print("[15] ready: start Nav2 (ros2 launch lime_isaac_bringup navigation.launch.py), then ros2 run lime_isaac_bringup patrol", flush=True)

# the places of the patrol (patrol.py): where the robot must stop, in this order (the charger somewhere in between)
PLACES = {"lookout 1": (3.2, -1.8), "lookout 2": (3.3, 1.9), "lookout 3": (0.5, 1.9), "lookout 4": (-1.3, -1.8), "charger": (-1.5, 0.0)}
HOME = np.array([0.0, 0.0])
visits, steps, here, still = [], 0, None, 0
cone_prim = XformPrim(cone)
rest = None
while simulation_app.is_running():
    simulation_app.update()
    steps += 1
    if recorder:
        recorder.capture()
    if args.test or args.record:
        if steps == 60:  # the cone has settled
            rest = cone_prim.get_world_poses()[0].numpy()[0].copy()
        xy = robot.get_world_poses()[0].numpy()[0, :2]
        near = next((name for name, p in PLACES.items() if np.linalg.norm(xy - p) < 0.3), None)
        if near and near != here and visits[-1:] != [near]:  # came to a place
            visits.append(near)
            print(f"[15] at {near}, t = {steps / 60:.0f} s", flush=True)
        here = near
        speed = np.linalg.norm(robot.get_velocities()[0].numpy()[0, :2])
        home = len([v for v in visits if v.startswith("lookout")]) == 4 and np.linalg.norm(xy - HOME) < 0.3
        still = still + 1 if home and speed < 0.02 else 0
        if still == 60:
            print(f"[15] back home, t = {steps / 60:.0f} s", flush=True)
        if still > 180 or steps > 600 * 60:
            break

ok = True
if args.test:
    lookouts = [v for v in visits if v.startswith("lookout")]
    checks = {
        f"the four lookouts in order ({', '.join(visits)})": lookouts == ["lookout 1", "lookout 2", "lookout 3", "lookout 4"],
        "one stop at the charger, between two lookouts": visits.count("charger") == 1 and 0 < visits.index("charger") < len(visits) - 1,
        "back home at the end": still > 180,
    }
    moved = np.linalg.norm(cone_prim.get_world_poses()[0].numpy()[0] - rest)
    checks[f"cone not touched (moved {moved * 100:.1f} cm)"] = moved < 0.01
    for text, passed in checks.items():
        print(f"[15][check] {'ok  ' if passed else 'FAIL'} {text}")
    ok = all(checks.values())
    print(f"[15][test] {'PASS' if ok else 'FAIL'}")
if recorder:
    recorder.save()
app_utils.stop()
simulation_app.close(exit_code=0 if ok else 1)
sys.exit(0 if ok else 1)
The whole patrol: lime_isaac_bringup/scripts/patrol.py
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2026 An (an-robotics)
# SPDX-License-Identifier: Apache-2.0

"""Tutorial 15 mission: a patrol, written as a behavior tree (py_trees).

    ros2 run lime_isaac_bringup patrol
    ros2 run lime_isaac_bringup patrol --render DIR     # only draw the tree (DIR/patrol.png), no robot needed

The Lime visits four lookouts with Nav2, looks around at each, then goes home. It has a (pretend) battery that runs down as it
drives. When the battery is low, the tree interrupts the patrol, sends the robot to the charger, and then
continues the patrol where it was interrupted.
"""

import argparse
import math
import operator
import os
import sys

import py_trees
import rclpy
from geometry_msgs.msg import PoseStamped
from py_trees.common import Access, ComparisonExpression, Status

sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))  # tutorial 13's mission.py, lime_bt.py
from lime_bt import NavigateTo, TurnAround, run_tree  # noqa: E402

LOOKOUTS = [(3.2, -1.8, 0.0), (3.3, 1.9, math.pi / 2), (0.5, 1.9, math.pi), (-1.3, -1.8, -math.pi / 2)]  # x, y, yaw
CHARGER = (-1.5, 0.0, math.pi)
HOME = (0.0, 0.0, 0.0)
DRAIN = 5.0  # % per metre driven (a pretend battery)
LOW = 30.0  # %


class Battery(py_trees.behaviour.Behaviour):
    """Writes the battery level to the blackboard on every tick. The Lime's battery is pretend: it runs down by
    DRAIN % per metre driven (measured with odometry). Always SUCCESS: it is a sensor, not a decision."""

    def __init__(self, lime):
        super().__init__("Battery")
        self.lime, self.last = lime, None
        self.blackboard = self.attach_blackboard_client(name="Battery")
        self.blackboard.register_key(key="battery", access=Access.WRITE)
        self.blackboard.battery = 100.0

    def update(self):
        x, y, _ = self.lime.pose()
        if self.last is not None:
            self.blackboard.battery = max(0.0, self.blackboard.battery - DRAIN * math.hypot(x - self.last[0], y - self.last[1]))
        self.last = (x, y)
        self.feedback_message = f"{self.blackboard.battery:.0f} %"
        return Status.SUCCESS


class Charge(py_trees.behaviour.Behaviour):
    """Charge until full: +20 % per second. RUNNING while charging."""

    def __init__(self, log):
        super().__init__("Charge")
        self.log = log
        self.blackboard = self.attach_blackboard_client(name="Charge")
        self.blackboard.register_key(key="battery", access=Access.WRITE)

    def update(self):
        self.blackboard.battery = min(100.0, self.blackboard.battery + 2.0)  # one tick = 0.1 s
        if self.blackboard.battery < 100.0:
            return Status.RUNNING
        self.log.info("battery full")
        return Status.SUCCESS


class BeenThere(py_trees.behaviour.Behaviour):
    """Condition: is the current lookout checked off already? (After a recharge the patrol starts again
    from the first lookout, and skips the ones it has visited.)"""

    def __init__(self):
        super().__init__("Been there already?")
        self.blackboard = self.attach_blackboard_client(name=self.name)
        self.blackboard.register_key(key="lookout", access=Access.READ)
        self.blackboard.register_key(key="visited", access=Access.READ)

    def update(self):
        return Status.SUCCESS if self.blackboard.lookout in self.blackboard.visited else Status.FAILURE


class CheckOff(py_trees.behaviour.Behaviour):
    def __init__(self, log):
        super().__init__("Check it off")
        self.log = log
        self.blackboard = self.attach_blackboard_client(name=self.name)
        self.blackboard.register_key(key="lookout", access=Access.READ)
        self.blackboard.register_key(key="visited", access=Access.WRITE)
        self.blackboard.register_key(key="battery", access=Access.READ)

    def update(self):
        self.blackboard.visited = self.blackboard.visited + [self.blackboard.lookout]
        x, y, _ = self.blackboard.lookout
        self.log.info(f"lookout ({x}, {y}) checked, battery {self.blackboard.battery:.0f} %")
        return Status.SUCCESS


def build_tree(lime, log):
    blackboard = py_trees.blackboard.Client(name="patrol")
    for key in ("lookouts", "visited"):
        blackboard.register_key(key=key, access=Access.WRITE)
    blackboard.lookouts, blackboard.visited = LOOKOUTS, []

    battery_low = py_trees.behaviours.CheckBlackboardVariableValue(
        name=f"Battery below {LOW:.0f} %?", check=ComparisonExpression(variable="battery", value=LOW, operator=operator.lt)
    )
    recharge = py_trees.composites.Sequence("Recharge", memory=True, children=[
        battery_low,
        NavigateTo("Go to the charger", lime, pose=CHARGER),
        Charge(log),
    ])
    visit = py_trees.composites.Selector("Visit it", memory=False, children=[
        BeenThere(),
        py_trees.composites.Sequence("Go there", memory=True, children=[
            NavigateTo("Go to the lookout", lime, key="lookout"),
            TurnAround("Look around", lime),
            CheckOff(log),
        ]),
    ])
    patrol = py_trees.composites.Sequence("Patrol", memory=True, children=[
        py_trees.decorators.ForEach("Every lookout", visit, source_key="lookouts", target_key="lookout"),
        NavigateTo("Go home", lime, pose=HOME),
    ])
    what_now = py_trees.composites.Selector("What now?", memory=False, children=[
        py_trees.decorators.SuccessIsRunning("Then go on", recharge),  # after charging: carry on patrolling
        patrol,
    ])
    return py_trees.composites.Sequence("Lime patrol", memory=False, children=[Battery(lime), what_now])


def main():
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--render", metavar="DIR", help="only draw the tree into DIR (patrol.png / .svg / .dot)")
    args, _ros = parser.parse_known_args()
    if args.render:
        py_trees.display.render_dot_tree(build_tree(None, None), target_directory=args.render, name="patrol")
        return

    from mission import Lime, wait_until_nav2_active  # tutorial 13: Nav2 (BasicNavigator), TF, odometry pose

    rclpy.init()
    lime = Lime()
    start = PoseStamped()
    start.header.frame_id = "map"
    start.header.stamp = lime.nav.get_clock().now().to_msg()
    start.pose.orientation.w = 1.0
    lime.nav.setInitialPose(start)  # the robot starts at the map origin
    wait_until_nav2_active(lime.nav)
    status = run_tree(build_tree(lime, lime.log), lime.log)
    lime.log.info("patrol complete" if status == Status.SUCCESS else "patrol FAILED")
    lime.close()
    sys.exit(0 if status == Status.SUCCESS else 1)


if __name__ == "__main__":
    main()

Troubleshooting

Symptom Fix
RuntimeError: Executor is already spinning Two actions used the robot's ROS node at once: py_trees starts the new action before it stops the interrupted one. Action takes a lock (Action.robot), so the new action waits until the old one has cancelled its Nav2 goal.
The patrol starts from the first lookout again after charging That is what the tree does; Been there already? must skip the visited lookouts. Check that Check it off runs (it is the last child of Go there).
ModuleNotFoundError: No module named 'py_trees' Your container image is older than tutorial 15, which added py_trees to it. Rebuild it and restart the container: docker build -t lime_ros_jazzy:latest docker/ros_jazzy, then docker stop lime_ros (the next ./docker/run_ros.sh starts the new one).
The patrol waits forever at the start Nav2 is not active yet: wait for "Managed nodes are active". Is the simulation playing?

Next: 16 · All together: tidy the room