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 :
36 : void
37 0 : LivetimeCounter::set_state(LivetimeCounter::State state)
38 : {
39 0 : std::lock_guard<std::mutex> l(m_mutex);
40 0 : update_map(); // Add the time to the old state
41 0 : TLOG_DEBUG(1) << "Changing state from " << get_state_name(m_state) << " to " << get_state_name(state);
42 0 : m_state=state;
43 0 : }
44 :
45 : std::map<LivetimeCounter::State, LivetimeCounter::state_time_t>
46 0 : LivetimeCounter::get_time_map()
47 : {
48 0 : std::lock_guard<std::mutex> l(m_mutex);
49 0 : update_map();
50 0 : return m_state_times;
51 0 : }
52 :
53 : LivetimeCounter::state_time_t
54 0 : LivetimeCounter::get_time(LivetimeCounter::State state)
55 : {
56 0 : std::lock_guard<std::mutex> l(m_mutex);
57 0 : update_map();
58 0 : return m_state_times[state];
59 0 : }
60 :
61 : LivetimeCounter::state_time_t
62 0 : LivetimeCounter::now() const
63 : {
64 0 : using namespace std::chrono;
65 0 : return duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
66 : }
67 :
68 : std::string
69 0 : LivetimeCounter::get_report_string()
70 : {
71 0 : std::lock_guard<std::mutex> l(m_mutex);
72 0 : update_map();
73 0 : std::ostringstream oss;
74 0 : for(auto const& [state, t]: m_state_times){
75 0 : oss << get_state_name(state) << ": " << t << "ms ";
76 : }
77 0 : return oss.str();
78 0 : }
79 :
80 :
81 : std::string
82 0 : LivetimeCounter::get_state_name(LivetimeCounter::State state) const
83 : {
84 0 : switch(state){
85 0 : case State::kLive: return "live";
86 0 : case State::kDead: return "dead";
87 0 : case State::kPaused: return "paused";
88 0 : default:
89 0 : return "UNKNOWN";
90 : }
91 : }
92 :
93 : } // namespace dunedaq::trigger
|