MQTT Sensor adding a calculated value or attribute

Hello everyone.
I’v been using HA for 2-3 years but I still have a lot of problem in understanding the logic under the hood of a lot of things.
A little background before my question:
I’ve created few sensors (with ESP8266 and DHT22) and have them send to HA via MQTT readings (temp, hum and battery voltage) every 5 minutes.
Sensor are automatically discovered by HA because every sensor publish a set of configuration JASON values under homeassistant/sensor

  "device_class": "voltage",
  "name": "Voltaggio Batteria Studio",
  "state_topic": "sensor/Studio/state",
  "unit_of_measurement": "V",
  "value_template": "{{ value_json.voltage }}"

and in sensor/Studio/state I’ve got the following reading:

  "temperature": "21.80",
  "humidity": "50.40",
  "humidity": "50.30",
  "voltage": "3.31"

It’s all working smootly so far.

My Problem:
I want to add somewhere a state/entity/something for each sensor in which I store the timestamp every time I change the battery of a sensor (each battery last more or less 30-40 days)
I’ve already created an automation that is triggered when battery voltage of a sensor change from a low to a high value.
Where can I store such information and how ?
Is it better to create an helper or a sensor template ? or should modify the actual sensor to add an attribute to the existing entity ?


You cannot add random attributes to an entity - well you can, but the next time the state is updated, your attribute will be lost. Given you’ve created your own device, you could tell it the replacement date and have it stored locally and included in the MQTT messages each time.

Another way to do it is to use a helper, but this does not scale very well once you want to track 50 batteries. I use “customize.yaml” to store replacement dates “indirectly” on the battery entity, and then update it via a tap_action in the UI. This update then calls homeassistant.reload_core_config to reload customizations, and then homeassistant.update_entity to reload the entity.