blob: 22b52b9ef5ecf72bacc5c14d8926f6b0ce4a8108 [file] [log] [blame]
Tomáš Pecka74b885f2020-06-06 20:02:41 +02001#include <algorithm>
2#include <utility>
3#include "StateManager.h"
4#include "utils/log.h"
5
Tomáš Pecka261c8862020-11-05 11:23:08 +01006namespace velia::health {
Tomáš Pecka74b885f2020-06-06 20:02:41 +02007
8StateManager::StateManager()
Tomáš Pecka7c6b1d32020-11-25 14:17:21 +01009 : m_log(spdlog::get("health"))
Tomáš Pecka74b885f2020-06-06 20:02:41 +020010{
11}
12
13StateManager::~StateManager() = default;
14
15/** @brief Registers an input source */
16void StateManager::registerInput(void* input, State value)
17{
Jan Kundrát1a40d212020-11-02 14:02:56 +010018 m_log->trace("Registering input {}", input);
Tomáš Pecka74b885f2020-06-06 20:02:41 +020019
20 if (m_inputs.find(input) != m_inputs.end()) {
21 throw std::invalid_argument("Input already registered.");
22 }
23
24 updateState(input, value);
25}
26
27/** @brief Unregisters an input source */
28void StateManager::unregisterInput(void* input)
29{
Jan Kundrát1a40d212020-11-02 14:02:56 +010030 m_log->trace("Unregistering input {}", input);
Tomáš Pecka74b885f2020-06-06 20:02:41 +020031
32 auto it = m_inputs.find(input);
33 if (it == m_inputs.end()) {
34 throw std::invalid_argument("Input not registered.");
35 }
36
37 m_inputs.erase(it);
38 computeOutput();
39}
40
41void StateManager::updateState(void* input, State value)
42{
43 m_inputs[input] = value;
Jan Kundrát1a40d212020-11-02 14:02:56 +010044 m_log->trace("Input {} changed state to {}", input, value);
Tomáš Pecka74b885f2020-06-06 20:02:41 +020045 computeOutput();
46}
47
48void StateManager::computeOutput()
49{
50 auto itMax = std::max_element(m_inputs.begin(), m_inputs.end(), [](const auto& e1, const auto& e2) { return e1.second < e2.second; });
Jan Kundrátd208f3b2020-11-02 15:16:52 +010051
52 if (itMax == m_inputs.end()) {
53 // No inputs -- there's no sane thing to do, so remain silent
54 m_oldState.reset();
55 } else if (!m_oldState || (*m_oldState != itMax->second)) {
56 m_oldState = itMax->second;
Jan Kundrát1a40d212020-11-02 14:02:56 +010057 m_log->info("Status: {}", itMax->second);
Tomáš Pecka74b885f2020-06-06 20:02:41 +020058 m_outputSignal(itMax->second);
59 }
60}
61}