実際のところ
#include <behaviortree_cpp_v3/behavior_tree.h>
#include <behaviortree_cpp_v3/bt_factory.h>
#include <iostream>
#include <string>
using namespace BT;
class ApproachObject : public BT::SyncActionNode
{
public:
ApproachObject(const std::string& name) :
BT::SyncActionNode(name, {})
{}
BT::NodeStatus tick() override
{
std::cout << "ApproachObject: " << this->name() << std::endl;
return BT::NodeStatus::SUCCESS;
}
};
BT::NodeStatus CheckBattery()
{
std::cout << "[ Battery: OK ]" << std::endl;
return BT::NodeStatus::SUCCESS;
}
class GripperInterface
{
public:
GripperInterface(): _open(true) {}
NodeStatus open()
{
_open = true;
std::cout << "GripperInterface::open" << std::endl;
return NodeStatus::SUCCESS;
}
NodeStatus close()
{
std::cout << "GripperInterface::close" << std::endl;
_open = false;
return NodeStatus::SUCCESS;
}
private:
bool _open;
};
class SaySomething : public SyncActionNode
{
public:
SaySomething(const std::string& name, const NodeConfiguration& config)
: SyncActionNode(name, config)
{ }
static PortsList providedPorts()
{
return { InputPort<std::string>("message") };
}
NodeStatus tick() override
{
auto msg = getInput<std::string>("message");
std::cout << "Robot says: " << msg.value() << std::endl;
return NodeStatus::SUCCESS;
}
};
class ThinkWhatToSay : public SyncActionNode
{
public:
ThinkWhatToSay(const std::string& name, const NodeConfiguration& config)
: SyncActionNode(name, config)
{ }
static PortsList providedPorts()
{
return { OutputPort<std::string>("text") };
}
NodeStatus tick() override
{
setOutput("text", "The answer is 42" );
return NodeStatus::SUCCESS;
}
};
int main()
{
BehaviorTreeFactory factory;
factory.registerNodeType<ApproachObject>("ApproachObject");
factory.registerSimpleCondition("CheckBattery", [&](TreeNode&) { return CheckBattery(); });
GripperInterface gripper;
factory.registerSimpleAction("OpenGripper", [&](TreeNode&){ return gripper.open(); } );
factory.registerSimpleAction("CloseGripper", [&](TreeNode&){ return gripper.close(); } );
factory.registerNodeType<SaySomething>("SaySomething");
factory.registerNodeType<ThinkWhatToSay>("ThinkWhatToSay");
std::string xml_file = "/home/tsukarm/dev_ws/src/your_behavior_tree_package/config/my_tree.xml";
auto tree = factory.createTreeFromFile( "/home/tsukarm/dev_ws/src/your_behavior_tree_package/config/my_tree.xml");
tree.tickRootWhileRunning();
return 0;
}
<root main_tree_to_execute = "MainTree" BTCPP_format="4">
<BehaviorTree ID="MainTree">
<Sequence name="root_sequence">
<ApproachObject name="approach_object"/>
<CheckBattery name="check_battery"/>
<CloseGripper name="close_gripper"/>
<OpenGripper name="open_gripper"/>
<SaySomething message="hello" />
<ThinkWhatToSay text="{the_answer}"/>
<SaySomething message="{the_answer}" />
</Sequence>
</BehaviorTree>
</root>
実行
$ ros2 run your_behavior_tree_package simple_action_node
ApproachObject: approach_object
[ Battery: OK ]
GripperInterface::close
GripperInterface::open
Robot says: hello
Robot says: The answer is 42