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 const NodeStatistics& getStatistics(const std::string& path) const;
55
56 // find the statistics of a node, based on its TreeNode::UID()
57 const NodeStatistics& getStatistics(uint16_t uid) const;
58
59 // all statistics
60 const std::unordered_map<uint16_t, NodeStatistics>& statistics() const;
61
62 // path to UID map
63 const std::unordered_map<std::string, uint16_t>& pathToUID() const;
64
65 const std::map<uint16_t, std::string>& uidToPath() const;
66
67private:
68 std::unordered_map<uint16_t, NodeStatistics> _statistics;
69 std::unordered_map<std::string, uint16_t> _path_to_uid;
70 std::map<uint16_t, std::string> _uid_to_path;
71
72 virtual void callback(Duration timestamp, const TreeNode& node, NodeStatus prev_status,
73 NodeStatus status) override;
74};
75
76} // namespace BT
77
78#endif // BT_OBSERVER_H
Definition: abstract_logger.h:16
Struct used to store a tree. If this object goes out of scope, the tree is destroyed.
Definition: bt_factory.h:96
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