|
| 1 | +#include "behaviortree_cpp/bt_factory.h" |
| 2 | + |
| 3 | +using namespace BT; |
| 4 | + |
| 5 | +/** |
| 6 | + * @brief Show how to access an entry in the blackboard by pointer. |
| 7 | + * This approach is more verbose, but thread-safe |
| 8 | + * |
| 9 | + */ |
| 10 | +class PushIntoVector : public SyncActionNode |
| 11 | +{ |
| 12 | +public: |
| 13 | + PushIntoVector(const std::string& name, const NodeConfig& config) : |
| 14 | + SyncActionNode(name, config) |
| 15 | + {} |
| 16 | + |
| 17 | + NodeStatus tick() override |
| 18 | + { |
| 19 | + const int number = getInput<int>("value").value(); |
| 20 | + if(auto any_ptr = getLockedPortContent("vector")) |
| 21 | + { |
| 22 | + // inside this scope, any_ptr provides a mutex-protected, |
| 23 | + // thread-safe way to access an element inside the blackboard. |
| 24 | + if(auto vect_ptr = any_ptr->castPtr<std::vector<int>>()) |
| 25 | + { |
| 26 | + vect_ptr->push_back(number); |
| 27 | + std::cout << "Value ["<< number <<"] pushed into the vector. New size: " |
| 28 | + << vect_ptr->size() << "\n"; |
| 29 | + } |
| 30 | + else { |
| 31 | + // This happens when the entry of the blackboard is empty or if |
| 32 | + // we tried to cast to the wrong type. |
| 33 | + // Let's insert a new vector<int> with a single value |
| 34 | + std::vector<int> vect = {number}; |
| 35 | + any_ptr.assign(vect); |
| 36 | + std::cout << "We created a new vector, containing value ["<< number <<"]\n"; |
| 37 | + } |
| 38 | + return NodeStatus::SUCCESS; |
| 39 | + } |
| 40 | + else { |
| 41 | + return NodeStatus::FAILURE; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + static PortsList providedPorts() |
| 46 | + { |
| 47 | + return {BT::BidirectionalPort<std::vector<int>>("vector"), |
| 48 | + BT::InputPort<int>("value")}; |
| 49 | + } |
| 50 | +}; |
| 51 | + |
| 52 | +//-------------------------------------------------------------- |
| 53 | + |
| 54 | +// clang-format off |
| 55 | +static const char* xml_tree = R"( |
| 56 | + <root BTCPP_format="4" > |
| 57 | + <BehaviorTree ID="TreeA"> |
| 58 | + <Sequence> |
| 59 | + <PushIntoVector vector="{vect}" value="3"/> |
| 60 | + <PushIntoVector vector="{vect}" value="5"/> |
| 61 | + <PushIntoVector vector="{vect}" value="7"/> |
| 62 | + </Sequence> |
| 63 | + </BehaviorTree> |
| 64 | + </root> |
| 65 | + )"; |
| 66 | + |
| 67 | +// clang-format on |
| 68 | + |
| 69 | +int main() |
| 70 | +{ |
| 71 | + BehaviorTreeFactory factory; |
| 72 | + factory.registerNodeType<PushIntoVector>("PushIntoVector"); |
| 73 | + |
| 74 | + auto tree = factory.createTreeFromText(xml_tree); |
| 75 | + tree.tickWhileRunning(); |
| 76 | + return 0; |
| 77 | +} |
0 commit comments