From 57dfa30cf0dc3980ebae46a7b20beb48edc2fc4e Mon Sep 17 00:00:00 2001 From: Siwat Sirichai Date: Mon, 12 Feb 2024 16:40:46 +0700 Subject: [PATCH] remoteVar Callbacks --- ESPMegaPRO-OS-SDK/lib/ESPMegaPRO/RemoteVariable.cpp | 11 +++++++++++ ESPMegaPRO-OS-SDK/lib/ESPMegaPRO/RemoteVariable.hpp | 6 ++++++ 2 files changed, 17 insertions(+) diff --git a/ESPMegaPRO-OS-SDK/lib/ESPMegaPRO/RemoteVariable.cpp b/ESPMegaPRO-OS-SDK/lib/ESPMegaPRO/RemoteVariable.cpp index cc7f003..e06b622 100644 --- a/ESPMegaPRO-OS-SDK/lib/ESPMegaPRO/RemoteVariable.cpp +++ b/ESPMegaPRO-OS-SDK/lib/ESPMegaPRO/RemoteVariable.cpp @@ -95,6 +95,9 @@ void RemoteVariable::mqtt_callback(char* topic, char* payload) { if (strcmp(topic, this->topic) == 0) { ESP_LOGD("RemoteVariable", "Received MQTT message from %s", topic); strcpy(this->value, payload); + for (auto& callback : this->valueChangeCallback) { + callback.second(this->value); + } } } @@ -130,4 +133,12 @@ void RemoteVariable::setValue(const char* value) { if(!this->useSetValue) return; this->iot->publish(this->setValueTopic, value); +} + +uint8_t RemoteVariable::registerCallback(std::function callback) { + this->valueChangeCallback[this->valueChangeCallbackCount] = callback; + return valueChangeCallbackCount++; +} +void RemoteVariable::unregisterCallback(uint8_t handler) { + this->valueChangeCallback.erase(handler); } \ No newline at end of file diff --git a/ESPMegaPRO-OS-SDK/lib/ESPMegaPRO/RemoteVariable.hpp b/ESPMegaPRO-OS-SDK/lib/ESPMegaPRO/RemoteVariable.hpp index 3292c3f..56e38d1 100644 --- a/ESPMegaPRO-OS-SDK/lib/ESPMegaPRO/RemoteVariable.hpp +++ b/ESPMegaPRO-OS-SDK/lib/ESPMegaPRO/RemoteVariable.hpp @@ -1,5 +1,6 @@ #pragma once #include +#include /** * @brief A class that create a variable that exists on other devices and can be accessed remotely * @@ -19,6 +20,9 @@ class RemoteVariable void subscribe(); void requestValue(); char* getValue(); + uint8_t registerCallback(std::function); + void unregisterCallback(uint8_t handler); + private: void mqtt_callback(char* topic, char* payload); ESPMegaIoT* iot; @@ -29,4 +33,6 @@ class RemoteVariable const char* valueRequestTopic; bool useSetValue; const char* setValueTopic; + uint8_t valueChangeCallbackCount; + std::map> valueChangeCallback; }; \ No newline at end of file