Line data Source code
1 : #include "trigger/LivetimeCounter.hpp"
2 :
3 : #include "logging/Logging.hpp"
4 :
5 : #include <sstream>
6 :
7 : namespace dunedaq::trigger {
8 :
9 0 : LivetimeCounter::LivetimeCounter(LivetimeCounter::State state)
10 0 : : m_state(state)
11 0 : , m_last_state_change_time(now())
12 : {
13 0 : TLOG_DEBUG(1) << "Starting LivetimeCounter in state " << get_state_name(state);
14 0 : m_state_times[State::kLive] = 0;
15 0 : m_state_times[State::kDead] = 0;
16 0 : m_state_times[State::kPaused] = 0;
17 0 : }
18 :
19 0 : LivetimeCounter::~LivetimeCounter()
20 : {
21 0 : std::string report = get_report_string();
22 0 : TLOG() << "LivetimeCounter stopping. Counts: " << report;
23 0 : }
24 :
25 : void
26 0 : LivetimeCounter::update_map()
27 : {
28 : // Caller must lock the mutex, so we don't here
29 0 : auto current_time = now();
30 0 : auto delta = (current_time - m_last_state_change_time);
31 0 : m_state_times[m_state] += delta;
32 0 : m_last_state_change_time = current_time;
33 0 : }
34 :
35 : void
36 0 : LivetimeCounter::set_state(LivetimeCounter::State state)
37 : {
38 0 : std::lock_guard<std::mutex> l(m_mutex);
39 0 : update_map(); // Add the time to the old state
40 0 : TLOG_DEBUG(1) << "Changing state from " << get_state_name(m_state) << " to " << get_state_name(state);
41 0 : m_state = state;
42 0 : }
43 :
44 : std::map<LivetimeCounter::State, LivetimeCounter::state_time_t>
45 0 : LivetimeCounter::get_time_map()
46 : {
47 0 : std::lock_guard<std::mutex> l(m_mutex);
48 0 : update_map();
49 0 : return m_state_times;
50 0 : }
51 :
52 : LivetimeCounter::state_time_t
53 0 : LivetimeCounter::get_time(LivetimeCounter::State state)
54 : {
55 0 : std::lock_guard<std::mutex> l(m_mutex);
56 0 : update_map();
57 0 : return m_state_times[state];
58 0 : }
59 :
60 : LivetimeCounter::state_time_t
61 0 : LivetimeCounter::now() const
62 : {
63 0 : using namespace std::chrono;
64 0 : return duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
65 : }
66 :
67 : std::string
68 0 : LivetimeCounter::get_report_string()
69 : {
70 0 : std::lock_guard<std::mutex> l(m_mutex);
71 0 : update_map();
72 0 : std::ostringstream oss;
73 0 : for (auto const& [state, t] : m_state_times) {
74 0 : oss << get_state_name(state) << ": " << t << "ms ";
75 : }
76 0 : return oss.str();
77 0 : }
78 :
79 : std::string
80 0 : LivetimeCounter::get_state_name(LivetimeCounter::State state) const
81 : {
82 0 : switch (state) {
83 0 : case State::kLive:
84 0 : return "live";
85 0 : case State::kDead:
86 0 : return "dead";
87 0 : case State::kPaused:
88 0 : return "paused";
89 0 : default:
90 0 : return "UNKNOWN";
91 : }
92 : }
93 :
94 : } // namespace dunedaq::trigger
|