add helper methods for creating typical battery sensors for rc devices

This commit is contained in:
Nicu Hodos 2025-10-05 11:50:20 +02:00
parent 0a228df07d
commit 57b9494c98
3 changed files with 14 additions and 9 deletions

View File

@ -12,8 +12,7 @@ auto roomSensor = Builder<TemperatureSensor>::instance(TEMP_SENSOR)
.withArea("Basement")
.withParent(gatewayDevice))
.withValueTemplate("{{ value_json.sensor.temperature }}")
.addDiagnostic(createVoltageSensor(TEMP_SENSOR))
.addDiagnostic(createBatterySensor(TEMP_SENSOR, 2.5, 4.5))
.addPreconfigured(batterySensors<TemperatureSensor>(TEMP_SENSOR, 2.5, 4.5))
.build();
auto tankSensor = Builder<Sensor>::instance(new Sensor{ "Level", OIL_SENSOR })
@ -35,8 +34,7 @@ auto tankSensor = Builder<Sensor>::instance(new Sensor{ "Level", OIL_SENSOR })
.withValueTemplate("{{ value_json.sensor.value }}")
.build()
)
.addDiagnostic(createVoltageSensor(OIL_SENSOR))
.addDiagnostic(createBatterySensor(OIL_SENSOR, 4.0, 6.4))
.addPreconfigured(batterySensors<Sensor>(OIL_SENSOR, 4.0, 6.4))
.build();
auto presenceTracker = Builder<BinarySensor>::instance(PRESENCE_SENSOR)
@ -46,8 +44,7 @@ auto presenceTracker = Builder<BinarySensor>::instance(PRESENCE_SENSOR)
.withModel("AtTiny85")
.withParent(gatewayDevice))
.withValueTemplate("{{ value_json.sensor.state }}")
.addDiagnostic(createVoltageSensor(PRESENCE_SENSOR))
.addDiagnostic(createBatterySensor(PRESENCE_SENSOR, 2.7, 3.3))
.addPreconfigured(batterySensors<BinarySensor>(PRESENCE_SENSOR, 2.7, 3.3))
.withOffDelaySeconds(5*60)
.withDeviceClass("presence")
.build();

View File

@ -77,7 +77,15 @@ VoltageSensor* createVoltageSensor(const char* id) {
}
BatterySensor* createBatterySensor(const char* id, float min, float max) {
char value_json[128];
snprintf(value_json, 128, "{{ ((value_json.sensor.diagnostic.voltage|float-%f)|round(2)*100/%f)|int }}", min, max - min);
char* value_json = new char[128];
snprintf(value_json, 128, "{{ ((value_json.sensor.diagnostic.voltage|float-%.2f)|round(2)*100/%.2f)|int }}", min, max - min);
return new BatterySensor{id, "Battery level", value_json};
}
template <class T>
auto batterySensors(const char* id, float min, float max) {
return [id, min, max](Builder<T>& builder) -> Builder<T>& {
builder.addDiagnostic(createVoltageSensor(id)).addDiagnostic(createBatterySensor(id, min, max)).build();
return builder;
};
}

View File

@ -33,7 +33,7 @@ framework = arduino
lib_deps =
${env.lib_deps}
arkhipenko/TaskScheduler@^3.8.5
https://git.hodos.ro/libraries/ha-mqtt.git@^1.12.0
https://git.hodos.ro/libraries/ha-mqtt.git@^1.13.0
https://git.hodos.ro/libraries/wifi.git@^2.0.0
esphome/ESPAsyncWebServer-esphome@^3.4.0
upload_port = 192.168.6.161