Tomáš Pecka | 74b885f | 2020-06-06 20:02:41 +0200 | [diff] [blame] | 1 | #include <algorithm> |
| 2 | #include <utility> |
| 3 | #include "StateManager.h" |
| 4 | #include "utils/log.h" |
| 5 | |
| 6 | namespace velia { |
| 7 | |
| 8 | StateManager::StateManager() |
Tomáš Pecka | 31caebd | 2020-08-21 11:14:10 +0200 | [diff] [blame] | 9 | : m_log(spdlog::get("main")) |
Tomáš Pecka | 74b885f | 2020-06-06 20:02:41 +0200 | [diff] [blame] | 10 | { |
| 11 | } |
| 12 | |
| 13 | StateManager::~StateManager() = default; |
| 14 | |
| 15 | /** @brief Registers an input source */ |
| 16 | void StateManager::registerInput(void* input, State value) |
| 17 | { |
Jan Kundrát | 1a40d21 | 2020-11-02 14:02:56 +0100 | [diff] [blame] | 18 | m_log->trace("Registering input {}", input); |
Tomáš Pecka | 74b885f | 2020-06-06 20:02:41 +0200 | [diff] [blame] | 19 | |
| 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 */ |
| 28 | void StateManager::unregisterInput(void* input) |
| 29 | { |
Jan Kundrát | 1a40d21 | 2020-11-02 14:02:56 +0100 | [diff] [blame] | 30 | m_log->trace("Unregistering input {}", input); |
Tomáš Pecka | 74b885f | 2020-06-06 20:02:41 +0200 | [diff] [blame] | 31 | |
| 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 | |
| 41 | void StateManager::updateState(void* input, State value) |
| 42 | { |
| 43 | m_inputs[input] = value; |
Jan Kundrát | 1a40d21 | 2020-11-02 14:02:56 +0100 | [diff] [blame] | 44 | m_log->trace("Input {} changed state to {}", input, value); |
Tomáš Pecka | 74b885f | 2020-06-06 20:02:41 +0200 | [diff] [blame] | 45 | computeOutput(); |
| 46 | } |
| 47 | |
| 48 | void 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át | d208f3b | 2020-11-02 15:16:52 +0100 | [diff] [blame^] | 51 | |
| 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át | 1a40d21 | 2020-11-02 14:02:56 +0100 | [diff] [blame] | 57 | m_log->info("Status: {}", itMax->second); |
Tomáš Pecka | 74b885f | 2020-06-06 20:02:41 +0200 | [diff] [blame] | 58 | m_outputSignal(itMax->second); |
| 59 | } |
| 60 | } |
| 61 | } |