Skip to content

Commit 8803810

Browse files
committed
Add support for storing config value
1 parent 336d5dd commit 8803810

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

src/ConfigEntry.h

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ class ConfigEntry : public MqttEntry {
99
ConfigEntry(PubSubClient& mqttClient, MqttEntry& parent) : MqttEntry("config", mqttClient, parent) {
1010
SPIFFS.begin();
1111
load();
12+
setPublishFunction([this](MqttEntry* entry, String message){
13+
store();
14+
});
1215
}
1316

1417
String getString(String key, String defaultValue) {
@@ -61,7 +64,6 @@ class ConfigEntry : public MqttEntry {
6164
}
6265

6366
void store() {
64-
Serial.println("store");
6567
File f = SPIFFS.open("/config.cfg", "w");
6668
if (f) {
6769
each([&](MqttEntry* entry) {

src/EasyMqtt.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,11 @@ class EasyMqtt : public MqttEntry {
6363
debug("Connecting to MQTT: " + host + " on port " + String(port));
6464
if (mqttClient.connect(deviceId.c_str(), username.c_str(), password.c_str())) {
6565
debug("Connected to MQTT");
66+
67+
setPublishFunction([&](MqttEntry* entry, String message){
68+
mqttClient.publish(entry->getTopic().c_str(), message.c_str());
69+
});
70+
6671
debug("Topic", getTopic());
6772
each([&](MqttEntry* entry){
6873
if (entry->isOut()) {

src/MqttEntry.h

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,13 @@ class MqttEntry {
2828
MqttEntry::name = (char*)malloc(strlen(name)+1);
2929
strncpy(MqttEntry::name, name, strlen(name)+1);
3030
}
31+
32+
std::function<void(MqttEntry*, String)> getPublishFunction() {
33+
if(publishFunction == NULL && parent) {
34+
return parent->getPublishFunction();
35+
}
36+
return publishFunction;
37+
}
3138

3239
protected:
3340
MqttEntry(const char* name, PubSubClient& mqttClient, MqttEntry& parent) {
@@ -54,6 +61,10 @@ class MqttEntry {
5461
children->next = oldChild;
5562
return child;
5663
}
64+
65+
void setPublishFunction(std::function<void(MqttEntry*, String)> function) {
66+
publishFunction = function;
67+
}
5768

5869
public:
5970
void callback(const char* topic, uint8_t* payload, unsigned int length) {
@@ -159,7 +170,10 @@ class MqttEntry {
159170
* Publish value to mqtt
160171
*/
161172
void publish(String message) {
162-
client->publish(getTopic().c_str(), message.c_str());
173+
auto function = getPublishFunction();
174+
if(function) {
175+
getPublishFunction()(this,message);
176+
}
163177
}
164178

165179
/**

0 commit comments

Comments
 (0)