mirror of
https://github.com/mudita/MuditaOS.git
synced 2026-01-24 13:58:00 -05:00
84 lines
2.3 KiB
C++
84 lines
2.3 KiB
C++
// Copyright (c) 2017-2020, Mudita Sp. z.o.o. All rights reserved.
|
|
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
|
|
|
|
#pragma once
|
|
|
|
#include <algorithm>
|
|
#include <cassert>
|
|
|
|
#include "Service/Service.hpp"
|
|
#include "Service/Message.hpp"
|
|
#include "MessageType.hpp"
|
|
|
|
namespace utils
|
|
{
|
|
|
|
namespace state
|
|
{
|
|
template <typename T> class State
|
|
{
|
|
|
|
private:
|
|
T currentState;
|
|
T lastState;
|
|
sys::Service *owner = nullptr;
|
|
|
|
bool timeoutActive = false;
|
|
uint32_t timeoutElapseTime = 0;
|
|
T timeoutState;
|
|
|
|
bool notifyOwner(void)
|
|
{
|
|
auto msg = std::make_shared<sys::DataMessage>(MessageType::StateChange);
|
|
if (owner != nullptr) {
|
|
owner->bus.sendUnicast(msg, owner->GetName());
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public:
|
|
State(sys::Service *service) : owner(service)
|
|
{}
|
|
void set(T state)
|
|
{
|
|
LOG_INFO(
|
|
"%s state change: [ %s ] -> [ %s ]", owner->GetName().c_str(), c_str(currentState), c_str(state));
|
|
lastState = currentState;
|
|
currentState = state;
|
|
notifyOwner();
|
|
}
|
|
T get(void)
|
|
{
|
|
return currentState;
|
|
}
|
|
T getLast(void)
|
|
{
|
|
return lastState;
|
|
}
|
|
T getTimeoutState(void)
|
|
{
|
|
return timeoutState;
|
|
}
|
|
void disableTimeout(void)
|
|
{
|
|
timeoutActive = false;
|
|
}
|
|
void enableStateTimeout(uint32_t currentTime, uint32_t timeout, T timeoutOccuredState)
|
|
{
|
|
timeoutElapseTime = currentTime + timeout;
|
|
timeoutState = timeoutOccuredState;
|
|
timeoutActive = true;
|
|
}
|
|
bool timeoutOccured(uint32_t time)
|
|
{
|
|
if (time >= timeoutElapseTime && timeoutActive) {
|
|
disableTimeout();
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
};
|
|
} // namespace state
|
|
} // namespace utils
|