Nav2 Navigation Stack - jazzy  jazzy
ROS 2 Navigation Stack
behavior_tree_engine.cpp
1 // Copyright (c) 2018 Intel Corporation
2 // Copyright (c) 2020 Florian Gramss
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 
16 #include "nav2_behavior_tree/behavior_tree_engine.hpp"
17 
18 #include <memory>
19 #include <string>
20 #include <vector>
21 
22 #include "rclcpp/rclcpp.hpp"
23 #include "behaviortree_cpp/json_export.h"
24 #include "behaviortree_cpp/utils/shared_library.h"
25 #include "nav2_behavior_tree/json_utils.hpp"
26 
27 namespace nav2_behavior_tree
28 {
29 
31  const std::vector<std::string> & plugin_libraries, rclcpp::Node::SharedPtr node)
32 {
33  BT::SharedLibrary loader;
34  for (const auto & p : plugin_libraries) {
35  factory_.registerFromPlugin(loader.getOSName(p));
36  }
37 
38  // clock for throttled debug log
39  clock_ = node->get_clock();
40 
41  // FIXME: the next two line are needed for back-compatibility with BT.CPP 3.8.x
42  // Note that the can be removed, once we migrate from BT.CPP 4.5.x to 4.6+
43  BT::ReactiveSequence::EnableException(false);
44  BT::ReactiveFallback::EnableException(false);
45 }
46 
47 BtStatus
49  BT::Tree * tree,
50  std::function<void()> onLoop,
51  std::function<bool()> cancelRequested,
52  std::chrono::milliseconds loopTimeout)
53 {
54  rclcpp::WallRate loopRate(loopTimeout);
55  BT::NodeStatus result = BT::NodeStatus::RUNNING;
56 
57  // Loop until something happens with ROS or the node completes
58  try {
59  while (rclcpp::ok() && result == BT::NodeStatus::RUNNING) {
60  if (cancelRequested()) {
61  tree->haltTree();
62  return BtStatus::CANCELED;
63  }
64 
65  result = tree->tickOnce();
66 
67  if (result == BT::NodeStatus::RUNNING || result == BT::NodeStatus::IDLE) {
68  onLoop();
69  }
70 
71  if (!loopRate.sleep()) {
72  RCLCPP_DEBUG_THROTTLE(
73  rclcpp::get_logger("BehaviorTreeEngine"),
74  *clock_, 1000,
75  "Behavior Tree tick rate %0.2f was exceeded!",
76  1.0 / (loopRate.period().count() * 1.0e-9));
77  }
78  }
79  } catch (const BT::NodeExecutionError & ex) {
80  RCLCPP_ERROR(
81  rclcpp::get_logger("BehaviorTreeEngine"),
82  "BT Exception at Node: [%s] (Path: %s). Original error: %s. Exiting with failure.",
83  ex.failedNode().registration_name.c_str(),
84  ex.failedNode().node_path.c_str(),
85  ex.originalMessage().c_str());
86  return BtStatus::FAILED;
87  } catch (const std::exception & ex) {
88  RCLCPP_ERROR(
89  rclcpp::get_logger("BehaviorTreeEngine"),
90  "Behavior tree threw exception: %s. Exiting with failure.", ex.what());
91  return BtStatus::FAILED;
92  }
93 
94  return (result == BT::NodeStatus::SUCCESS) ? BtStatus::SUCCEEDED : BtStatus::FAILED;
95 }
96 
97 BT::Tree
99  const std::string & xml_string,
100  BT::Blackboard::Ptr blackboard)
101 {
102  return factory_.createTreeFromText(xml_string, blackboard);
103 }
104 
105 BT::Tree
107  const std::string & file_path,
108  BT::Blackboard::Ptr blackboard)
109 {
110  return factory_.createTreeFromFile(file_path, blackboard);
111 }
112 
113 void
115  BT::Tree * tree,
116  uint16_t server_port)
117 {
118  // This logger publish status changes using Groot2
119  groot_monitor_ = std::make_unique<BT::Groot2Publisher>(*tree, server_port);
120 
121  // Register common types JSON definitions
122  BT::RegisterJsonDefinition<builtin_interfaces::msg::Time>();
123  BT::RegisterJsonDefinition<std_msgs::msg::Header>();
124 }
125 
126 void
128 {
129  if (groot_monitor_) {
130  groot_monitor_.reset();
131  }
132 }
133 
134 // In order to re-run a Behavior Tree, we must be able to reset all nodes to the initial state
135 void
137 {
138  // this halt signal should propagate through the entire tree.
139  tree.haltTree();
140 }
141 
142 } // namespace nav2_behavior_tree
BehaviorTreeEngine(const std::vector< std::string > &plugin_libraries, rclcpp::Node::SharedPtr node)
A constructor for nav2_behavior_tree::BehaviorTreeEngine.
void addGrootMonitoring(BT::Tree *tree, uint16_t server_port)
Add Groot2 monitor to publish BT status changes.
BT::Tree createTreeFromFile(const std::string &file_path, BT::Blackboard::Ptr blackboard)
Function to create a BT from an XML file.
BT::Tree createTreeFromText(const std::string &xml_string, BT::Blackboard::Ptr blackboard)
Function to create a BT from a XML string.
void haltAllActions(BT::Tree &tree)
Function to explicitly reset all BT nodes to initial state.
BtStatus run(BT::Tree *tree, std::function< void()> onLoop, std::function< bool()> cancelRequested, std::chrono::milliseconds loopTimeout=std::chrono::milliseconds(10))
Function to execute a BT at a specific rate.