        * [ SimpleGoalChecker ](../../configuration/packages/nav2_controller-plugins/simple_goal_checker.html)
        * [ StoppedGoalChecker ](../../configuration/packages/nav2_controller-plugins/stopped_goal_checker.html)
      * [ Default Plugins ](../../configuration/packages/configuring-controller-server.html#default-plugins)
      * [ Example ](../../configuration/packages/configuring-controller-server.html#example)
    * [ DWB Controller ](../../configuration/packages/configuring-dwb-controller.html)
      * [ Controller ](../../configuration/packages/configuring-dwb-controller.html#controller)
        * [ DWB Controller ](../../configuration/packages/dwb-params/controller.html)
        * [ XYTheta Iterator ](../../configuration/packages/dwb-params/iterator.html)
        * [ Kinematic Parameters ](../../configuration/packages/dwb-params/kinematic.html)
        * [ Publisher ](../../configuration/packages/dwb-params/visualization.html)
      * [ Plugins ](../../configuration/packages/configuring-dwb-controller.html#plugins)
        * [ LimitedAccelGenerator ](../../configuration/packages/dwb-plugins/limited_accel_generator.html)
        * [ StandardTrajectoryGenerator ](../../configuration/packages/dwb-plugins/standard_traj_generator.html)
      * [ Trajectory Critics ](../../configuration/packages/configuring-dwb-controller.html#trajectory-critics)
        * [ BaseObstacleCritic ](../../configuration/packages/trajectory_critics/base_obstacle.html)
        * [ GoalAlignCritic ](../../configuration/packages/trajectory_critics/goal_align.html)
        * [ GoalDistCritic ](../../configuration/packages/trajectory_critics/goal_dist.html)
        * [ ObstacleFootprintCritic ](../../configuration/packages/trajectory_critics/obstacle_footprint.html)
        * [ OscillationCritic ](../../configuration/packages/trajectory_critics/oscillation.html)
        * [ PathAlignCritic ](../../configuration/packages/trajectory_critics/path_align.html)
        * [ PathDistCritic ](../../configuration/packages/trajectory_critics/path_dist.html)
        * [ PreferForwardCritic ](../../configuration/packages/trajectory_critics/prefer_forward.html)
        * [ RotateToGoalCritic ](../../configuration/packages/trajectory_critics/rotate_to_goal.html)
        * [ TwirlingCritic ](../../configuration/packages/trajectory_critics/twirling.html)
      * [ Example ](../../configuration/packages/configuring-dwb-controller.html#example)
    * [ Regulated Pure Pursuit ](../../configuration/packages/configuring-regulated-pp.html)
      * [ Regulated Pure Pursuit Parameters ](../../configuration/packages/configuring-regulated-pp.html#regulated-pure-pursuit-parameters)
      * [ Example ](../../configuration/packages/configuring-regulated-pp.html#example)
    * [ Model Predictive Path Integral Controller ](../../configuration/packages/configuring-mppic.html)
      * [ MPPI Parameters ](../../configuration/packages/configuring-mppic.html#mppi-parameters)
        * [ Trajectory Visualization ](../../configuration/packages/configuring-mppic.html#trajectory-visualization)
        * [ Path Handler ](../../configuration/packages/configuring-mppic.html#path-handler)
        * [ Ackermann Motion Model ](../../configuration/packages/configuring-mppic.html#ackermann-motion-model)
        * [ Constraint Critic ](../../configuration/packages/configuring-mppic.html#constraint-critic)
        * [ Goal Angle Critic ](../../configuration/packages/configuring-mppic.html#goal-angle-critic)
        * [ Goal Critic ](../../configuration/packages/configuring-mppic.html#goal-critic)
        * [ Obstacles Critic ](../../configuration/packages/configuring-mppic.html#obstacles-critic)
        * [ Cost Critic ](../../configuration/packages/configuring-mppic.html#cost-critic)
        * [ Path Align Critic ](../../configuration/packages/configuring-mppic.html#path-align-critic)
        * [ Path Angle Critic ](../../configuration/packages/configuring-mppic.html#path-angle-critic)


Name  |  Default  |  Description
---|---|---
bt_file_path  |  "tree.xml"  |  File path to the xml file to load
loop_timeout  |  100  |  Time between tree ticks in milliseconds
plugins  |  []  |  List of plugins names for custom tree nodes, example `
['fibonacci_bt_node'] `
run_groot_monitoring  |  true  |  Rather or not to publish debugging
information for Groot
publisher_port  |  1666  |  ZMQ publisher port for Groot
server_port  |  1667  |  ZMQ server port for Groot
max_msg_per_second  |  25  |  ZMQ message rate limit for Groot

Note that all plugins specified in the ` plugins ` parameter should be pointed
to by the ` LD_LIBRARY_PATH ` environment variable. This should be handled
automatically when sourcing the ROS2 workspace but if issues come up you can
check to make sure LD_LIBRARY_PATH is set correctly by running ` echo
$LD_LIBRARY_PATH ` in the terminal where you are having issues running the
behavior tree.


###  Watchers


The BT can be associated with [ State Machine
](https://en.wikipedia.org/wiki/Finite-state_machine) (SM) however there are
certain differences in which BT outperforms the SM.
The main problem with SM is transitions between states which increase while
the number of states grows. States in SM are tightly connected and there is
often a problem when there is a necessity for reuse. It is true that SM can be
handled with ease by a designer (SW engineer), but a person will undoubtedly
find it difficult to comprehend and forecast the system’s overall behavior.
Most of these issues are resolved by **Behavior Trees, which enhance the
modular design and can be reused. Behavior Trees are by nature hierarchical.**


[ package.xml ](/berkeleyauv/behavior_tree/blob/master/package.xml
"package.xml")


###  2- Exporting the planner plugin  ¶


#  Provide feedback


Our main goals are:


|

View all files

##  Repository files navigation


##  Languages


[ Robotics  ](https://medium.com/tag/robotics?source=post_page-----
775ec0e97856---------------robotics-----------------)


##  Acknowledgements


      * [ Composition ](../../tutorials/docs/adding_a_nav2_task_server.html#composition)
      * [ Error codes ](../../tutorials/docs/adding_a_nav2_task_server.html#error-codes)
      * [ Conclusion ](../../tutorials/docs/adding_a_nav2_task_server.html#conclusion)
    * [ Filtering of Noise-Induced Obstacles ](../../tutorials/docs/filtering_of_noise-induced_obstacles.html)
      * [ Overview ](../../tutorials/docs/filtering_of_noise-induced_obstacles.html#overview)
      * [ Requirements ](../../tutorials/docs/filtering_of_noise-induced_obstacles.html#requirements)
      * [ Tutorial Steps ](../../tutorials/docs/filtering_of_noise-induced_obstacles.html#tutorial-steps)
        * [ 1\. Enable Denoise Layer ](../../tutorials/docs/filtering_of_noise-induced_obstacles.html#enable-denoise-layer)
        * [ 2\. Run Nav2 stack ](../../tutorials/docs/filtering_of_noise-induced_obstacles.html#run-nav2-stack)
      * [ How it works ](../../tutorials/docs/filtering_of_noise-induced_obstacles.html#how-it-works)
    * [ Camera Calibration ](../../tutorials/docs/camera_calibration.html)
      * [ Overview ](../../tutorials/docs/camera_calibration.html#overview)
      * [ Requirements ](../../tutorials/docs/camera_calibration.html#requirements)
      * [ Tutorial Steps ](../../tutorials/docs/camera_calibration.html#tutorial-steps)
    * [ Get Backtrace in ROS 2 / Nav2 ](../../tutorials/docs/get_backtrace.html)
      * [ Overview ](../../tutorials/docs/get_backtrace.html#overview)
      * [ Preliminaries ](../../tutorials/docs/get_backtrace.html#preliminaries)
      * [ From a Node ](../../tutorials/docs/get_backtrace.html#from-a-node)
      * [ From a Launch File ](../../tutorials/docs/get_backtrace.html#from-a-launch-file)
      * [ From Large Project ](../../tutorials/docs/get_backtrace.html#from-large-project)
      * [ From Nav2 Bringup ](../../tutorials/docs/get_backtrace.html#from-nav2-bringup)
      * [ Automatic backtrace on crash ](../../tutorials/docs/get_backtrace.html#automatic-backtrace-on-crash)
    * [ Profiling in ROS 2 / Nav2 ](../../tutorials/docs/get_profile.html)
      * [ Overview ](../../tutorials/docs/get_profile.html#overview)
      * [ Preliminaries ](../../tutorials/docs/get_profile.html#preliminaries)
      * [ Profile from a Node ](../../tutorials/docs/get_profile.html#profile-from-a-node)
      * [ Profile from a Launch File ](../../tutorials/docs/get_profile.html#profile-from-a-launch-file)
      * [ From Nav2 Bringup ](../../tutorials/docs/get_profile.html#from-nav2-bringup)
      * [ Interpreting Results ](../../tutorials/docs/get_profile.html#interpreting-results)
    * [ Docker for Development: Zero to Hero ](../../tutorials/docs/docker_dev.html)
      * [ Overview ](../../tutorials/docs/docker_dev.html#overview)
      * [ Preliminaries ](../../tutorials/docs/docker_dev.html#preliminaries)
      * [ Important Docker Commands ](../../tutorials/docs/docker_dev.html#important-docker-commands)
      * [ Exploring Your First Container ](../../tutorials/docs/docker_dev.html#exploring-your-first-container)
      * [ Understanding ROS Docker Images ](../../tutorials/docs/docker_dev.html#understanding-ros-docker-images)
      * [ For Docker-Based Development ](../../tutorials/docs/docker_dev.html#for-docker-based-development)
        * [ Building a Development Image ](../../tutorials/docs/docker_dev.html#building-a-development-image)
        * [ Visualizations from Docker ](../../tutorials/docs/docker_dev.html#visualizations-from-docker)
      * [ For Docker-Based Deployment ](../../tutorials/docs/docker_dev.html#for-docker-based-deployment)
      * [ Conclusion ](../../tutorials/docs/docker_dev.html#conclusion)


#  Writing a New Behavior Tree Plugin  ¶


[ .gitignore ](/berkeleyauv/behavior_tree/blob/master/.gitignore ".gitignore")


The code in this tutorial can be found in [ nav2_behavior_tree
](https://github.com/ros-planning/navigation2/tree/main/nav2_behavior_tree)
package as the ` wait_action  ` node. This action node can be considered as a
reference for writing other action node plugins.


Skip to content


* Solutions


    * [ Topics ](/topics)
    * [ Trending ](/trending)
    * [ Collections ](/collections)


[ ](/berkeleyauv/behavior_tree/commits/master/)

###


Additional navigation options


On tick


##  Tutorial Steps  ¶


Method is called when this BT node is ticked by the behavior tree while
executing. This should be used to get dynamic updates like new blackboard
values, input ports, or parameters. May also reset state for the action.


    static PortsList providedPorts() {
         return providedBasicPorts({InputPort<geometry_msgs::msg::Vector3>("distances")});
    }


[ Report repository ](/contact/report-
content?content_url=https%3A%2F%2Fgithub.com%2FBehaviorTree%2FBehaviorTree.ROS2&report=BehaviorTree+%28user%29)


* Turtlebot3


No

on_wait_for_result()


BehaviorTree.CPP utilities to work with ROS2


* Requirements


[ behaviortree_ros2
](/BehaviorTree/BehaviorTree.ROS2/tree/humble/behaviortree_ros2
"behaviortree_ros2")


Text to speech


[ .gitignore ](/BehaviorTree/BehaviorTree.ROS2/blob/humble/.gitignore
".gitignore")


[ src ](/berkeleyauv/behavior_tree/tree/master/src "src")


Below you will find the code which you can run in the [ ROSject
](https://app.theconstructsim.com/LiveClass/8e39921b-f25e-4bdf-b8af-d71cc0f560c9/)
. (ROS2 Galactic)


####  Basic Ports


#  berkeleyauv/behavior_tree


[ Notifications ](/login?return_to=%2FBehaviorTree%2FBehaviorTree.ROS2)


[ 767 Followers ](/followers?source=post_page-----
775ec0e97856--------------------------------)


[ **The BT framework is the C++ library** ](https://www.behaviortree.dev/)
**** that enables you to architect the BT in your robotics or gaming
application. BT provides abstract methods (built in C++) to secure logical
relationships within your application. For instance, if you develop a game,
the behavior tree can be related to the performance of the game or define how
the game characters behave in certain game situations, etc. In this regard, we
state that the BT framework offers the tools to enable logical/abstract
relationships between C++ classes, whose methods are called in accordance with
the logical tree (BT) structure of your program.


[ Markus Buchholz ](/?source=post_page-----
775ec0e97856--------------------------------)


The following example combines the above mechanism and displays how the
mentioned signals are distributed across the BT.


    * [ Constrained smoother ](../../configuration/packages/configuring-constrained-smoother.html)
      * [ Smoother Server Parameters ](../../configuration/packages/configuring-constrained-smoother.html#smoother-server-parameters)
      * [ Example ](../../configuration/packages/configuring-constrained-smoother.html#example)
    * [ Velocity Smoother ](../../configuration/packages/configuring-velocity-smoother.html)
      * [ Velocity Smoother Parameters ](../../configuration/packages/configuring-velocity-smoother.html#velocity-smoother-parameters)
      * [ Example ](../../configuration/packages/configuring-velocity-smoother.html#example)
    * [ Collision Monitor ](../../configuration/packages/configuring-collision-monitor.html)
      * [ Provided Nodes ](../../configuration/packages/configuring-collision-monitor.html#provided-nodes)
        * [ Collision Monitor Node ](../../configuration/packages/collision_monitor/configuring-collision-monitor-node.html)
        * [ Collision Detector Node ](../../configuration/packages/collision_monitor/configuring-collision-detector-node.html)
    * [ Waypoint Follower ](../../configuration/packages/configuring-waypoint-follower.html)
      * [ Parameters ](../../configuration/packages/configuring-waypoint-follower.html#parameters)
      * [ Provided Plugins ](../../configuration/packages/configuring-waypoint-follower.html#provided-plugins)
        * [ WaitAtWaypoint ](../../configuration/packages/nav2_waypoint_follower-plugins/wait_at_waypoint.html)
        * [ PhotoAtWaypoint ](../../configuration/packages/nav2_waypoint_follower-plugins/photo_at_waypoint.html)
        * [ InputAtWaypoint ](../../configuration/packages/nav2_waypoint_follower-plugins/input_at_waypoint.html)
      * [ Default Plugin ](../../configuration/packages/configuring-waypoint-follower.html#default-plugin)
      * [ Example ](../../configuration/packages/configuring-waypoint-follower.html#example)
  * [ Tuning Guide ](../../tuning/index.html)
    * [ Inflation Potential Fields ](../../tuning/index.html#inflation-potential-fields)
    * [ Robot Footprint vs Radius ](../../tuning/index.html#robot-footprint-vs-radius)
    * [ Rotate in Place Behavior ](../../tuning/index.html#rotate-in-place-behavior)
    * [ Planner Plugin Selection ](../../tuning/index.html#planner-plugin-selection)
    * [ Controller Plugin Selection ](../../tuning/index.html#controller-plugin-selection)
    * [ Caching Obstacle Heuristic in Smac Planners ](../../tuning/index.html#caching-obstacle-heuristic-in-smac-planners)
    * [ Costmap2D Plugins ](../../tuning/index.html#costmap2d-plugins)
    * [ Nav2 Launch Options ](../../tuning/index.html#nav2-launch-options)
    * [ Other Pages We’d Love To Offer ](../../tuning/index.html#other-pages-we-d-love-to-offer)
  * [ Nav2 Behavior Trees ](../../behavior_trees/index.html)
    * [ Introduction To Nav2 Specific Nodes ](../../behavior_trees/overview/nav2_specific_nodes.html)
      * [ Action Nodes ](../../behavior_trees/overview/nav2_specific_nodes.html#action-nodes)
      * [ Condition Nodes ](../../behavior_trees/overview/nav2_specific_nodes.html#condition-nodes)
      * [ Decorator Nodes ](../../behavior_trees/overview/nav2_specific_nodes.html#decorator-nodes)
      * [ Control: PipelineSequence ](../../behavior_trees/overview/nav2_specific_nodes.html#control-pipelinesequence)
      * [ Control: Recovery ](../../behavior_trees/overview/nav2_specific_nodes.html#control-recovery)
      * [ Control: RoundRobin ](../../behavior_trees/overview/nav2_specific_nodes.html#control-roundrobin)
    * [ Detailed Behavior Tree Walkthrough ](../../behavior_trees/overview/detailed_behavior_tree_walkthrough.html)
      * [ Overview ](../../behavior_trees/overview/detailed_behavior_tree_walkthrough.html#overview)
      * [ Prerequisites ](../../behavior_trees/overview/detailed_behavior_tree_walkthrough.html#prerequisites)
      * [ Navigate To Pose With Replanning and Recovery ](../../behavior_trees/overview/detailed_behavior_tree_walkthrough.html#navigate-to-pose-with-replanning-and-recovery)


[ Report repository ](/contact/report-
content?content_url=https%3A%2F%2Fgithub.com%2Fberkeleyauv%2Fbehavior_tree&report=berkeleyauv+%28user%29)


[ Open in app
](https://rsci.app.link/?%24canonical_url=https%3A%2F%2Fmedium.com%2Fp%2F775ec0e97856&%7Efeature=LoOpenInAppButton&%7Echannel=ShowPostUnderUser&source=---two_column_layout_nav----------------------------------)


**Method description**


Status


Name  |  Name  |


Last commit message


[ Sign in
](https://medium.com/m/signin?operation=login&redirect=https%3A%2F%2Fmarkus-x-
buchholz.medium.com%2Fbehavior-trees-in-c-for-robotic-applications-
ros2-775ec0e97856&source=post_page---two_column_layout_nav
-----------------------global_nav-----------)


    * [ Actions  Automate any workflow  ](/features/actions)
    * [ Packages  Host and manage packages  ](/features/packages)
    * [ Security  Find and fix vulnerabilities  ](/features/security)
    * [ Codespaces  Instant dev environments  ](/features/codespaces)
    * [ Copilot  Write better code with AI  ](/features/copilot)
    * [ Code review  Manage code changes  ](/features/code-review)
    * [ Issues  Plan and track work  ](/features/issues)
    * [ Discussions  Collaborate outside of code  ](/features/discussions)


For this reason, we retain the same license and copyright.


###  Footer navigation


6. See the Building Nodes section


[ include/  behavior_tree
](/berkeleyauv/behavior_tree/tree/master/include/behavior_tree "This path
skips through empty directories")


* [ GitHub Sponsors  Fund open source developers  ](/sponsors)


      * [ Navigation Subtree ](../../behavior_trees/overview/detailed_behavior_tree_walkthrough.html#navigation-subtree)
      * [ Recovery Subtree ](../../behavior_trees/overview/detailed_behavior_tree_walkthrough.html#recovery-subtree)
    * [ Navigate To Pose ](../../behavior_trees/trees/nav_to_pose_recovery.html)
    * [ Navigate Through Poses ](../../behavior_trees/trees/nav_through_poses_recovery.html)
    * [ Navigate To Pose and Pause Near Goal-Obstacle ](../../behavior_trees/trees/nav_to_pose_and_pause_near_goal_obstacle.html)
    * [ Navigate To Pose With Consistent Replanning And If Path Becomes Invalid ](../../behavior_trees/trees/nav_to_pose_with_consistent_replanning_and_if_path_becomes_invalid.html)
    * [ Follow Dynamic Point ](../../behavior_trees/trees/follow_point.html)
    * [ Odometry Calibration ](../../behavior_trees/trees/odometry_calibration.html)
  * [ Navigation Plugins ](../../plugins/index.html)
    * [ Behavior-Tree Navigators ](../../plugins/index.html#behavior-tree-navigators)
    * [ Costmap Layers ](../../plugins/index.html#costmap-layers)
    * [ Costmap Filters ](../../plugins/index.html#costmap-filters)
    * [ Controllers ](../../plugins/index.html#controllers)
    * [ Planners ](../../plugins/index.html#planners)
    * [ Smoothers ](../../plugins/index.html#smoothers)
    * [ Behaviors ](../../plugins/index.html#behaviors)
    * [ Waypoint Task Executors ](../../plugins/index.html#waypoint-task-executors)
    * [ Goal Checkers ](../../plugins/index.html#goal-checkers)
    * [ Progress Checkers ](../../plugins/index.html#progress-checkers)
    * [ Behavior Tree Nodes ](../../plugins/index.html#behavior-tree-nodes)
  * [ Migration Guides ](../../migration/index.html)
    * [ Dashing to Eloquent ](../../migration/Dashing.html)
      * [ New Packages ](../../migration/Dashing.html#new-packages)
      * [ New Plugins ](../../migration/Dashing.html#new-plugins)
      * [ Navigation2 Architectural Changes ](../../migration/Dashing.html#navigation2-architectural-changes)
    * [ Eloquent to Foxy ](../../migration/Eloquent.html)
      * [ General ](../../migration/Eloquent.html#general)
      * [ Server Updates ](../../migration/Eloquent.html#server-updates)
      * [ New Plugins ](../../migration/Eloquent.html#new-plugins)
      * [ Map Server Re-Work ](../../migration/Eloquent.html#map-server-re-work)
      * [ New Particle Filter Messages ](../../migration/Eloquent.html#new-particle-filter-messages)
      * [ Selection of Behavior Tree in each navigation action ](../../migration/Eloquent.html#selection-of-behavior-tree-in-each-navigation-action)
      * [ FollowPoint Capability ](../../migration/Eloquent.html#followpoint-capability)
      * [ New Costmap Layer ](../../migration/Eloquent.html#new-costmap-layer)
    * [ Foxy to Galactic ](../../migration/Foxy.html)
      * [ NavigateToPose Action Feedback updates ](../../migration/Foxy.html#navigatetopose-action-feedback-updates)
      * [ NavigateToPose BT-node Interface Changes ](../../migration/Foxy.html#navigatetopose-bt-node-interface-changes)
      * [ NavigateThroughPoses and ComputePathThroughPoses Actions Added ](../../migration/Foxy.html#navigatethroughposes-and-computepaththroughposes-actions-added)
      * [ ComputePathToPose BT-node Interface Changes ](../../migration/Foxy.html#computepathtopose-bt-node-interface-changes)
      * [ ComputePathToPose Action Interface Changes ](../../migration/Foxy.html#computepathtopose-action-interface-changes)


     <root main_tree_to_execute = "MainTree" >

         <BehaviorTree ID="MainTree">
            <Fallback name="root">
                <Task1 name="task_1"/>
                <Task2 name="task_2"/>
                <Sequence>
                    <Task3 name="task_3"/>
                    <Task4  name="task_4"/>
                </Sequence>
            </Fallback>
         </BehaviorTree>

     </root>
     )";


##  [ Contributors  10  ](/BehaviorTree/BehaviorTree.ROS2/graphs/contributors)


[ Sign in
](/login?return_to=https%3A%2F%2Fgithub.com%2Fberkeleyauv%2Fbehavior_tree)


[ ![Markus
Buchholz](https://miro.medium.com/v2/resize:fill:144:144/1*12k3P8bjeeTvt1EoxSTDEg.jpeg)
](/?source=post_page-----775ec0e97856--------------------------------)


[ Apache-2.0 license ](/BehaviorTree/BehaviorTree.ROS2/blob/humble/LICENSE)


Yes

on_tick()


](https://help.medium.com/hc/en-us?source=post_page-----
775ec0e97856--------------------------------)


Constructor to indicate the corresponding XML tag name to that matches the
plugin, the name of the action server to call using the plugin, and any
BehaviorTree.CPP special configurations required.


###  BtService


[ Artificial Intelligence  ](https://medium.com/tag/artificial-
intelligence?source=post_page-----775ec0e97856---------------
artificial_intelligence-----------------)


##  Footer


[ ](/berkeleyauv/behavior_tree/branches) [ ](/berkeleyauv/behavior_tree/tags)


Thank you for reading.


  * [ Notifications ](/login?return_to=%2Fberkeleyauv%2Fbehavior_tree)
  * [ Fork  2  ](/login?return_to=%2Fberkeleyauv%2Fbehavior_tree)
  * [ Star  10  ](/login?return_to=%2Fberkeleyauv%2Fbehavior_tree)


5. Add the following code segment, changing the ` Type ` and ` ClientNodeName ` based on your setup. The name that you set here is the name that will be used in the tree.xml.


[ 10  stars ](/berkeleyauv/behavior_tree/stargazers) [ 2  forks
](/berkeleyauv/behavior_tree/forks) [ Branches
](/berkeleyauv/behavior_tree/branches) [ Tags
](/berkeleyauv/behavior_tree/tags) [ Activity
](/berkeleyauv/behavior_tree/activity)


](https://medium.com/about?autoplay=1&source=post_page-----
775ec0e97856--------------------------------)


Method is called when the ROS 2 action server returns a successful result.
Returns the value the BT node will report back to the tree.


  * [ C++  75.2%  ](/berkeleyauv/behavior_tree/search?l=c%2B%2B)
  * [ Python  15.1%  ](/berkeleyauv/behavior_tree/search?l=python)
  * [ CMake  9.7%  ](/berkeleyauv/behavior_tree/search?l=cmake)


  * to minimize the amount of boilerplate.
  * to make asynchronous Actions non-blocking.


###  Forks


[ **35** forks ](/BehaviorTree/BehaviorTree.ROS2/forks)


* [ GitHub Sponsors  Fund open source developers  ](/sponsors)


    * [ Enterprise ](/enterprise)
    * [ Teams ](/team)
    * [ Startups ](/enterprise/startups)
    * [ Education  ](https://education.github.com)


Repositories


####  Basic Ports


Search or jump to...


The CMakeLists.txt should include the following supporting code


However, in order to build the architecture of the whole robot application, we
need to move to a **higher level of programming abstraction** , meaning
evaluating the task like path planner or power management as a simple
component.


Name  |  Name  |


No

For this tutorial, we will only be using the ` on_tick()  ` method.


For


With regard to robotics specifical, the BT is the sort of abstraction that
shifts from low-level task control (path planner, power management, etc) to
higher—level behaviors.


[ ](/BehaviorTree/BehaviorTree.ROS2/commits/humble/)

###


Clear


#  Logical Primitives


[ Sign up
](/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-
name%3E%2F%3Crepo-name%3E&source=header-
repo&source_repo=berkeleyauv%2Fbehavior_tree)


[ Sign in
](/login?return_to=https%3A%2F%2Fgithub.com%2Fberkeleyauv%2Fbehavior_tree)


Share


](https://medium.statuspage.io/?source=post_page-----
775ec0e97856--------------------------------)


This tutorial shows how to create your own behavior tree (BT) plugin. The BT
plugins are used as nodes in the behavior tree XML processed by the BT
Navigator for navigation logic.


      * [ Appendix ](../../tutorials/docs/docker_dev.html#appendix)
        * [ Nav2 Development Image ](../../tutorials/docs/docker_dev.html#nav2-development-image)
        * [ Nav2 Deployment Image ](../../tutorials/docs/docker_dev.html#nav2-deployment-image)
  * [ Plugin Tutorials ](../index.html)
    * [ Writing a New Costmap2D Plugin ](writing_new_costmap2d_plugin.html)
      * [ Overview ](writing_new_costmap2d_plugin.html#overview)
      * [ Requirements ](writing_new_costmap2d_plugin.html#requirements)
      * [ Tutorial Steps ](writing_new_costmap2d_plugin.html#tutorial-steps)
        * [ 1- Write a new Costmap2D plugin ](writing_new_costmap2d_plugin.html#write-a-new-costmap2d-plugin)
        * [ 2- Export and make GradientLayer plugin ](writing_new_costmap2d_plugin.html#export-and-make-gradientlayer-plugin)
        * [ 3- Enable the plugin in Costmap2D ](writing_new_costmap2d_plugin.html#enable-the-plugin-in-costmap2d)
        * [ 4- Run GradientLayer plugin ](writing_new_costmap2d_plugin.html#run-gradientlayer-plugin)
    * [ Writing a New Planner Plugin ](writing_new_nav2planner_plugin.html)
      * [ Overview ](writing_new_nav2planner_plugin.html#overview)
      * [ Requirements ](writing_new_nav2planner_plugin.html#requirements)
      * [ Tutorial Steps ](writing_new_nav2planner_plugin.html#tutorial-steps)
        * [ 1- Creating a new Planner Plugin ](writing_new_nav2planner_plugin.html#creating-a-new-planner-plugin)
        * [ 2- Exporting the planner plugin ](writing_new_nav2planner_plugin.html#exporting-the-planner-plugin)
        * [ 3- Pass the plugin name through params file ](writing_new_nav2planner_plugin.html#pass-the-plugin-name-through-params-file)
        * [ 4- Run StraightLine plugin ](writing_new_nav2planner_plugin.html#run-straightline-plugin)
    * [ Writing a New Controller Plugin ](writing_new_nav2controller_plugin.html)
      * [ Overview ](writing_new_nav2controller_plugin.html#overview)
      * [ Requirements ](writing_new_nav2controller_plugin.html#requirements)
      * [ Tutorial Steps ](writing_new_nav2controller_plugin.html#tutorial-steps)
        * [ 1- Create a new Controller Plugin ](writing_new_nav2controller_plugin.html#create-a-new-controller-plugin)
        * [ 2- Exporting the controller plugin ](writing_new_nav2controller_plugin.html#exporting-the-controller-plugin)
        * [ 3- Pass the plugin name through the params file ](writing_new_nav2controller_plugin.html#pass-the-plugin-name-through-the-params-file)
        * [ 4- Run Pure Pursuit Controller plugin ](writing_new_nav2controller_plugin.html#run-pure-pursuit-controller-plugin)
    * Writing a New Behavior Tree Plugin
      * Overview
      * Requirements
      * Tutorial Steps
        * 1- Creating a new BT Plugin
        * 2- Exporting the planner plugin
        * 3- Add plugin library name to config
        * 4- Run Your Custom plugin
    * [ Writing a New Behavior Plugin ](writing_new_behavior_plugin.html)
      * [ Overview ](writing_new_behavior_plugin.html#overview)
      * [ Requirements ](writing_new_behavior_plugin.html#requirements)
      * [ Tutorial Steps ](writing_new_behavior_plugin.html#tutorial-steps)


###  License


[ README.md ](/berkeleyauv/behavior_tree/blob/master/README.md "README.md")


humble


##  Use saved searches to filter your results more quickly


Additional navigation options


About


Careers


In order for the BT Navigator node to discover the plugin we’ve just
registered, we need to list the plugin library name under the bt_navigator
node in the configuration YAML file. Configuration should look similar to the
one shown below. Take note of nav2_wait_action_bt_node listed under
plugin_lib_names.


      * [ Added Smoother Task Server ](../../migration/Galactic.html#added-smoother-task-server)
      * [ Removed Use Approach Velocity Scaling Param in RPP ](../../migration/Galactic.html#removed-use-approach-velocity-scaling-param-in-rpp)
      * [ Refactored AMCL motion models as plugins ](../../migration/Galactic.html#refactored-amcl-motion-models-as-plugins)
      * [ Dropping Support for Live Groot Monitoring of Nav2 ](../../migration/Galactic.html#dropping-support-for-live-groot-monitoring-of-nav2)
      * [ Replanning Only if Path is Invalid ](../../migration/Galactic.html#replanning-only-if-path-is-invalid)
      * [ Fix CostmapLayer clearArea invert param logic ](../../migration/Galactic.html#fix-costmaplayer-cleararea-invert-param-logic)
      * [ Dynamic Composition ](../../migration/Galactic.html#dynamic-composition)
      * [ BT Cancel Node ](../../migration/Galactic.html#bt-cancel-node)
      * [ BT PathLongerOnApproach Node ](../../migration/Galactic.html#bt-pathlongeronapproach-node)
      * [ BT TruncatePathLocal Node ](../../migration/Galactic.html#bt-truncatepathlocal-node)
      * [ Constrained Smoother ](../../migration/Galactic.html#constrained-smoother)
      * [ Replanning at a Constant Rate and if the Path is Invalid ](../../migration/Galactic.html#replanning-at-a-constant-rate-and-if-the-path-is-invalid)
      * [ Euclidean Distance 2D ](../../migration/Galactic.html#euclidean-distance-2d)
      * [ Recovery To Behavior ](../../migration/Galactic.html#recovery-to-behavior)
      * [ Respawn Support in Launch and Lifecycle Manager ](../../migration/Galactic.html#respawn-support-in-launch-and-lifecycle-manager)
      * [ New Nav2 Velocity Smoother ](../../migration/Galactic.html#new-nav2-velocity-smoother)
      * [ Goal Checker API Changed ](../../migration/Galactic.html#goal-checker-api-changed)
      * [ Added Assisted Teleop ](../../migration/Galactic.html#added-assisted-teleop)
    * [ Humble to Iron ](../../migration/Humble.html)
      * [ New Behavior-Tree Navigator Plugins ](../../migration/Humble.html#new-behavior-tree-navigator-plugins)
      * [ Added Collision Monitor ](../../migration/Humble.html#added-collision-monitor)
      * [ Removed use_sim_time from yaml ](../../migration/Humble.html#removed-use-sim-time-from-yaml)
      * [ Run-time Speed up of Smac Planner ](../../migration/Humble.html#run-time-speed-up-of-smac-planner)
      * [ Recursive Refinement of Smac and Simple Smoothers ](../../migration/Humble.html#recursive-refinement-of-smac-and-simple-smoothers)
      * [ Simple Commander Python API ](../../migration/Humble.html#simple-commander-python-api)
      * [ Smac Planner Start Pose Included in Path ](../../migration/Humble.html#smac-planner-start-pose-included-in-path)
      * [ Parameterizable Collision Checking in RPP ](../../migration/Humble.html#parameterizable-collision-checking-in-rpp)
      * [ Expanded Planner Benchmark Tests ](../../migration/Humble.html#expanded-planner-benchmark-tests)
      * [ Smac Planner Path Tolerances ](../../migration/Humble.html#smac-planner-path-tolerances)
      * [ costmap_2d_node default constructor ](../../migration/Humble.html#costmap-2d-node-default-constructor)
      * [ Feedback for Navigation Failures ](../../migration/Humble.html#feedback-for-navigation-failures)
      * [ Costmap Filters ](../../migration/Humble.html#costmap-filters)
      * [ Savitzky-Golay Smoother ](../../migration/Humble.html#savitzky-golay-smoother)
      * [ Changes to Map yaml file path for map_server node in Launch ](../../migration/Humble.html#changes-to-map-yaml-file-path-for-map-server-node-in-launch)
      * [ SmootherSelector BT Node ](../../migration/Humble.html#smootherselector-bt-node)
      * [ Publish Costmap Layers ](../../migration/Humble.html#publish-costmap-layers)
      * [ Give Behavior Server Access to Both Costmaps ](../../migration/Humble.html#give-behavior-server-access-to-both-costmaps)
      * [ New Model Predictive Path Integral Controller ](../../migration/Humble.html#new-model-predictive-path-integral-controller)
      * [ Behavior Tree Uses Error Codes ](../../migration/Humble.html#behavior-tree-uses-error-codes)
      * [ Load, Save and Loop Waypoints from the Nav2 Panel in RViz ](../../migration/Humble.html#load-save-and-loop-waypoints-from-the-nav2-panel-in-rviz)


ROS2 package for managing the AUV's behavior using BTCPP behavior trees.


[ ](/BehaviorTree/BehaviorTree.ROS2/branches) [
](/BehaviorTree/BehaviorTree.ROS2/tags)


###  Resources


[ Star  ](/login?return_to=%2Fberkeleyauv%2Fbehavior_tree)


Query


    WaitAction::WaitAction(
      const std::string & xml_tag_name,
      const std::string & action_name,
      const BT::NodeConfiguration & conf)
    : BtActionNode<nav2_msgs::action::Wait>(xml_tag_name, action_name, conf)
    {
      int duration;
      getInput("wait_duration", duration);
      if (duration <= 0) {
        RCLCPP_WARN(
          node_->get_logger(), "Wait duration is negative or zero "
          "(%i). Setting to positive.", duration);
        duration *= -1;
      }

      goal_.time.sec = duration;
    }


Toggle navigation


[ btcpp_ros2_samples
](/BehaviorTree/BehaviorTree.ROS2/tree/humble/btcpp_ros2_samples
"btcpp_ros2_samples")


The beauty of the BT framework is the fact that designers receive a full
implementation of all the mechanisms and other components to architect complex
logical structures. Moreover, the logical flow can be designed as a
multithreading application without unnecessary effort. All C++ mechanisms to
support threading are incorporated into the framework.


#  behavior_tree


[ btcpp_ros2_interfaces
](/BehaviorTree/BehaviorTree.ROS2/tree/humble/btcpp_ros2_interfaces
"btcpp_ros2_interfaces")


Readme


[ Activity  ](/BehaviorTree/BehaviorTree.ROS2/activity)


#  Creating a custom ROS2 action/service client node


[ BehaviorTree ](/BehaviorTree) /  **[ BehaviorTree.ROS2
](/BehaviorTree/BehaviorTree.ROS2) ** Public


  * [ Code  ](/berkeleyauv/behavior_tree)
  * [ Issues  2  ](/berkeleyauv/behavior_tree/issues)
  * [ Pull requests  1  ](/berkeleyauv/behavior_tree/pulls)
  * [ Actions  ](/berkeleyauv/behavior_tree/actions)
  * [ Projects  0  ](/berkeleyauv/behavior_tree/projects)
  * [ Security  ](/berkeleyauv/behavior_tree/security)
  * [ Insights  ](/berkeleyauv/behavior_tree/pulse)


[
](https://medium.com/search?source=---two_column_layout_nav----------------------------------)


To see all available qualifiers, see our [ documentation
](https://docs.github.com/search-github/github-code-search/understanding-
github-code-search-syntax) .


        * [ 1- Launch Navigation2 ](../../tutorials/docs/navigation2_with_slam.html#launch-navigation2)
        * [ 2- Launch SLAM ](../../tutorials/docs/navigation2_with_slam.html#launch-slam)
        * [ 3- Working with SLAM ](../../tutorials/docs/navigation2_with_slam.html#working-with-slam)
        * [ 4- Getting Started Simplification ](../../tutorials/docs/navigation2_with_slam.html#getting-started-simplification)
    * [ (STVL) Using an External Costmap Plugin ](../../tutorials/docs/navigation2_with_stvl.html)
      * [ Overview ](../../tutorials/docs/navigation2_with_stvl.html#overview)
      * [ Costmap2D and STVL ](../../tutorials/docs/navigation2_with_stvl.html#costmap2d-and-stvl)
      * [ Tutorial Steps ](../../tutorials/docs/navigation2_with_stvl.html#tutorial-steps)
        * [ 0- Setup ](../../tutorials/docs/navigation2_with_stvl.html#setup)
        * [ 1- Install STVL ](../../tutorials/docs/navigation2_with_stvl.html#install-stvl)
        * [ 1- Modify Navigation2 Parameter ](../../tutorials/docs/navigation2_with_stvl.html#modify-navigation2-parameter)
        * [ 2- Launch Navigation2 ](../../tutorials/docs/navigation2_with_stvl.html#launch-navigation2)
        * [ 3- RVIZ ](../../tutorials/docs/navigation2_with_stvl.html#rviz)
    * [ Navigating Using GPS Localization ](../../tutorials/docs/navigation2_with_gps.html)
      * [ Overview ](../../tutorials/docs/navigation2_with_gps.html#overview)
      * [ Requirements ](../../tutorials/docs/navigation2_with_gps.html#requirements)
      * [ GPS Localization Overview ](../../tutorials/docs/navigation2_with_gps.html#gps-localization-overview)
      * [ Tutorial Steps ](../../tutorials/docs/navigation2_with_gps.html#tutorial-steps)
        * [ 0- Setup Gazebo World ](../../tutorials/docs/navigation2_with_gps.html#setup-gazebo-world)
        * [ 1- Setup GPS Localization system ](../../tutorials/docs/navigation2_with_gps.html#setup-gps-localization-system)
        * [ 2- Setup Navigation system ](../../tutorials/docs/navigation2_with_gps.html#setup-navigation-system)
        * [ 3- Interactive GPS Waypoint Follower ](../../tutorials/docs/navigation2_with_gps.html#interactive-gps-waypoint-follower)
        * [ 4- Logged GPS Waypoint Follower & Waypoint Logging ](../../tutorials/docs/navigation2_with_gps.html#logged-gps-waypoint-follower-waypoint-logging)
      * [ Conclusion ](../../tutorials/docs/navigation2_with_gps.html#conclusion)
    * [ Groot - Interacting with Behavior Trees ](../../tutorials/docs/using_groot.html)
      * [ Overview ](../../tutorials/docs/using_groot.html#overview)
      * [ Visualize Behavior Trees ](../../tutorials/docs/using_groot.html#visualize-behavior-trees)
      * [ Edit Behavior Trees ](../../tutorials/docs/using_groot.html#edit-behavior-trees)
      * [ Adding A Custom Node ](../../tutorials/docs/using_groot.html#adding-a-custom-node)
    * [ Using VIO to Augment Robot Odometry ](../../tutorials/docs/integrating_vio.html)
      * [ Overview ](../../tutorials/docs/integrating_vio.html#overview)
      * [ Setting Up the ZED X Camera ](../../tutorials/docs/integrating_vio.html#setting-up-the-zed-x-camera)
      * [ Setting Up ZED ROS ](../../tutorials/docs/integrating_vio.html#setting-up-zed-ros)
      * [ Fusing VIO Into Local State Estimate ](../../tutorials/docs/integrating_vio.html#fusing-vio-into-local-state-estimate)
        * [ Fusing VSLAM Into Global State Estimate ](../../tutorials/docs/integrating_vio.html#fusing-vslam-into-global-state-estimate)
      * [ Testing it Out! ](../../tutorials/docs/integrating_vio.html#testing-it-out)
    * [ Dynamic Object Following ](../../tutorials/docs/navigation2_dynamic_point_following.html)
      * [ Overview ](../../tutorials/docs/navigation2_dynamic_point_following.html#overview)
      * [ Tutorial Steps ](../../tutorials/docs/navigation2_dynamic_point_following.html#tutorial-steps)
        * [ 0- Create the Behavior Tree ](../../tutorials/docs/navigation2_dynamic_point_following.html#create-the-behavior-tree)


##  Folders and files


[ Write
](https://medium.com/m/signin?operation=register&redirect=https%3A%2F%2Fmedium.com%2Fnew-
story&source=---two_column_layout_nav-----------------------
new_post_topnav-----------)


  * If done flag is true then process _result.code and return corresponding BT::NodeStatu
  * Else return running


latest


#  Search code, repositories, users, issues, pull requests...


[ .gitignore ](/BehaviorTree/BehaviorTree.ROS2/blob/humble/.gitignore
".gitignore")


[ scripts ](/berkeleyauv/behavior_tree/tree/master/scripts "scripts")


{{ message }}


##  [ Packages  0  ](/orgs/BehaviorTree/packages?repo_name=BehaviorTree.ROS2)


#  Overview


* [ Pricing ](/pricing)


ROS2 package for managing the AUV's behavior using BTCPP behavior trees.


    <root main_tree_to_execute="MainTree">
      <BehaviorTree ID="MainTree">
        <RecoveryNode number_of_retries="6" name="NavigateRecovery">
          <PipelineSequence name="NavigateWithReplanning">
            <RateController hz="1.0">
              <RecoveryNode number_of_retries="1" name="ComputePathToPose">
                <ComputePathToPose goal="{goal}" path="{path}" planner_id="GridBased"/>
                <ClearEntireCostmap name="ClearGlobalCostmap-Context" service_name="global_costmap/clear_entirely_global_costmap"/>
              </RecoveryNode>
            </RateController>
            <RecoveryNode number_of_retries="1" name="FollowPath">
              <FollowPath path="{path}" controller_id="FollowPath"/>
              <ClearEntireCostmap name="ClearLocalCostmap-Context" service_name="local_costmap/clear_entirely_local_costmap"/>
            </RecoveryNode>
          </PipelineSequence>
          <ReactiveFallback name="RecoveryFallback">
            <GoalUpdated/>
            <SequenceStar name="RecoveryActions">
              <ClearEntireCostmap name="ClearLocalCostmap-Subtree" service_name="local_costmap/clear_entirely_local_costmap"/>
              <ClearEntireCostmap name="ClearGlobalCostmap-Subtree" service_name="global_costmap/clear_entirely_global_costmap"/>
              <Spin spin_dist="1.57"/>
              <Wait wait_duration="5"/>
            </SequenceStar>
          </ReactiveFallback>
        </RecoveryNode>
      </BehaviorTree>
    </root>


[ Action Service Example
](https://github.com/berkeleyauv/sub_behavior/blob/master/sub_behavior/plugins/action/snap_photo.cpp)


We read every piece of feedback, and take your input very seriously.


[ LICENSE ](/BehaviorTree/BehaviorTree.ROS2/blob/humble/LICENSE "LICENSE")


  * Set the done flag to false
  * wait for action server
  * Get the goal from the populate goal method
  * Send goal and wait for acceptance
  * return status running if goal is accepted


In the ROSject (on a Linux terminal) perform the following actions,


Name


When we design a robot system, we still have to consider how the fundamental
components (low-level actions/tasks) work and look for optimization (eg. boost
the performance of the path algorithm by adding heuristics).


      * [ Smoothers ](../../concepts/index.html#smoothers)
      * [ Robot Footprints ](../../concepts/index.html#robot-footprints)
      * [ Waypoint Following ](../../concepts/index.html#waypoint-following)
    * [ State Estimation ](../../concepts/index.html#state-estimation)
      * [ Standards ](../../concepts/index.html#standards)
      * [ Global Positioning: Localization and SLAM ](../../concepts/index.html#global-positioning-localization-and-slam)
      * [ Odometry ](../../concepts/index.html#odometry)
    * [ Environmental Representation ](../../concepts/index.html#environmental-representation)
      * [ Costmaps and Layers ](../../concepts/index.html#costmaps-and-layers)
      * [ Costmap Filters ](../../concepts/index.html#costmap-filters)
      * [ Other Forms ](../../concepts/index.html#other-forms)
    * [ Nav2 Academic Overview ](../../concepts/index.html#nav2-academic-overview)
  * [ First-Time Robot Setup Guide ](../../setup_guides/index.html)
    * [ Setting Up Transformations ](../../setup_guides/transformation/setup_transforms.html)
      * [ Transforms Introduction ](../../setup_guides/transformation/setup_transforms.html#transforms-introduction)
      * [ Static Transform Publisher Demo ](../../setup_guides/transformation/setup_transforms.html#static-transform-publisher-demo)
      * [ Transforms in Navigation2 ](../../setup_guides/transformation/setup_transforms.html#transforms-in-navigation2)
      * [ Conclusion ](../../setup_guides/transformation/setup_transforms.html#conclusion)
    * [ Setting Up The URDF ](../../setup_guides/urdf/setup_urdf.html)
      * [ URDF and the Robot State Publisher ](../../setup_guides/urdf/setup_urdf.html#urdf-and-the-robot-state-publisher)
      * [ Setting Up the Environment ](../../setup_guides/urdf/setup_urdf.html#setting-up-the-environment)
      * [ Writing the URDF ](../../setup_guides/urdf/setup_urdf.html#writing-the-urdf)
      * [ Build and Launch ](../../setup_guides/urdf/setup_urdf.html#build-and-launch)
      * [ Visualization using RVIZ ](../../setup_guides/urdf/setup_urdf.html#visualization-using-rviz)
      * [ Adding Physical Properties ](../../setup_guides/urdf/setup_urdf.html#adding-physical-properties)
      * [ Conclusion ](../../setup_guides/urdf/setup_urdf.html#conclusion)
    * [ Setting Up Odometry ](../../setup_guides/odom/setup_odom.html)
      * [ Odometry Introduction ](../../setup_guides/odom/setup_odom.html#odometry-introduction)
      * [ Setting Up Odometry on your Robot ](../../setup_guides/odom/setup_odom.html#setting-up-odometry-on-your-robot)
      * [ Simulating an Odometry System using Gazebo ](../../setup_guides/odom/setup_odom.html#simulating-an-odometry-system-using-gazebo)
        * [ Setup and Prerequisites ](../../setup_guides/odom/setup_odom.html#setup-and-prerequisites)
        * [ Adding Gazebo Plugins to a URDF ](../../setup_guides/odom/setup_odom.html#adding-gazebo-plugins-to-a-urdf)
        * [ Launch and Build Files ](../../setup_guides/odom/setup_odom.html#launch-and-build-files)
        * [ Build, Run and Verification ](../../setup_guides/odom/setup_odom.html#build-run-and-verification)
      * [ Robot Localization Demo ](../../setup_guides/odom/setup_odom.html#robot-localization-demo)
        * [ Configuring Robot Localization ](../../setup_guides/odom/setup_odom.html#configuring-robot-localization)
        * [ Launch and Build Files ](../../setup_guides/odom/setup_odom.html#id3)
        * [ Build, Run and Verification ](../../setup_guides/odom/setup_odom.html#id4)
      * [ Conclusion ](../../setup_guides/odom/setup_odom.html#conclusion)
    * [ Setting Up Sensors ](../../setup_guides/sensors/setup_sensors.html)


###  1- Creating a new BT Plugin  ¶


[ Sign up
](/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-
name%3E%2F%3Crepo-name%3E&source=header-
repo&source_repo=BehaviorTree%2FBehaviorTree.ROS2)


[ ](https://github.com "GitHub") © 2024 GitHub, Inc.


[
](https://medium.com/?source=---two_column_layout_nav----------------------------------)


[ Custom properties  ](/BehaviorTree/BehaviorTree.ROS2/custom-properties)


#  BehaviorTree/BehaviorTree.ROS2


Code


Last commit date

---|---|---|---

##  Latest commit


[ ![Markus
Buchholz](https://miro.medium.com/v2/resize:fill:88:88/1*12k3P8bjeeTvt1EoxSTDEg.jpeg)
](/?source=post_page-----775ec0e97856--------------------------------)


Cancel  Submit feedback


    * [ Learning Pathways  ](https://resources.github.com/learn/pathways/)
    * [ White papers, Ebooks, Webinars  ](https://resources.github.com/)
    * [ Customer Stories ](/customer-stories)
    * [ Partners  ](https://partner.github.com/)


#  Behavior Trees for Robotic Applications (ROS2) in C++


[ Branches  ](/berkeleyauv/behavior_tree/branches) [ Tags
](/berkeleyauv/behavior_tree/tags)


**We use the idea of a high level of abstraction therefore it seems to be
reasonable to elaborate on the location of this abstraction. The following
figure gives you an overview of a stack of abstractions.**


        * [ 1- Setup Rviz clicked point ](../../tutorials/docs/navigation2_dynamic_point_following.html#setup-rviz-clicked-point)
        * [ 2- Run Dynamic Object Following in Nav2 Simulation ](../../tutorials/docs/navigation2_dynamic_point_following.html#run-dynamic-object-following-in-nav2-simulation)
    * [ Navigating with Keepout Zones ](../../tutorials/docs/navigation2_with_keepout_filter.html)
      * [ Overview ](../../tutorials/docs/navigation2_with_keepout_filter.html#overview)
      * [ Requirements ](../../tutorials/docs/navigation2_with_keepout_filter.html#requirements)
      * [ Tutorial Steps ](../../tutorials/docs/navigation2_with_keepout_filter.html#tutorial-steps)
        * [ 1\. Prepare filter mask ](../../tutorials/docs/navigation2_with_keepout_filter.html#prepare-filter-mask)
        * [ 2\. Configure Costmap Filter Info Publisher Server ](../../tutorials/docs/navigation2_with_keepout_filter.html#configure-costmap-filter-info-publisher-server)
        * [ 3\. Enable Keepout Filter ](../../tutorials/docs/navigation2_with_keepout_filter.html#enable-keepout-filter)
        * [ 4\. Run Nav2 stack ](../../tutorials/docs/navigation2_with_keepout_filter.html#run-nav2-stack)
    * [ Navigating with Speed Limits ](../../tutorials/docs/navigation2_with_speed_filter.html)
      * [ Overview ](../../tutorials/docs/navigation2_with_speed_filter.html#overview)
      * [ Requirements ](../../tutorials/docs/navigation2_with_speed_filter.html#requirements)
      * [ Tutorial Steps ](../../tutorials/docs/navigation2_with_speed_filter.html#tutorial-steps)
        * [ 1\. Prepare filter mask ](../../tutorials/docs/navigation2_with_speed_filter.html#prepare-filter-mask)
        * [ 2\. Configure Costmap Filter Info Publisher Server ](../../tutorials/docs/navigation2_with_speed_filter.html#configure-costmap-filter-info-publisher-server)
        * [ 3\. Enable Speed Filter ](../../tutorials/docs/navigation2_with_speed_filter.html#enable-speed-filter)
        * [ 4\. Run Nav2 stack ](../../tutorials/docs/navigation2_with_speed_filter.html#run-nav2-stack)
    * [ Using Rotation Shim Controller ](../../tutorials/docs/using_shim_controller.html)
      * [ Overview ](../../tutorials/docs/using_shim_controller.html#overview)
      * [ What is the Rotation Shim Controller? ](../../tutorials/docs/using_shim_controller.html#what-is-the-rotation-shim-controller)
      * [ Configuring Rotation Shim Controller ](../../tutorials/docs/using_shim_controller.html#configuring-rotation-shim-controller)
      * [ Configuring Primary Controller ](../../tutorials/docs/using_shim_controller.html#configuring-primary-controller)
      * [ Demo Execution ](../../tutorials/docs/using_shim_controller.html#demo-execution)
    * [ Adding a Smoother to a BT ](../../tutorials/docs/adding_smoother.html)
      * [ Overview ](../../tutorials/docs/adding_smoother.html#overview)
      * [ Requirements ](../../tutorials/docs/adding_smoother.html#requirements)
      * [ Tutorial Steps ](../../tutorials/docs/adding_smoother.html#tutorial-steps)
        * [ 0- Familiarization with the Smoother BT Node ](../../tutorials/docs/adding_smoother.html#familiarization-with-the-smoother-bt-node)
        * [ 1- Specifying a Smoother Plugin ](../../tutorials/docs/adding_smoother.html#specifying-a-smoother-plugin)
        * [ 2- Modifying your BT XML ](../../tutorials/docs/adding_smoother.html#modifying-your-bt-xml)
    * [ Using Collision Monitor ](../../tutorials/docs/using_collision_monitor.html)
      * [ Overview ](../../tutorials/docs/using_collision_monitor.html#overview)
      * [ Requirements ](../../tutorials/docs/using_collision_monitor.html#requirements)
      * [ Configuring Collision Monitor ](../../tutorials/docs/using_collision_monitor.html#configuring-collision-monitor)
      * [ Configuring Collision Monitor with VelocityPolygon ](../../tutorials/docs/using_collision_monitor.html#configuring-collision-monitor-with-velocitypolygon)
      * [ Preparing Nav2 stack ](../../tutorials/docs/using_collision_monitor.html#preparing-nav2-stack)
      * [ Demo Execution ](../../tutorials/docs/using_collision_monitor.html#demo-execution)
    * [ Adding a New Nav2 Task Server ](../../tutorials/docs/adding_a_nav2_task_server.html)
      * [ Lifecycle Nodes ](../../tutorials/docs/adding_a_nav2_task_server.html#lifecycle-nodes)


You can’t perform that action at this time.


Last commit message


[ CMakeLists.txt ](/berkeleyauv/behavior_tree/blob/master/CMakeLists.txt
"CMakeLists.txt")


Help


###  Stars


[ Branches  ](/BehaviorTree/BehaviorTree.ROS2/branches) [ Tags
](/BehaviorTree/BehaviorTree.ROS2/tags)


[ Edit ](https://github.com/ros-planning/navigation.ros.org)


Blog


Here, we give the input of the ` xml_tag_name  ` , which tells the BT node
plugin the string in the XML that corresponds to this node. This will be seen
later when we register this BT node as a plugin. It also takes in the string
name of the action server that it will call to execute some behavior. Finally,
a set of configurations that we can safely ignore for the purposes of most
node plugins.


[ .github/  workflows
](/BehaviorTree/BehaviorTree.ROS2/tree/humble/.github/workflows "This path
skips through empty directories")


Code


#  Building Nodes


[ Cpp  ](https://medium.com/tag/cpp?source=post_page-----775ec0e97856
---------------cpp-----------------)


Readme


The fallback node (OR operator). (by author)


This commit does not belong to any branch on this repository, and may belong
to a fork outside of the repository.


  * [ Code  ](/BehaviorTree/BehaviorTree.ROS2)
  * [ Issues  ](/BehaviorTree/BehaviorTree.ROS2/issues)
  * [ Pull requests  ](/BehaviorTree/BehaviorTree.ROS2/pulls)
  * [ Actions  ](/BehaviorTree/BehaviorTree.ROS2/actions)
  * [ Projects  ](/BehaviorTree/BehaviorTree.ROS2/projects)
  * [ Security  ](/BehaviorTree/BehaviorTree.ROS2/security)
  * [ Insights  ](/BehaviorTree/BehaviorTree.ROS2/pulse)


[ behaviortree_ros2
](/BehaviorTree/BehaviorTree.ROS2/tree/humble/behaviortree_ros2
"behaviortree_ros2")


](https://blog.medium.com/?source=post_page-----
775ec0e97856--------------------------------)


The following article provides you with general intuition over the Behaviour
Trees which are often used in robotic applications or frameworks: [ ROS
](https://www.ros.org/) , [ Moveit ](https://picknik.ai/moveit/) , and [ NAV2
](https://navigation.ros.org/behavior_trees/index.html) . Understanding the
principles of the Behavior Tress (BT) framework gives you an excellent
opportunity to apply knowledge in the [ gaming domain
](https://www.gamedeveloper.com/programming/behavior-trees-for-ai-how-they-
work) . The BT can be integrated with [ Unity
](https://medium.com/geekculture/how-to-create-a-simple-behaviour-tree-in-
unity-c-3964c84c060e) or [ Unreal ](https://docs.unrealengine.com/5.1/en-
US/behavior-trees-in-unreal-engine/) .


Now you can use a behavior tree with your custom BT node. For example, the `
navigate_w_replanning_and_recovery.xml  ` file is shown below.


Provides the framework for a standard ROS2 action client. Implementation is
done through overriding ` ActionT::Goal populate_goal() ` . Adding additional
ports can be done by overriding ` BT::PortsList providedPorts() ` . Canceling
actions is done by halting the node which can be accomplished by using
something like a reactive sequence with an action or condition node preceding
the BtAction node which, upon returning ` FAILURE ` , will cause the reactive
sequence to halt the BtAction node which will subsequently cancel the action
over ROS2.


        {
        }

        // You must override the virtual function tick()
        NodeStatus tick() override
        {
            std::cout << "Task3: " << this->name() << std::endl;
            return BT::NodeStatus::SUCCESS;
        }
    };

    class Task4 : public BT::SyncActionNode
    {
      public:
        Task4(const std::string& name) : BT::SyncActionNode(name, {})
        {
        }

        // You must override the virtual function tick()
        NodeStatus tick() override
        {
            std::cout << "Task4: " << this->name() << std::endl;
            return BT::NodeStatus::SUCCESS;
        }
    };

    static const char* xml_text_medium = R"(

     <root main_tree_to_execute = "MainTree" >

         <BehaviorTree ID="MainTree">
            <Fallback name="root">
                <Task1 name="task_1"/>
                <Task2 name="task_2"/>
                <Sequence>
                    <Task3 name="task_3"/>
                    <Task4  name="task_4"/>
                </Sequence>
            </Fallback>
         </BehaviorTree>


While discussing the concept of BT, I used the logical flow formulation. In
the context of software design, we can evaluate the discussed concept as a
logical connection between certain software modules (nodes). The logical
connection can be described as the usage of a certain logic operator like AND,
OR, or NOT wrapped into the BT framework.


[ Programming  ](https://medium.com/tag/programming?source=post_page-----
775ec0e97856---------------programming-----------------)


[ plugins/  action  ](/berkeleyauv/behavior_tree/tree/master/plugins/action
"This path skips through empty directories")


The ` BTActionNode  ` class provides 5 virtual methods to use, in addition to
the information provided in the constructor. Let’s learn more about the
methods needed to write a BT action plugin.


[ Custom properties  ](/berkeleyauv/behavior_tree/custom-properties)


Toggle navigation


###  Forks


In simple principle (only for the purpose of this article), we can distinguish
two logical nodes (BT mechanisms). The **fallback** realizes the logical OR
and **sequence** node, which realizes the AND logic.


##  [ Releases ](/BehaviorTree/BehaviorTree.ROS2/releases)


    #include "behaviortree_cpp_v3/bt_factory.h"

    using namespace BT;

    class Task1 : public BT::SyncActionNode
    {
      public:
        Task1(const std::string& name) : BT::SyncActionNode(name, {})
        {
        }

        // You must override the virtual function tick()
        NodeStatus tick() override
        {
            std::cout << "Task1: " << this->name() << std::endl;
            return BT::NodeStatus::FAILURE;
        }
    };

    class Task2 : public BT::SyncActionNode
    {
      public:
        Task2(const std::string& name) : BT::SyncActionNode(name, {})
        {
        }

        // You must override the virtual function tick()
        NodeStatus tick() override
        {
            std::cout << "Task2: " << this->name() << std::endl;
            return BT::NodeStatus::FAILURE;
        }
    };

    class Task3 : public BT::SyncActionNode
    {
      public:
        Task3(const std::string& name) : BT::SyncActionNode(name, {})


In this macro, we must create a ` NodeBuilder  ` so that our custom action
node can have a non-default constructor signature (for the action and xml
names). This lambda will return a unique pointer to the behavior tree node we
have created. Fill in the constructor with the relevant information, giving it
the ` name  ` and ` config  ` given in the function arguments. Then define the
ROS 2 action server’s name that this BT node will call, in this case, it’s the
` Wait  ` action.


[ README.md ](/BehaviorTree/BehaviorTree.ROS2/blob/humble/README.md
"README.md")


BtService and BtAction are both contained entirely in header files so no
static linking is required to work with them.


[ Star  ](/login?return_to=%2FBehaviorTree%2FBehaviorTree.ROS2)


Both can be depicted as follows,


* [ The ReadME Project  GitHub community articles  ](/readme)


[ btcpp_ros2_interfaces
](/BehaviorTree/BehaviorTree.ROS2/tree/humble/btcpp_ros2_interfaces
"btcpp_ros2_interfaces")


No releases published


8 min read


The ` providedPorts()  ` method gives us the opportunity to define input or
output ports. Ports can be thought of as parameters that the behavior tree
node has access to from the behavior tree itself. For our example, there is
only a single input port, the ` wait_duration  ` which can be set in the BT
XML for each instance of the ` wait  ` recovery. We set the type, ` int  ` ,
the default ` 1  ` , the name ` wait_duration  ` , and a description of the
port ` Wait  time  ` .


Cancel  Create saved search


Cancel  Submit feedback


Go to file


Privacy


[ **3** watching ](/berkeleyauv/behavior_tree/watchers)


**Required?**

---|---|---

Constructor


master


We will create a simple BT plugin node to perform an action on another server.
For this example, we’re going to analyze the simplest behavior tree action
node in the ` nav2_behavior_tree  ` package, the ` wait  ` node. Beyond this
example of an action BT node, you can also create custom decorator, condition,
and control nodes. Each node type has a unique role in the behavior tree to
perform actions like planning, control the flow of the BT, check the status of
a condition, or modify the output of other BT nodes.


  * [ Getting Started ](../../getting_started/index.html)
    * [ Installation ](../../getting_started/index.html#installation)
    * [ Running the Example ](../../getting_started/index.html#running-the-example)
    * [ Navigating ](../../getting_started/index.html#navigating)
  * [ Development Guides ](../../development_guides/index.html)
    * [ Build and Install ](../../development_guides/build_docs/index.html)
      * [ Install ](../../development_guides/build_docs/index.html#install)
      * [ Build ](../../development_guides/build_docs/index.html#build)
        * [ Released Distribution Binaries ](../../development_guides/build_docs/index.html#released-distribution-binaries)
        * [ Rolling Development Source ](../../development_guides/build_docs/index.html#rolling-development-source)
        * [ Docker Container Images ](../../development_guides/build_docs/index.html#docker-container-images)
      * [ Generate Doxygen ](../../development_guides/build_docs/index.html#generate-doxygen)
      * [ Help ](../../development_guides/build_docs/index.html#help)
        * [ Build Troubleshooting Guide ](../../development_guides/build_docs/build_troubleshooting_guide.html)
    * [ Dev Containers ](../../development_guides/devcontainer_docs/index.html)
      * [ Dev Container Guide ](../../development_guides/devcontainer_docs/devcontainer_guide.html)
        * [ Creating Dev Containers ](../../development_guides/devcontainer_docs/devcontainer_guide.html#creating-dev-containers)
        * [ Using Dev Containers ](../../development_guides/devcontainer_docs/devcontainer_guide.html#using-dev-containers)
      * [ What, Why, How? ](../../development_guides/devcontainer_docs/index.html#what-why-how)
        * [ What is a Dev Container? ](../../development_guides/devcontainer_docs/index.html#what-is-a-dev-container)
        * [ Why use a Dev Container? ](../../development_guides/devcontainer_docs/index.html#why-use-a-dev-container)
        * [ How do Dev Containers work? ](../../development_guides/devcontainer_docs/index.html#how-do-dev-containers-work)
      * [ Prerequisites ](../../development_guides/devcontainer_docs/index.html#prerequisites)
      * [ Getting started ](../../development_guides/devcontainer_docs/index.html#getting-started)
      * [ Security ](../../development_guides/devcontainer_docs/index.html#security)
    * [ Getting Involved ](../../development_guides/involvement_docs/index.html)
      * [ Getting Involved ](../../development_guides/involvement_docs/index.html#id1)
      * [ Process ](../../development_guides/involvement_docs/index.html#process)
      * [ Licensing ](../../development_guides/involvement_docs/index.html#licensing)
      * [ Developer Certification of Origin (DCO) ](../../development_guides/involvement_docs/index.html#developer-certification-of-origin-dco)
  * [ Navigation Concepts ](../../concepts/index.html)
    * [ ROS 2 ](../../concepts/index.html#ros-2)
      * [ Action Server ](../../concepts/index.html#action-server)
      * [ Lifecycle Nodes and Bond ](../../concepts/index.html#lifecycle-nodes-and-bond)
    * [ Behavior Trees ](../../concepts/index.html#behavior-trees)
    * [ Navigation Servers ](../../concepts/index.html#navigation-servers)
      * [ Planner, Controller, Smoother and Recovery Servers ](../../concepts/index.html#planner-controller-smoother-and-recovery-servers)
      * [ Planners ](../../concepts/index.html#planners)
      * [ Controllers ](../../concepts/index.html#controllers)
      * [ Behaviors ](../../concepts/index.html#behaviors)


To see all available qualifiers, see our [ documentation
](https://docs.github.com/search-github/github-code-search/understanding-
github-code-search-syntax) .


    add_library(name_bt_node SHARED plugins/action/name.cpp)
    list(APPEND plugin_libs name_bt_node)


For


[ scripts ](/berkeleyauv/behavior_tree/tree/master/scripts "scripts")


Method is called when the ROS 2 action server returns an aborted result.
Returns the value the BT node will report back to the tree.


[ ros2 ](/topics/ros2 "Topic: ros2")


[ src ](/berkeleyauv/behavior_tree/tree/master/src "src")


Query


* Open Source


* Tutorial Steps


###  3- Add plugin library name to config  ¶


    static BT::PortsList providedPorts()
    {
      return providedBasicPorts(
        {
          BT::InputPort<int>("wait_duration", 1, "Wait time")
        });
    }


#  BehaviorTree.ROS2


  * [ Notifications ](/login?return_to=%2FBehaviorTree%2FBehaviorTree.ROS2)
  * [ Fork  35  ](/login?return_to=%2FBehaviorTree%2FBehaviorTree.ROS2)
  * [ Star  102  ](/login?return_to=%2FBehaviorTree%2FBehaviorTree.ROS2)


####  Program Flow


BehaviorTree.CPP utilities to work with ROS2


Repositories


[ berkeleyauv ](/berkeleyauv) /  **[ behavior_tree
](/berkeleyauv/behavior_tree) ** Public


Skip to content


[ .gitignore ](/berkeleyauv/behavior_tree/blob/master/.gitignore ".gitignore")


[ CMakeLists.txt ](/berkeleyauv/behavior_tree/blob/master/CMakeLists.txt
"CMakeLists.txt")


[ Sign in
](/login?return_to=https%3A%2F%2Fgithub.com%2FBehaviorTree%2FBehaviorTree.ROS2)


[ plugins/  action  ](/berkeleyauv/behavior_tree/tree/master/plugins/action
"This path skips through empty directories")


The ` on_tick()  ` method is called when the behavior tree ticks a specific
node. For the wait BT node, we simply want to notify a counter on the
blackboard that an action plugin that corresponds to a recovery was ticked.
This is useful to keep metrics about the number of recoveries executed during
a specific navigation run. You could also log or update the ` goal_  ` waiting
duration if that is a variable input.


Jan 20, 2023


  * [ Code  ](/berkeleyauv/behavior_tree)
  * [ Issues  ](/berkeleyauv/behavior_tree/issues)
  * [ Pull requests  ](/berkeleyauv/behavior_tree/pulls)
  * [ Actions  ](/berkeleyauv/behavior_tree/actions)
  * [ Projects  ](/berkeleyauv/behavior_tree/projects)
  * [ Security  ](/berkeleyauv/behavior_tree/security)
  * [ Insights  ](/berkeleyauv/behavior_tree/pulse)


###  License


ROS2 package for managing the AUV's behavior using BTCPP behavior trees. BTCPP
documentation can be found at [ https://www.behaviortree.dev
](https://www.behaviortree.dev) . The github repository which contains
examples and source code can be found [ here
](https://github.com/BehaviorTree/BehaviorTree.CPP) . To visualize the
behavior trees checkout [ Groot ](https://github.com/BehaviorTree/Groot) and
download the latest AppImage under releases.


](https://policy.medium.com/medium-terms-of-
service-9db0094a1e0f?source=post_page-----
775ec0e97856--------------------------------)


MMethod is called when the ROS 2 action server returns a cancelled result.
Returns the value the BT node will report back to the tree.


4\. Now the tick is sent to the Sequence node (AND). Sequence sends tick to
task 3 and receives SUCCESS but the Sequence is logical AND operation so so we
continue to check if all are SUCCESS.
Task 4 is SUCCESS therefore the root receives also SUCCESS.


[ Here ](https://www.youtube.com/watch?v=KO4S0Lsba6I) you will find also the
brilliant introduction to BT link to the online environment where you can run
your mobile robot.


    BT_REGISTER_NODES(factory)
    {
      BT::NodeBuilder builder =
        [](const std::string & name, const BT::NodeConfiguration & config)
        {
          return std::make_unique<nav2_behavior_tree::WaitAction>(name, "wait", config);
        };

      factory.registerBuilder<nav2_behavior_tree::WaitAction>("Wait", builder);
    }


[ Search syntax tips ](https://docs.github.com/search-github/github-code-
search/understanding-github-code-search-syntax)


[ Activity  ](/berkeleyauv/behavior_tree/activity)


Apache-2.0 license


##  [ Contributors  2  ](/berkeleyauv/behavior_tree/graphs/contributors)


        * [ CancelCoverage ](../../configuration/packages/bt-plugins/actions/CancelCoverage.html)
        * [ RemovePassedGoals ](../../configuration/packages/bt-plugins/actions/RemovePassedGoals.html)
        * [ CancelControl ](../../configuration/packages/bt-plugins/actions/CancelControl.html)
        * [ CancelBackUp ](../../configuration/packages/bt-plugins/actions/CancelBackUp.html)
        * [ CancelSpin ](../../configuration/packages/bt-plugins/actions/CancelSpin.html)
        * [ CancelWait ](../../configuration/packages/bt-plugins/actions/CancelWait.html)
        * [ CancelDriveOnHeading ](../../configuration/packages/bt-plugins/actions/CancelDriveOnHeading.html)
        * [ CancelAssistedTeleop ](../../configuration/packages/bt-plugins/actions/CancelAssistedTeleop.html)
        * [ SmoothPath ](../../configuration/packages/bt-plugins/actions/Smooth.html)
      * [ Condition Plugins ](../../configuration/packages/configuring-bt-xml.html#condition-plugins)
        * [ GoalReached ](../../configuration/packages/bt-plugins/conditions/GoalReached.html)
        * [ TransformAvailable ](../../configuration/packages/bt-plugins/conditions/TransformAvailable.html)
        * [ DistanceTraveled ](../../configuration/packages/bt-plugins/conditions/DistanceTraveled.html)
        * [ GoalUpdated ](../../configuration/packages/bt-plugins/conditions/GoalUpdated.html)
        * [ GloballyUpdatedGoal ](../../configuration/packages/bt-plugins/conditions/GloballyUpdatedGoal.html)
        * [ InitialPoseReceived ](../../configuration/packages/bt-plugins/conditions/InitialPoseReceived.html)
        * [ IsStuck ](../../configuration/packages/bt-plugins/conditions/IsStuck.html)
        * [ TimeExpired ](../../configuration/packages/bt-plugins/conditions/TimeExpired.html)
        * [ IsBatteryLow ](../../configuration/packages/bt-plugins/conditions/IsBatteryLow.html)
        * [ IsPathValid ](../../configuration/packages/bt-plugins/conditions/IsPathValid.html)
        * [ PathExpiringTimer ](../../configuration/packages/bt-plugins/conditions/PathExpiringTimer.html)
        * [ AreErrorCodesPresent ](../../configuration/packages/bt-plugins/conditions/AreErrorCodesPresent.html)
        * [ WouldAControllerRecoveryHelp ](../../configuration/packages/bt-plugins/conditions/WouldAControllerRecoveryHelp.html)
        * [ WouldAPlannerRecoveryHelp ](../../configuration/packages/bt-plugins/conditions/WouldAPlannerRecoveryHelp.html)
        * [ WouldASmootherRecoveryHelp ](../../configuration/packages/bt-plugins/conditions/WouldASmootherRecoveryHelp.html)
        * [ IsBatteryCharging ](../../configuration/packages/bt-plugins/conditions/IsBatteryCharging.html)
      * [ Control Plugins ](../../configuration/packages/configuring-bt-xml.html#control-plugins)
        * [ PipelineSequence ](../../configuration/packages/bt-plugins/controls/PipelineSequence.html)
        * [ RoundRobin ](../../configuration/packages/bt-plugins/controls/RoundRobin.html)
        * [ RecoveryNode ](../../configuration/packages/bt-plugins/controls/RecoveryNode.html)
      * [ Decorator Plugins ](../../configuration/packages/configuring-bt-xml.html#decorator-plugins)
        * [ RateController ](../../configuration/packages/bt-plugins/decorators/RateController.html)
        * [ DistanceController ](../../configuration/packages/bt-plugins/decorators/DistanceController.html)
        * [ SpeedController ](../../configuration/packages/bt-plugins/decorators/SpeedController.html)
        * [ GoalUpdater ](../../configuration/packages/bt-plugins/decorators/GoalUpdater.html)
        * [ PathLongerOnApproach ](../../configuration/packages/bt-plugins/decorators/PathLongerOnApproach.html)
        * [ SingleTrigger ](../../configuration/packages/bt-plugins/decorators/SingleTrigger.html)
      * [ Example ](../../configuration/packages/configuring-bt-xml.html#example)
    * [ Costmap 2D ](../../configuration/packages/configuring-costmaps.html)
      * [ Costmap2D ROS Parameters ](../../configuration/packages/configuring-costmaps.html#costmap2d-ros-parameters)


##  Requirements  ¶


####  Program Flow


By Solution


Name  |  Default  |  Description
---|---|---
server_timeout  |  None  |  timeout for accepting goal and `
wait_for_action_server `
cancel_timeout  |  None  |  timeout for action cancelation to be accepted
server_name  |  None  |  name of the service to call

* * *


##  About


A function to define the input and output ports a BT node may have. These are
analogous to parameters that are defined in the BT XML by hardcoded values or
by the value of output ports of other nodes.


On tick


General overview of SW architecture (by author)


Since BT is the C++ library that provides a framework to create BT (in C++),
the article focuses on an overview of BT. Your interest in this area can be
expanded by the [ online course ](https://app.theconstructsim.com/Course/131/)
, and [ hands-on course ](https://www.theconstructsim.com/one-day-
training/behavior-trees-for-ros2/) , which I highly recommend. If you are
interested more about learning ROS, robotics, AI, ML, software, and many more
please take a look at [ The ConstructSim ](https://www.theconstructsim.com/)
website and be inspired by [ what you can learn
](https://www.theconstructsim.com/robotigniteacademy_learnros/ros-courses-
library/) . They have also a perfectly done Robotics [ Developer Master Class
](https://www.theconstructsim.com/robotics-developer/) which approaches you to
land in the dream company.


This is the only executable in this repository and is responsible for loading
the behavior tree xml and plugins and then executing the behavior tree.
BtEngine is run as a ROS node and has the default name ` bt_engine ` not to be
confused with the additional node that this process will create which is used
by BtService and BtAction with the default name ` bt_node ` .


* Overview


No

on_aborted()


[ LICENSE ](/BehaviorTree/BehaviorTree.ROS2/blob/humble/LICENSE "LICENSE")


Our example plugin inherits from the base class `
nav2_behavior_tree::BtActionNode  ` . The base class is a wrapper on the
BehaviorTree.CPP ` BT::ActionNodeBase  ` that simplifies BT action nodes that
utilize ROS 2 action clients. An ` BTActionNode  ` is both a BT action and
uses ROS 2 action network interfaces for calling a remote server to do some
work.


[ **10** stars ](/berkeleyauv/behavior_tree/stargazers)


Provides the framework for a standard ROS2 service client. Implementation is
done through overriding the ` ServiceT::Request::SharedPtr populate_request()
` and ` BT::NodeStatus handle_response(ServiceT::Response::SharedPtr response)
` methods. Adding additional ports can be done by overriding ` BT::PortsList
providedPorts() ` .


[ **102** stars ](/BehaviorTree/BehaviorTree.ROS2/stargazers)


Go to file


    * [ All features ](/features)
    * [ Documentation  ](https://docs.github.com)
    * [ GitHub Skills  ](https://skills.github.com/)
    * [ Blog  ](https://github.blog)


The sequence node (AND operator). (by author)


##  Footer


    * [ Enterprise ](/enterprise)
    * [ Teams ](/team)
    * [ Startups ](/enterprise/startups)
    * [ Education  ](https://education.github.com)


Include my email address so I can be contacted


Additionally, check **plugins.hpp** to see how to learn how to wrap your Nodes
into plugins that can be loaded at run-time.


    set(dependencies
            rclcpp
            ...
            )

    <<<List of plugin specific segments resembling the above code snippet>>>

    foreach(bt_plugin ${plugin_libs})
      ament_target_dependencies(${bt_plugin} ${dependencies})
      target_compile_definitions(${bt_plugin} PRIVATE BT_PLUGIN_EXPORT)
    endforeach()

    install(TARGETS ${plugin_libs}
            ARCHIVE DESTINATION lib
            LIBRARY DESTINATION lib
            RUNTIME DESTINATION bin
            )


  * Configure Parameters
  * Load the plugins specified by the ` plugins ` parameter
  * Load tree specified by the ` bt_file_path ` parameter and create a second ROS node that lives in the blackboard and is accessible to all nodes in the tree
  * Check if ` run_groot_monitoring ` is true and if so start groot monitoring on ` publisher_port ` connected to ` server_port `
  * while rclcpp::ok() tick the tree and sleep to match tick rate with 1/ ` loop_timeout ` .


##  Languages


##  Folders and files


A lot of code is either inspired or copied from [ Nav2
](https://navigation.ros.org/) .


#  Provide feedback


###  Watchers


[ trees ](/berkeleyauv/behavior_tree/tree/master/trees "trees")


###  BtEngine


**method**


##  History


Yes

providedPorts()


Expected output


Last commit date

---|---|---|---

##  Latest commit


[ ](https://github.com "GitHub") © 2024 GitHub, Inc.


    * [ CI/CD & Automation ](/solutions/ci-cd/)
    * [ DevOps ](/solutions/devops/)
    * [ DevSecOps  ](https://resources.github.com/devops/fundamentals/devsecops/)


Search


#  Search code, repositories, users, issues, pull requests...


The remaining methods are not used and are not mandatory to override them.
Only some BT node plugins will require overriding ` on_wait_for_result()  ` to
check for preemption or check a timeout. The success, aborted, and cancelled
methods will default to ` SUCCESS  ` , ` FAILURE  ` , ` SUCCESS  `
respectively, if not overridden.


* Gazebo


[ 102  stars ](/BehaviorTree/BehaviorTree.ROS2/stargazers) [ 35  forks
](/BehaviorTree/BehaviorTree.ROS2/forks) [ Branches
](/BehaviorTree/BehaviorTree.ROS2/branches) [ Tags
](/BehaviorTree/BehaviorTree.ROS2/tags) [ Activity
](/BehaviorTree/BehaviorTree.ROS2/activity)


2\. the root that sends the tick to that fallback. We follow the left side.
Fallback sends a tick to task 1 which is a failure (of course this is only the
simulation ). Normally the decision SUCCESS or FAILURE is taken by the running
program. In our case callback returns Failure.
**Please note, now we run the Fallback node (OR) which needs at least one
SUCCESS to return SUCCESS therefore all the nodes can be checked. For the
sequence node (AND) the first FAILURE terminates “node investigation”.**


    bt_navigator:
      ros__parameters:
        use_sim_time: True
        global_frame: map
        robot_base_frame: base_link
        odom_topic: /odom
        default_bt_xml_filename: "navigate_w_replanning_and_recovery.xml"
        plugin_lib_names:
        - nav2_back_up_action_bt_node # other plugin
        - nav2_wait_action_bt_node    # our new plugin


[ 21 Commits  ](/berkeleyauv/behavior_tree/commits/master/)


This package provides abstractions that make building a extensible behavior
trees with ROS2 easy. The general development flow for adding new behaviors
and functionality to the AUV can be summarized in the following steps:


  * [ ![@facontidavide](https://avatars.githubusercontent.com/u/2822888?s=64&v=4) ](https://github.com/facontidavide)
  * [ ![@tony-p](https://avatars.githubusercontent.com/u/11678396?s=64&v=4) ](https://github.com/tony-p)
  * [ ![@vicmassy](https://avatars.githubusercontent.com/u/12095279?s=64&v=4) ](https://github.com/vicmassy)
  * [ ![@emersonknapp](https://avatars.githubusercontent.com/u/537409?s=64&v=4) ](https://github.com/emersonknapp)
  * [ ![@marip8](https://avatars.githubusercontent.com/u/18411310?s=64&v=4) ](https://github.com/marip8)
  * [ ![@SyllogismRXS](https://avatars.githubusercontent.com/u/573396?s=64&v=4) ](https://github.com/SyllogismRXS)
  * [ ![@mnumanuyar](https://avatars.githubusercontent.com/u/15452050?s=64&v=4) ](https://github.com/mnumanuyar)
  * [ ![@MarqRazz](https://avatars.githubusercontent.com/u/25058794?s=64&v=4) ](https://github.com/MarqRazz)
  * [ ![@CihatAltiparmak](https://avatars.githubusercontent.com/u/35902471?s=64&v=4) ](https://github.com/CihatAltiparmak)
  * [ ![@marj3220](https://avatars.githubusercontent.com/u/56129292?s=64&v=4) ](https://github.com/marj3220)


You signed in with another tab or window. [ Reload ]() to refresh your
session.  You signed out in another tab or window. [ Reload ]() to refresh
your session.  You switched accounts on another tab or window. [ Reload ]() to
refresh your session.  Dismiss alert


[ Action Client Example
](https://github.com/berkeleyauv/sub_behavior/blob/master/sub_behavior/plugins/action/move_distance.cpp)


Abstraction stack. (by author)


    * [ Actions  Automate any workflow  ](/features/actions)
    * [ Packages  Host and manage packages  ](/features/packages)
    * [ Security  Find and fix vulnerabilities  ](/features/security)
    * [ Codespaces  Instant dev environments  ](/features/codespaces)
    * [ Copilot  Write better code with AI  ](/features/copilot)
    * [ Code review  Manage code changes  ](/features/code-review)
    * [ Issues  Plan and track work  ](/features/issues)
    * [ Discussions  Collaborate outside of code  ](/features/discussions)


  * [ Code  ](/BehaviorTree/BehaviorTree.ROS2)
  * [ Issues  13  ](/BehaviorTree/BehaviorTree.ROS2/issues)
  * [ Pull requests  1  ](/BehaviorTree/BehaviorTree.ROS2/pulls)
  * [ Actions  ](/BehaviorTree/BehaviorTree.ROS2/actions)
  * [ Projects  0  ](/BehaviorTree/BehaviorTree.ROS2/projects)
  * [ Security  ](/BehaviorTree/BehaviorTree.ROS2/security)
  * [ Insights  ](/BehaviorTree/BehaviorTree.ROS2/pulse)


  * **BT.CPP** 4.1 or newer.
  * **ROS2** Humble or newer.


##  Overview  ¶


|

View all files

##  Repository files navigation


  * Action clients.
  * Service Clients.
  * Topic Subscribers.
  * Topic Publishers.


We finally give the builder to a factory to register. ` Wait  ` given to the
factory is the name in the behavior tree XML file that corresponds to this BT
node plugin. An example can be seen below, where the ` Wait  ` BT XML node
specifies a non-variable input port ` wait_duration  ` of 5 seconds.


[ btcpp_ros2_samples
](/BehaviorTree/BehaviorTree.ROS2/tree/humble/btcpp_ros2_samples
"btcpp_ros2_samples")


© Copyright 2023.


Include my email address so I can be contacted


##  [ Packages  0  ](/orgs/berkeleyauv/packages?repo_name=behavior_tree)


  * If node status is idle or a current goal is in progress as determined in ` goal_in_progress ` based on the status of the ` _goal_handle ` then send a goal, return ` RUNNING ` .
  * Else spin the node and check to see if the goal status has changed, return the value returned by ` process_goal_status `


* Nav2 (Including dependencies)


##  History


  * If node status is idle wait for service with timeout ` server_timeout `
  * If node status is idle call service server with message generated by ` populate_request `
  * Return ` Running ` and wait for the service to complete
  * Upon service call completion run ` handle_response ` and return the status code returned by handle response


Now that we have created our custom BT node, we need to export our plugin so
that it would be visible to the behavior tree when it loads a custom BT XML.
Plugins are loaded at runtime, and if they are not visible, then our BT
Navigator server won’t be able to load them or use them. In BehaviorTree.CPP,
exporting and loading plugins is handled by the ` BT_REGISTER_NODES  ` macro.


Clear


     </root>
     )";

    int main()
    {
        BehaviorTreeFactory factory;

        factory.registerNodeType<Task1>("Task1");
        factory.registerNodeType<Task2>("Task2");
        factory.registerNodeType<Task3>("Task3");
        factory.registerNodeType<Task4>("Task4");

        std::cout << "\n------------ BUILDING A NEW TREE ------------" << std::endl;

        auto tree = factory.createTreeFromText(xml_text_medium);

        tree.tickRoot();

        std::cout << std::endl;

        // }

        return 0;
    }


The following figure provides you with a general overview of BT. As you can
see the BT framework can be run independently, without ROS (as I mention while
you design a game). Later I will give you an example of how to build a simple
BT and run your first program. Please note the tutorials on the official site
are outstanding and should be studied accordingly to exhaust all the remaining
issues.


Researcher in underwater robotics


  1. Create a new .cpp file for the desired node, typically this will be in ` plugins/action ` within a ROS2 package
  2. The cpp file should contain a class that inherits ` public BtAction<ActionType> ` or ` public BtService<ServiceType> ` , we will override the necessary methods to generate a fully implemented behavior tree node.
  3. For action client override the ` ActionType::Goal populate_goal() ` method, for a service client override ` ServiceType::Request::SharedPtr populate_request() ` and ` BT::NodeStatus handle_response(ServiceType::Response::SharedPtr response) ` .
  4. (Optional) Override the ` static PortsList providedPorts() ` method to add additional ports, the code should look similar to the below example code segment


The XML describing the logic depicted above BT can be formulated:


[ include/  behavior_tree
](/berkeleyauv/behavior_tree/tree/master/include/behavior_tree "This path
skips through empty directories")


##  Use saved searches to filter your results more quickly


[ 1  tags  ](/BehaviorTree/BehaviorTree.ROS2/tags)


We read every piece of feedback, and take your input very seriously.


Name


[ trees ](/berkeleyauv/behavior_tree/tree/master/trees "trees")


Method is called when the behavior tree node is waiting for a result from the
ROS 2 action server it called. This could be used to check for updates to
preempt the current task, check for a timeout, or anything to compute while
waiting for the action to complete.


1\. presented BT consists of 4 tasks, falling to fallback, and sequence nodes.


[ README.md ](/berkeleyauv/behavior_tree/blob/master/README.md "README.md")


#  Saved searches


Add package dependencies to the ` CMakeLists.txt ` and add the following
snippet adapted to your behavior tree node


When working with other types of BT nodes (e.g. decorator, control, condition)
use the corresponding BT node, ` BT::DecoratorNode  ` , ` BT::ControlNode  ` ,
or ` BT::ConditionNode  ` . For BT action nodes that do _not_ utilize ROS 2
action interfaces, use the ` BT::ActionNodeBase  ` base class itself.


* ROS 2 (binary or build-from-source)


        * [ 1- Creating a new Behavior Plugin ](writing_new_behavior_plugin.html#creating-a-new-behavior-plugin)
        * [ 2- Exporting the Behavior Plugin ](writing_new_behavior_plugin.html#exporting-the-behavior-plugin)
        * [ 3- Pass the plugin name through params file ](writing_new_behavior_plugin.html#pass-the-plugin-name-through-params-file)
        * [ 4- Run Behavior Plugin ](writing_new_behavior_plugin.html#run-behavior-plugin)
    * [ Writing a New Navigator Plugin ](writing_new_navigator_plugin.html)
      * [ Overview ](writing_new_navigator_plugin.html#overview)
      * [ Requirements ](writing_new_navigator_plugin.html#requirements)
      * [ Tutorial Steps ](writing_new_navigator_plugin.html#tutorial-steps)
        * [ 1- Create a new Navigator Plugin ](writing_new_navigator_plugin.html#create-a-new-navigator-plugin)
        * [ 2- Exporting the navigator plugin ](writing_new_navigator_plugin.html#exporting-the-navigator-plugin)
        * [ 3- Pass the plugin name through the params file ](writing_new_navigator_plugin.html#pass-the-plugin-name-through-the-params-file)
        * [ 4- Run plugin ](writing_new_navigator_plugin.html#run-plugin)
  * [ Configuration Guide ](../../configuration/index.html)
    * [ Behavior-Tree Navigator ](../../configuration/packages/configuring-bt-navigator.html)
      * [ Parameters ](../../configuration/packages/configuring-bt-navigator.html#parameters)
      * [ Example ](../../configuration/packages/configuring-bt-navigator.html#example)
    * [ Behavior Tree XML Nodes ](../../configuration/packages/configuring-bt-xml.html)
      * [ Action Plugins ](../../configuration/packages/configuring-bt-xml.html#action-plugins)
        * [ Wait ](../../configuration/packages/bt-plugins/actions/Wait.html)
        * [ Spin ](../../configuration/packages/bt-plugins/actions/Spin.html)
        * [ BackUp ](../../configuration/packages/bt-plugins/actions/BackUp.html)
        * [ DriveOnHeading ](../../configuration/packages/bt-plugins/actions/DriveOnHeading.html)
        * [ AssistedTeleop ](../../configuration/packages/bt-plugins/actions/AssistedTeleop.html)
        * [ ComputePathToPose ](../../configuration/packages/bt-plugins/actions/ComputePathToPose.html)
        * [ FollowPath ](../../configuration/packages/bt-plugins/actions/FollowPath.html)
        * [ NavigateToPose ](../../configuration/packages/bt-plugins/actions/NavigateToPose.html)
        * [ ClearEntireCostmap ](../../configuration/packages/bt-plugins/actions/ClearEntireCostmap.html)
        * [ ClearCostmapExceptRegion ](../../configuration/packages/bt-plugins/actions/ClearCostmapExceptRegion.html)
        * [ ClearCostmapAroundRobot ](../../configuration/packages/bt-plugins/actions/ClearCostmapAroundRobot.html)
        * [ ReinitializeGlobalLocalization ](../../configuration/packages/bt-plugins/actions/ReinitializeGlobalLocalization.html)
        * [ TruncatePath ](../../configuration/packages/bt-plugins/actions/TruncatePath.html)
        * [ TruncatePathLocal ](../../configuration/packages/bt-plugins/actions/TruncatePathLocal.html)
        * [ PlannerSelector ](../../configuration/packages/bt-plugins/actions/PlannerSelector.html)
        * [ ControllerSelector ](../../configuration/packages/bt-plugins/actions/ControllerSelector.html)
        * [ SmootherSelector ](../../configuration/packages/bt-plugins/actions/SmootherSelector.html)
        * [ GoalCheckerSelector ](../../configuration/packages/bt-plugins/actions/GoalCheckerSelector.html)
        * [ ProgressCheckerSelector ](../../configuration/packages/bt-plugins/actions/ProgressCheckerSelector.html)
        * [ NavigateThroughPoses ](../../configuration/packages/bt-plugins/actions/NavigateThroughPoses.html)
        * [ ComputePathThroughPoses ](../../configuration/packages/bt-plugins/actions/ComputePathThroughPoses.html)
        * [ ComputeCoveragePath ](../../configuration/packages/bt-plugins/actions/ComputeCoveragePath.html)


Name  |  Default  |  Description
---|---|---
server_timeout  |  None  |  timeout for ` wait_for_service `
server_name  |  None  |  name of the service to call

###  BtAction


[
![Test](https://github.com/BehaviorTree/BehaviorTree.ROS2/actions/workflows/test.yml/badge.svg)
](https://github.com/BehaviorTree/BehaviorTree.ROS2/actions/workflows/test.yml)


In the constructor, we need to get any non-variable parameters that apply to
the behavior tree node. In this example, we need to get the value of the
duration to sleep from the input port of the behavior tree XML.


](https://speechify.com/medium?source=post_page-----
775ec0e97856--------------------------------)


bool ResourceManager::is_urdf_already_loaded() const { return is_urdf_loaded__; }


{
 auto current_command = input_command_.readFromRT();
 for (size_t i = 0; i < command_interfaces_.size(); ++i) {
 if (!std::isnan((*current_command)->data[i])) {
 command_interfaces_[i].set_value((*current_command)->data[i]);
 }
 }
 if (state_publisher_ && state_publisher_->trylock()) {
 state_publisher_->msg_.header.stamp = get_node()->now();
 state_publisher_->msg_.set_point = command_interfaces_[0].get_value();
 state_publisher_->unlockAndPublish();
 }
 return controller_interface::return_type::OK;
}
Implementing a forwarding controller
pluginlib_export_plugin_description_file(controller_interface rrbot_controller.xml)
#include "pluginlib/class_list_macros.hpp"
PLUGINLIB_EXPORT_CLASS(rrbot_controller::RRBotControllerArray, controller_interface::ControllerBase)
<library path="librrbot_controller_array">
 <class name="rrbot_controller/RRBotControllerArray"
 type="rrbot_controller::RRBotControllerArray"
base_class_type="controller_interface::ControllerBase">
 <description>
 RRBotControllerArray ros_control controller.
 </description>
 </class>
</library>
In CMakelists.txt:
In controller.cpp
In rrbot_controller.xml:
Let’s test it all!
ros2 launch rrbot_bringup rrbot_with_rrbot_controller_array.launch.py
ros2 topic pub /rrbot_controller/commands
example_interfaces/msg/Float64MultiArray "data:
- 0.5
- 0.5"
Messages and modifying a controller
std_msgs/MultiArrayLayout layout
 std_msgs/MultiArrayDimension[] dim
 string label


    if (result)
    {
      // TODO(destogl): is it better to check here if previous state was unconfigured instead of
      // checking if each state already exists? Or we should somehow know that transition has
      // happened and only then trigger this part of the code?
      // On the other side this part of the code should never be executed in real-time critical
      // thread, so it could be also OK as it is...
      for (const auto & interface : hardware_info_map_[hardware.get_name()].state_interfaces)
      {
        // add all state interfaces to available list
        auto found_it = std::find(
          available_state_interfaces_.begin(), available_state_interfaces_.end(), interface);


// CM API: Called in "update"-thread
void ResourceManager::make_controller_reference_interfaces_available(
  const std::string & controller_name)
{
  auto interface_names =
    resource_storage_->controllers_reference_interfaces_map_.at(controller_name);
  std::lock_guard<std::recursive_mutex> guard(resource_interfaces_lock_);
  resource_storage_->available_command_interfaces_.insert(
    resource_storage_->available_command_interfaces_.end(), interface_names.begin(),
    interface_names.end());
}


Thanks for explaining it. Is this restriction at the loaned interfaces level
already applied to the code in this PR?
Sorry, something went wrong.
All reactions
[
![christophfroehlich](https://avatars.githubusercontent.com/u/3367244?s=60&v=4)
](/christophfroehlich)
**[ christophfroehlich ](/christophfroehlich) ** requested changes  Mar 24,
2024
[ View reviewed changes  ](/ros-controls/ros2_control/pull/1240/files)
Copy link
Contributor
###
![@christophfroehlich](https://avatars.githubusercontent.com/u/3367244?s=48&v=4)
**[ christophfroehlich ](/christophfroehlich) ** left a comment  •
edited
There was a problem hiding this comment.
###  Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. [ Learn more
](https://docs.github.com/articles/managing-disruptive-comments/#hiding-a-
comment) .
Choose a reason  Spam  Abuse  Off Topic  Outdated  Duplicate  Resolved  Hide
comment
I like the approach, considering the cleaner code as demonstrated with
example_1 and the (as by now, theoretical) support of other datatypes. I don't
comment on the code as this has been done extensively by others already.
What is missing for my approval is an update to the documentation:
  * A migration guide [ here ](https://github.com/ros-controls/ros2_control/blob/master/doc/migration/Iron.rst) .
  * Update the [ Writing a Hardware Component ](https://control.ros.org/master/doc/ros2_control/hardware_interface/doc/writing_new_hardware_component.html#writing-a-hardware-component) section
Sorry, something went wrong.
All reactions
[ ![@bmagyar](https://avatars.githubusercontent.com/u/3524577?s=40&v=4)
](/bmagyar) [ bmagyar ](/bmagyar) mentioned this pull request  Apr 1, 2024
[ Changing how handles are used (in stages and PRs)  #1467  ](/ros-
controls/ros2_control/issues/1467)
Open
[
![@mamueluth](https://avatars.githubusercontent.com/u/19118679?s=40&u=f81462164d8259aace7a7f80ef76fd0c3dfeff1d&v=4)
](/mamueluth) [ mamueluth ](/mamueluth) [ force-pushed ](/ros-
controls/ros2_control/compare/7c07d0c6bf0b677fe0feedd48d5343c5b8e9079a..8dec983a6d3ca945ad6f4277b935f6d466e68120)


  // TODO(destogl): Propagate "false" up, if happens in initialize_hardware
  void load_and_initialize_actuator(const HardwareInfo & hardware_info)
  {
    auto load_and_init_actuators = [&](auto & container)
    {
      check_for_duplicates(hardware_info);
      load_hardware<Actuator, ActuatorInterface>(hardware_info, actuator_loader_, container);
      if (initialize_hardware(hardware_info, container.back()))
      {
        import_state_interfaces(container.back());
        import_command_interfaces(container.back());
      }
      else
      {
        RCUTILS_LOG_WARN_NAMED(
          "resource_manager",
          "Actuator hardware component '%s' from plugin '%s' failed to initialize.",
          hardware_info.name.c_str(), hardware_info.hardware_plugin_name.c_str());
      }
    };


  template <class HardwareT>
  bool activate_hardware(HardwareT & hardware)
  {
    bool result = trigger_and_print_hardware_state_transition(
      std::bind(&HardwareT::activate, &hardware), "activate", hardware.get_name(),
      lifecycle_msgs::msg::State::PRIMARY_STATE_ACTIVE);


[ [ legend ](graph_legend.html) ]


// CM API: Called in "callback/slow"-thread
return_type ResourceManager::set_component_state(
  const std::string & component_name, rclcpp_lifecycle::State & target_state)
{
  using lifecycle_msgs::msg::State;
  using std::placeholders::_1;
  using std::placeholders::_2;


  return read_write_status;
}


controls/ros2_control/pull/1240/commits/667892dcb4cc0a6267d443b1add559f241ec8c3f
"first steps towards variants and storing of value in handle, missing:
* variant
* adjusting of resource manager") ` …
` [ 667892d ](/ros-
controls/ros2_control/pull/1240/commits/667892dcb4cc0a6267d443b1add559f241ec8c3f)
`

    * variant
    * adjusting of resource manager
[ ![@mamueluth](https://avatars.githubusercontent.com/u/19118679?s=40&v=4)
](/mamueluth)
` [ add variant support ](/ros-
controls/ros2_control/pull/1240/commits/62300d7b62b354e347156c7e0bbb8be837c0a51f
"add variant support") `
` [ 62300d7 ](/ros-
controls/ros2_control/pull/1240/commits/62300d7b62b354e347156c7e0bbb8be837c0a51f)
`
[ ![@mamueluth](https://avatars.githubusercontent.com/u/19118679?s=40&v=4)
](/mamueluth)
` [ adjusted resource manager to work with shared_ptr adapt actuator,sensor
](/ros-
controls/ros2_control/pull/1240/commits/617c5420563d52b88ff485c1df0aa86064ab3fc5
"adjusted resource manager to work with shared_ptr adapt actuator,sensor
and system") ` …
` [ 617c542 ](/ros-
controls/ros2_control/pull/1240/commits/617c5420563d52b88ff485c1df0aa86064ab3fc5)
`

    and system
[ ![@mamueluth](https://avatars.githubusercontent.com/u/19118679?s=40&v=4)
](/mamueluth)
` [ cleanup ](/ros-
controls/ros2_control/pull/1240/commits/e4ee06dbc334d214aa8c4862f61b52b64ea77525
"cleanup") `
` [ e4ee06d ](/ros-
controls/ros2_control/pull/1240/commits/e4ee06dbc334d214aa8c4862f61b52b64ea77525)
`


size_t ResourceManager::sensor_components_size() const
{
  return resource_storage_->sensors_.size();
}