Sarafun Behavior Trees package  1
Behavior trees for the SARAFun project
 All Data Structures Namespaces Functions Variables Enumerations Enumerator
TreeRunner.cpp
1 #include <sarafun_tree/TreeRunner.h>
2 
3 using namespace BT;
4 namespace sarafun
5 {
6  TreeRunner::TreeRunner(int tick_period)
7  {
8  tick_period_ = tick_period;
9  parser_ = 0;
10  tree_thread_ = 0;
11  draw_thread_ = 0;
12  root_ = new SequenceNode("root"); // Make a permanent root to avoid screwing up the draw method
13  }
14 
15  bool TreeRunner::startTree(std::string tree_description_path)
16  {
17  ControlNode *tree_root;
18  if (parser_ != 0)
19  {
20  ROS_WARN("startTree called with an active tree running. Will terminate active tree.");
21  stopTree();
22  }
23 
24  parser_ = new bt_parser::Parser(tree_description_path);
25 
26  try
27  {
28  tree_root = dynamic_cast<ControlNode *>(parser_->parseTree());
29 
30  if (tree_root == nullptr)
31  {
32  return false;
33  }
34 
35  root_->AddChild(tree_root);
36 
37  if (draw_thread_ == 0)
38  {
39  ROS_DEBUG("Start drawing");
40  draw_thread_ = new boost::thread(&drawTree, root_);
41  }
42  }
43  catch(BehaviorTreeException &Exception)
44  {
45  ROS_ERROR("%s", Exception.what());
46  return false;
47  }
48 
49  tree_thread_ = new boost::thread(Execute, root_, tick_period_);
50 
51  enableDrawing();
52  return true;
53  }
54 
55  void TreeRunner::stopTree()
56  {
57  disableDrawing();
58  sleep(1.0); // TODO: Make this deterministic
59  if (tree_thread_ != 0)
60  {
61  if (tree_thread_->joinable())
62  {
63  ROS_INFO("Stopping a running behavior tree");
64  try
65  {
66  tree_thread_->interrupt();
67  tree_thread_->join();
68  delete tree_thread_;
69  }
70  catch (std::exception &e)
71  {
72  ROS_WARN("Exception when joining the tree thread: %s", e.what());
73  }
74  tree_thread_ = 0;
75  }
76 
77  delete parser_;
78  parser_ = 0;
79  }
80  else
81  {
82  ROS_WARN("stopTree called with no tree to stop");
83  }
84  }
85 }