BehaviorTree
Core Library to create and execute Behavior Trees
Loading...
Searching...
No Matches
bt_observer.h
1#ifndef BT_OBSERVER_H
2#define BT_OBSERVER_H
3
4#include "behaviortree_cpp/loggers/abstract_logger.h"
5
6#include <cstring>
7
8namespace BT
9{
10
11/**
12 * @brief The TreeObserver is used to collect statistics about which nodes
13 * are executed and their returned status.
14 *
15 * It is particularly useful to create unit tests, since if allow to
16 * determine if a certain transition happened as expected, in a non intrusive way.
17 */
19{
20public:
21 TreeObserver(const BT::Tree& tree);
22 ~TreeObserver() override;
23
24 TreeObserver(const TreeObserver&) = delete;
25 TreeObserver& operator=(const TreeObserver&) = delete;
26 TreeObserver(TreeObserver&&) = delete;
27 TreeObserver& operator=(TreeObserver&&) = delete;
28
29 virtual void flush() override
30 {}
31
32 void resetStatistics();
33
34 struct NodeStatistics
35 {
36 // Last __valid__ result, either SUCCESS or FAILURE
37 NodeStatus last_result = NodeStatus::IDLE;
38 // Last status. Can be any status, including IDLE or SKIPPED
39 NodeStatus current_status = NodeStatus::IDLE;
40
41 // count status transitions, excluding transition to IDLE
42 unsigned transitions_count = 0;
43 // count number of transitions to SUCCESS
44 unsigned success_count = 0;
45 // count number of transitions to FAILURE
46 unsigned failure_count = 0;
47 // count number of transitions to SKIPPED
48 unsigned skip_count = 0;
49
50 Duration last_timestamp = {};
51 };
52
53 // find the statistics of a node, based on its path.
54 // If more nodes have the same path, this is the first one in depth-first order.
55 const NodeStatistics& getStatistics(const std::string& path) const;
56
57 // find the statistics of a node, based on its TreeNode::UID()
58 const NodeStatistics& getStatistics(uint16_t uid) const;
59
60 // all statistics
61 const std::unordered_map<uint16_t, NodeStatistics>& statistics() const;
62
63 // path to UID map
64 const std::unordered_map<std::string, uint16_t>& pathToUID() const;
65
66 const std::map<uint16_t, std::string>& uidToPath() const;
67
68private:
69 std::unordered_map<uint16_t, NodeStatistics> _statistics;
70 std::unordered_map<std::string, uint16_t> _path_to_uid;
71 std::map<uint16_t, std::string> _uid_to_path;
72
73 virtual void callback(Duration timestamp, const TreeNode& node, NodeStatus prev_status,
74 NodeStatus status) override;
75};
76
77} // namespace BT
78
79#endif // BT_OBSERVER_H
Definition: abstract_logger.h:18
Struct used to store a tree. If this object goes out of scope, the tree is destroyed.
Definition: bt_factory.h:100
Abstract base class for Behavior Tree Nodes.
Definition: tree_node.h:154
The TreeObserver is used to collect statistics about which nodes are executed and their returned stat...
Definition: bt_observer.h:19
Definition: action_node.h:24
NodeStatus
Definition: basic_types.h:34
Definition: bt_observer.h:35