注册
registerNodeType 用于注册类类型节点。
registerSimpleAction 用于注册普通函数或 lambda 作为节点。
如果想用类注册,应该定义一个继承自 BT::SyncActionNode 的类,并实现 tick()
registerNodeType
继承BT::SyncActionNode 的类,并重写tick
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class SaySomething : public BT::SyncActionNode{public :SaySomething (const std::string &name):BT::SyncActionNode (name,{}) {} BT::NodeStatus tick () override {std::cout<<"fixed:" <<this ->name ()<<std::endl; return BT::NodeStatus::SUCCESS;} };
在ros2节点的实现中:
1 2 3 4 5 6 7 BT::BehaviorTreeFactory factory; factory.registerNodeType <SaySomething>("SaySomething" ); auto tree = factory.createTreeFromFile ("src/bt/src/tree.xml" );tree.tickRootWhileRunning ();
registerSimpleAction
只需要定义一个返回类型为BT::NodeStatus 的函数
1 2 3 4 5 6 7 BT::NodeStatus SaySomething () {std::cout << "Fixed" << std::endl; return BT::NodeStatus::SUCCESS;};
在ros2的节点中注册行为树节点时,使用bind绑定:
1 factory.registerSimpleAction ("SaySomething" , std::bind (SaySomething));
Ports
当一个行为树有输入输出端口时,这个端口必须在一个静态 函数中声明。
必须是static!!!
1 static MyCustomNode::PortsList providedPorts () ;
端口的输入使用这种格式:TreeNode::getInput<T>(key)。
例如在我的例子中:
1 BT::Optional<std::string> msg = getInput <std::string>("message" );
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 static BT::PortsList providedPorts () {return {BT::OutputPort <std::string>("text" )} ;} BT::NodeStatus tick () override {setOutput ("text" , "A text" );return BT::NodeStatus::SUCCESS;}
在xml文件中的配置:
1 2 3 4 5 <SaySomething message ="A Message" /> <ThinkWhatToSay text ="{_answer}" /> <SaySomething message ="{_answer}" />
ReactiveSequence
在 BehaviorTree.CPP 中,Sequence 和 ReactiveSequence 的主要区别在于节点的 tick 行为:
Sequence :每次 tick 时,从上到下依次 tick 子节点。如果某个子节点返回 RUNNING 或 FAILURE,Sequence 会停止并返回该状态。下次 tick 时,会从上次未完成的子节点继续执行,前面的 SUCCESS 节点不会再被 tick,只有后续节点会被 tick。
ReactiveSequence :每次 tick 时,总是从第一个子节点开始,依次 tick 所有子节点。即使前面的节点已经返回过 SUCCESS,下一次 tick 也会重新 tick 这些节点。只要有一个子节点返回 RUNNING 或 FAILURE,ReactiveSequence 就会立即返回该状态。
实际效果:
用 Sequence,前面已经成功的节点不会重复执行,只有未完成的节点会被 tick。
用 ReactiveSequence,每次 tick 都会从头到尾重新 tick 所有子节点,适合需要持续监控前置条件或前置动作的场景。
不使用ReactiveSequence
Tree:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <root BTCPP_format ="3" > <BehaviorTree ID ="MainTree" > <Sequence name ="root_sequence" > <SaySomething message ="A Message" /> <ThinkWhatToSay text ="{_answer}" /> <SaySomething message ="{_answer}" /> <GetPosition position ="1;2" /> <Count /> </Sequence > </BehaviorTree > </root >
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 [INFO] [1768807916.325380944] [bt_node]: BT Node Started ---ticking fixed:SaySomething Message is :A Message fixed:SaySomething Message is :A text Position:(1,2) Count Start! status:RUNNING ---ticking Count is Running! NUM:0 status:RUNNING ---ticking Count is Running! NUM:1 status:RUNNING ...emit... ---ticking Count is Running! NUM:10 status:RUNNING ---ticking Count is Running! Count Finished! status:SUCCESS
使用ReactiveSequence
tree:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 <root BTCPP_format ="3" > <BehaviorTree ID ="MainTree" > <ReactiveSequence > <SaySomething message ="A Message" /> <ThinkWhatToSay text ="{_answer}" /> <SaySomething message ="{_answer}" /> <GetPosition position ="1;2" /> <Sequence name ="root_sequence" > <Count /> </Sequence > </ReactiveSequence > </BehaviorTree > </root >
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 [INFO] [1768808382.466450956] [bt_node]: BT Node Started ---ticking fixed:SaySomething Message is :A Message fixed:SaySomething Message is :A text Position:(1,2) Count Start! status:RUNNING ---ticking fixed:SaySomething Message is :A Message fixed:SaySomething Message is :A text Position:(1,2) Count is Running! NUM:0 status:RUNNING ...emit... ---ticking fixed:SaySomething Message is :A Message fixed:SaySomething Message is :A text Position:(1,2) Count is Running! NUM:10 status:RUNNING ---ticking fixed:SaySomething Message is :A Message fixed:SaySomething Message is :A text Position:(1,2) Count is Running! Count Finished! status:SUCCESS
完整代码
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 #include <behaviortree_cpp_v3/action_node.h> #include <behaviortree_cpp_v3/basic_types.h> #include <behaviortree_cpp_v3/exceptions.h> #include <behaviortree_cpp_v3/tree_node.h> #include <iostream> #include <iterator> #include <memory> #include <rclcpp/logging.hpp> #include <rclcpp/node.hpp> #include <string> #include <tinyxml2.h> #include <rclcpp/rclcpp.hpp> #include "behaviortree_cpp_v3/bt_factory.h" using namespace std;struct Position2D {double x;double y;}; namespace BT {template <> inline Position2D convertFromString (StringView str) {auto parts = BT::splitString (str,';' );if (parts.size ()!=2 ){throw BT::RuntimeError ("invalid position input" );} else {Position2D output; output.x = BT::convertFromString <double >(parts[0 ]); output.y = BT::convertFromString <double >(parts[1 ]); return output;} } } class SaySomething : public BT::SyncActionNode{public :SaySomething (const std::string &name,const BT::NodeConfiguration& config):BT::SyncActionNode (name,config) {} static BT::PortsList providedPorts () {return {BT::InputPort <std::string>("message" )};} BT::NodeStatus tick () override {BT::Optional<std::string> msg = getInput <std::string>("message" ); if (!msg){throw BT::RuntimeError ("missing [message]" ,msg.error ());} std::cout<<"fixed:" <<this ->name ()<<std::endl; std::cout<<"Message is :" <<msg.value ()<<std::endl; return BT::NodeStatus::SUCCESS;} }; class ThinkWhatToSay : public BT::SyncActionNode{public :ThinkWhatToSay (const string& name, const BT::NodeConfiguration config): BT::SyncActionNode (name, config) {} static BT::PortsList providedPorts () {return {BT::OutputPort <std::string>("text" )} ;} BT::NodeStatus tick () override {setOutput ("text" , "A text" );return BT::NodeStatus::SUCCESS;} }; class GetPosition : public BT::SyncActionNode{public : GetPosition (const string& name,const BT::NodeConfiguration& config) : BT::SyncActionNode (name,config){} static BT::PortsList providedPorts () {return {BT::InputPort <Position2D>("position" )};} BT::NodeStatus tick () override {BT::Optional<Position2D> Position = getInput <Position2D>("position" ); if (!Position){throw ("Position empty!" );}else { std::cout<<"Position:(" <<Position->x<<"," <<Position->y<<")" <<std::endl; } return BT::NodeStatus::SUCCESS;} }; class SetGoal : public BT::SyncActionNode{public : SetGoal (const string& name,const BT::NodeConfiguration& config) : BT::SyncActionNode (name,config){} static BT::PortsList providedPorts () {return {BT::OutputPort <Position2D>("goal" )};} BT::NodeStatus tick () override {Position2D goal; goal.x=8 ; goal.y=9 ; setOutput <Position2D>("goal" , goal);return BT::NodeStatus::SUCCESS;} }; class Count : public BT::StatefulActionNode{public : Count (const string& name,const BT::NodeConfiguration config):BT::StatefulActionNode (name,config){} BT::NodeStatus onStart () override ;BT::NodeStatus onRunning () override ;void onHalted () override ;static BT::PortsList providedPorts () {return {};} private :int num;}; BT::NodeStatus Count::onStart () {std::cout<<"Count Start!" <<std::endl; num = 0 ; return BT::NodeStatus::RUNNING;}; BT::NodeStatus Count::onRunning () {std::cout<<"Count is Running!" <<std::endl; if (num<=10 ){std::cout<<"NUM:" <<num<<std::endl; num++; return BT::NodeStatus::RUNNING;} else {std::cout<<"Count Finished!" <<std::endl; return BT::NodeStatus::SUCCESS;} } void Count::onHalted () {std::cout << "Count Halted!" << std::endl; } class BTNode : public rclcpp::Node{public :BTNode (std::string name) : Node (name){RCLCPP_INFO (this ->get_logger (),"BT Node Started" );BT::BehaviorTreeFactory factory; factory.registerNodeType <SaySomething>("SaySomething" ); factory.registerNodeType <ThinkWhatToSay>("ThinkWhatToSay" ); factory.registerNodeType <GetPosition>("GetPosition" ); factory.registerNodeType <Count>("Count" ); auto tree = factory.createTreeFromFile ("src/bt/src/tree.xml" );std::cout<<"---ticking" <<std::endl; auto status = tree.tickRoot ();std::cout<<"status:" <<BT::toStr (status)<<std::endl<<std::endl; while (status==BT::NodeStatus::RUNNING){std::cout<<"---ticking" <<std::endl; status = tree.tickRoot (); std::cout<<"status:" <<BT::toStr (status)<<std::endl<<std::endl; } } }; int main (int argc,char ** argv) {rclcpp::init (argc,argv); auto node = make_shared <BTNode>("bt_node" );rclcpp::spin (node); rclcpp::shutdown (); return 0 ; }
CMakeLists.txt:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 cmake_minimum_required (VERSION 3.8 )project (bt)set (CMAKE_CXX_STANDARD 17 )if (CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang" )add_compile_options (-Wall -Wextra -Wpedantic)endif () find_package (ament_cmake REQUIRED)find_package (behaviortree_cpp_v3 REQUIRED)find_package (rclcpp REQUIRED)find_package (tinyxml2_vendor REQUIRED) if (BUILD_TESTING)find_package (ament_lint_auto REQUIRED)set (ament_cmake_copyright_FOUND TRUE )set (ament_cmake_cpplint_FOUND TRUE )ament_lint_auto_find_test_dependencies() endif () ament_package() add_executable (bt src/bt.cpp)ament_target_dependencies(bt rclcpp behaviortree_cpp_v3 tinyxml2_vendor) install (TARGETSbt DESTINATION lib/${PROJECT_NAME} )
xml:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 <root BTCPP_format ="3" main_tree_to_execute ="MainTree" > <BehaviorTree ID ="MainTree" > <Sequence > <ReactiveSequence > <SaySomething message ="A Message" /> <ThinkWhatToSay text ="{_answer}" /> <SaySomething message ="{_answer}" /> <GetPosition position ="1;2" /> <Sequence name ="root_sequence" > <Count /> </Sequence > </ReactiveSequence > <SubTree ID ="SubTree" /> </Sequence > </BehaviorTree > <BehaviorTree ID ="SubTree" > <Sequence > <SaySomething message ="SubTree said" /> </Sequence > </BehaviorTree > </root >