2023-10-18 17:18:42 -07:00
|
|
|
#pragma once
|
|
|
|
#include <functional>
|
|
|
|
#include <utility>
|
|
|
|
#include <vector>
|
|
|
|
|
|
|
|
namespace esphome {
|
|
|
|
namespace ratgdo {
|
|
|
|
|
|
|
|
template <typename... X>
|
|
|
|
class OnceCallbacks;
|
|
|
|
|
|
|
|
template <typename... Ts>
|
|
|
|
class OnceCallbacks<void(Ts...)> {
|
|
|
|
public:
|
|
|
|
template <typename Callback>
|
2024-01-19 13:24:16 -10:00
|
|
|
void operator()(Callback&& callback) { this->callbacks_.push_back(std::forward<Callback>(callback)); }
|
2023-10-18 17:18:42 -07:00
|
|
|
|
2024-01-19 13:24:16 -10:00
|
|
|
void trigger(Ts... args)
|
2023-10-18 17:18:42 -07:00
|
|
|
{
|
2024-01-20 15:51:02 -08:00
|
|
|
for (auto& cb : this->callbacks_) {
|
2023-10-18 17:18:42 -07:00
|
|
|
cb(args...);
|
2024-01-20 15:51:02 -08:00
|
|
|
}
|
2023-10-18 17:18:42 -07:00
|
|
|
this->callbacks_.clear();
|
|
|
|
}
|
|
|
|
|
|
|
|
protected:
|
|
|
|
std::vector<std::function<void(Ts...)>> callbacks_;
|
|
|
|
};
|
|
|
|
|
2024-01-20 15:51:02 -08:00
|
|
|
template <typename... X>
|
|
|
|
class ExpiringCallbacks;
|
|
|
|
|
|
|
|
template <typename... Ts>
|
|
|
|
class ExpiringCallbacks<void(Ts...)> {
|
|
|
|
public:
|
|
|
|
template <typename Callback>
|
2024-01-20 14:43:24 -10:00
|
|
|
void operator()(uint32_t expiration, Callback&& callback)
|
|
|
|
{
|
|
|
|
this->callbacks_.push_back(std::make_pair(expiration, std::forward<Callback>(callback)));
|
2024-01-20 15:51:02 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
void trigger(uint32_t now, Ts... args)
|
|
|
|
{
|
|
|
|
for (auto& cb : this->callbacks_) {
|
|
|
|
if (cb.first >= now) {
|
|
|
|
cb.second(args...);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
this->callbacks_.clear();
|
|
|
|
}
|
|
|
|
|
2024-01-20 14:43:24 -10:00
|
|
|
bool is_expired(uint32_t now) const
|
2024-01-20 15:51:02 -08:00
|
|
|
{
|
|
|
|
bool expired = true;
|
2024-01-20 17:31:31 -08:00
|
|
|
for (const auto& cb : this->callbacks_) {
|
2024-01-20 15:51:02 -08:00
|
|
|
if (cb.first >= now) {
|
|
|
|
expired = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return expired;
|
|
|
|
}
|
|
|
|
|
2024-01-20 14:43:24 -10:00
|
|
|
void clear()
|
2024-01-20 15:51:02 -08:00
|
|
|
{
|
|
|
|
this->callbacks_.clear();
|
|
|
|
}
|
|
|
|
|
|
|
|
protected:
|
|
|
|
std::vector<std::pair<uint32_t, std::function<void(Ts...)>>> callbacks_;
|
|
|
|
};
|
|
|
|
|
2023-10-18 17:18:42 -07:00
|
|
|
} // namespace ratgdo
|
|
|
|
} // namespace esphome
|