use struct for timer and use generic callback

This commit is contained in:
Nicu Hodos 2025-02-10 13:09:23 +01:00
parent 3df8f48538
commit daf6c876a8
2 changed files with 35 additions and 11 deletions

View File

@ -137,8 +137,8 @@ namespace Devices {
Display::brightness.registerCallback([]{ Display::brightness.registerCallback([]{
brightnessMqtt->updateState(Display::brightness); brightnessMqtt->updateState(Display::brightness);
}); });
Display::Timer::remainingCallback = [](int8 current){ Display::Timer::timer.registerCallback([](int8 current){
timerRemainingMqtt->updateState(to_string(current).c_str()); timerRemainingMqtt->updateState(to_string(current).c_str());
}; });
} }
} }

View File

@ -101,13 +101,38 @@ namespace Display {
} brightness; } brightness;
namespace Timer { namespace Timer {
int8 timer = 0, current = 0; typedef void (*remaining_callback_t)(int8);
void (*remainingCallback)(int8); struct : public CallbackAware<remaining_callback_t> {
void operator=(int8 value) {
initial = remaining = value;
}
operator int8() {
return remaining;
}
void start() {
remaining = initial + 1;
}
void decrease() {
remaining--;
if (callback) callback(remaining);
}
bool atBeginning() {
return initial == remaining;
}
private:
int8 initial = 0, remaining = 0;
} timer;
Task tDisplayTimer(SECONDS(10), TASK_ONCE + 1, Task tDisplayTimer(SECONDS(10), TASK_ONCE + 1,
[]{ []{
if (current >= 0) { if (timer >= 0) {
clockDisplay.print(current, DEC); clockDisplay.print(timer, DEC);
clockDisplay.writeDisplay(); clockDisplay.writeDisplay();
} }
}, &ts, false, }, &ts, false,
@ -123,18 +148,17 @@ namespace Display {
Task tTimer(MINUTES(1), TASK_FOREVER, Task tTimer(MINUTES(1), TASK_FOREVER,
[]{ []{
static constexpr uint8 threshold = 16; static constexpr uint8 threshold = 16;
current--; timer.decrease();
if (current == timer) { if (timer.atBeginning()) {
if (timer <= threshold) tDisplayTimer.setIterations(TASK_FOREVER); if (timer <= threshold) tDisplayTimer.setIterations(TASK_FOREVER);
tDisplayTimer.restart(); tDisplayTimer.restart();
} else if (current == threshold) { } else if (timer == threshold) {
tDisplayTimer.setIterations(TASK_FOREVER); tDisplayTimer.setIterations(TASK_FOREVER);
tDisplayTimer.restart(); tDisplayTimer.restart();
} }
if (remainingCallback) remainingCallback(current);
}, &ts, false, }, &ts, false,
[]{ []{
current = timer+1; timer.start();
return true; return true;
}, },
[]{ []{