Hi everyone,
I’m developing a custom integration for Modbus sensors that postprocess CSV values. The goal is to update sensor state and also store the timestamp of the last update as an attribute. I have an after_update rule that sets an attribute (for example, "A1B2C3D4E5F6_last_hourly": "2025021715"
), and the log confirms that it’s set correctly. However, when a subsequent rule (such as a calculation rule) runs, the attributes from the previous update seem to be lost, leaving only the attributes from the latest update.
Here’s a snippet of my helper function for updating the target sensor state and attributes:
def _set_target_attribute(self, attribute: str, value: Any) -> None:
"""Update the target sensor's state and set an attribute value."""
try:
self._target_sensor = self._hass.states.get(self._target)
# Make a copy of the current attributes
new_attributes = dict(self._target_sensor.attributes)
# Update with the new attribute
new_attributes[attribute] = value
# Set the state with the merged attributes
self._hass.states.set(self._target, self._target_sensor.state, new_attributes)
_LOGGER.debug("AUR: Set attribute '%s' to '%s' on target '%s'.", attribute, value, self._target)
except Exception as exc:
_LOGGER.error("AUR: Error setting attribute '%s' for target '%s': %s", attribute, self._target, exc)
And here’s part of the log output:
2025-02-17 15:20:41.684 DEBUG ... New attributes: {
'icon': 'mdi:calendar-today',
'friendly_name': 'burner_pellets_counter_hour',
'unit_of_measurement': 'rotations/hour',
'precision': 2,
'previous_value': None,
'A1B2C3D4E5F6_last_hourly': '2025021715'
}
2025-02-17 15:20:41.713 DEBUG ... New attributes: {
'icon': 'mdi:calendar-today',
'friendly_name': 'burner_pellets_counter_hour',
'unit_of_measurement': 'rotations/hour',
'precision': 2,
'previous_value': None,
'A1B2C3D4E5F6_last_calculation': '20250217152041696097'
}
As you can see, after the hourly update the attribute "A1B2C3D4E5F6_last_hourly"
is set, but then when the calculation rule runs, only "A1B2C3D4E5F6_last_calculation"
is in the attribute dictionary. It appears that the new update is overwriting the entire attributes dictionary, rather than merging with the previous values.
Question:
Is there a way to update the sensor’s attributes so that subsequent updates merge with (and preserve) existing attributes? I want each after_update rule to add or update its own attribute without losing previously stored attributes.
Any help or suggestions would be greatly appreciated!
Thanks in advance.
Feel free to adjust the wording or include additional context as needed.