From 3df8f48538147cfb84ceb15e862fe57edc7e2676 Mon Sep 17 00:00:00 2001 From: Nicu Hodos Date: Mon, 10 Feb 2025 12:50:44 +0100 Subject: [PATCH] add generic callback struct and use it for brightness and hourFormat24 --- include/devices.h | 8 ++++---- include/display.h | 21 +++++++++++++++------ 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/include/devices.h b/include/devices.h index 10bdf83..267b0db 100644 --- a/include/devices.h +++ b/include/devices.h @@ -131,12 +131,12 @@ namespace Devices { } void setup() { - Display::hourFormat24.changedCallback = []{ + Display::hourFormat24.registerCallback([]{ hourFormatMqtt->updateState(Display::hourFormat24); - }; - Display::brightness.changedCallback = []{ + }); + Display::brightness.registerCallback([]{ brightnessMqtt->updateState(Display::brightness); - }; + }); Display::Timer::remainingCallback = [](int8 current){ timerRemainingMqtt->updateState(to_string(current).c_str()); }; diff --git a/include/display.h b/include/display.h index 5cdf099..c08791e 100644 --- a/include/display.h +++ b/include/display.h @@ -14,6 +14,17 @@ #define DISPLAY_SENSOR_ITERATIONS 2+1 #define DISPLAY_DELAY (SECONDS(2)) +typedef void (*callback_t)(); + +template +struct CallbackAware { + void registerCallback(T f) { + callback = f; + } +protected: + T callback; +}; + namespace Display { void displayTime(); @@ -51,8 +62,7 @@ namespace Display { tDisplayTime.enable(); }); - struct HourFormat { - void (*changedCallback)(); + struct HourFormat : public CallbackAware { operator bool() { return format24; @@ -61,7 +71,7 @@ namespace Display { void operator=(bool value) { format24 = value; tDisplayTime.restart(); - if (changedCallback) changedCallback(); + if (callback) callback(); } private: bool format24 = false; @@ -70,17 +80,16 @@ namespace Display { // Create display object Adafruit_7segment clockDisplay = Adafruit_7segment(); - struct Brightness { + struct Brightness : public CallbackAware { static constexpr uint8 MIN = 0; static constexpr uint8 MAX = 15; static constexpr uint8 DAY = 11; static constexpr uint8 NIGHT = MIN; - void (*changedCallback)(); void operator=(uint8 value) { current = value % (MAX + 1); clockDisplay.setBrightness(current); - if (changedCallback) changedCallback(); + if (callback) callback(); } operator uint8() {