keep track of enabled sensors using struct

This commit is contained in:
Nicu Hodos 2024-10-09 08:43:45 +02:00
parent 2456ae1dc8
commit 8f534cce94
2 changed files with 14 additions and 9 deletions

View File

@ -1,12 +1,16 @@
#pragma once
#include "TaskScheduler.h"
#include "mqtt.h"
#include "ha.h"
using namespace Ha;
namespace HaESP {
struct {
bool heapStats = false;
bool restartInfo = false;
} activeSensors;
Task tHeap(5 * TASK_MINUTE, TASK_FOREVER, []() {
Sensor::mapSensors["heap_fragmentation"]->updateState(to_string(ESP.getHeapFragmentation()).c_str());
Sensor::mapSensors["heap_free"]->updateState(to_string(ESP.getFreeHeap()).c_str());
@ -35,16 +39,19 @@ namespace HaESP {
.withPrecision(0)
.build()
);
Mqtt::connectedStatus.setWaiting();
tHeap.enable();
activeSensors.heapStats = true;
return builder;
}
template <class T>
Builder<T>& restartInfo(Builder<T>& builder) {
builder.addDiagnostic(Builder<Sensor>::instance((new Sensor{ "Restart reason", "restart_reason" })).build());
Mqtt::connectedStatus.setWaiting();
tRestartInfo.waitFor(&Mqtt::connectedStatus);
activeSensors.restartInfo = true;
return builder;
}
void enableSensors() {
if (activeSensors.heapStats) tHeap.enable();
if (activeSensors.restartInfo) tRestartInfo.enable();
}
}

View File

@ -3,15 +3,13 @@
#include <AsyncMqttClient.h>
#include <ArduinoJson.h>
#include <TaskScheduler.h>
#include "ha.h"
#include "esp.h"
#define MAIN_TOPIC "homeassistant/+/" MAIN_DEVICE_ID "/#"
using namespace Ha;
namespace Mqtt {
StatusRequest connectedStatus;
AsyncMqttClient client;
Task tReConnect(TASK_MINUTE, TASK_FOREVER, []{
@ -33,6 +31,7 @@ namespace Mqtt {
if (firstTime) {
Component::components.forEach([](Component* c) { c->publishConfig(); });
AbstractBuilder::deleteAll();
HaESP::enableSensors();
firstTime = false;
}
}
@ -66,7 +65,6 @@ namespace Mqtt {
client.subscribe(MAIN_TOPIC, 0);
tReConnect.disable();
Serial.println("Connected to MQTT");
connectedStatus.signal();
if (onConnected) onConnected();
});
client.onDisconnect([onDisconnected](AsyncMqttClientDisconnectReason reason) {