Get last state and attributes for Sensor component after restart

I’m writing my first integration for Home Assistant. It’s loading data from a 3rd party API to create a daily metric. The API provides a list of entries, which I filter by todays date, aggregate the values and output to the sensor state (and store some attribute).

The challenge is that the data provided by that the API only returns 10 entries, rather than entire list for a day (or more). So if there are more entries in a day then my aggregate for today will not be correct (because I’ll not receive the entries from beginning of the day).

To work around this limitation I’m using previous state of the sensor (and its attributes) to determine the delta of my metric since last update and update the state with the delta. Here’s an example of the code:

            last_entry_id = self.attrs[ATTR_LAST_ENTRY_ID]
            data = self.api.fetch_entries()
            
            today = datetime.date.today()
            start_of_today = datetime.datetime(today.year, today.month, today.day)

            todays_entries = get_entries_period(data["entries"], start_of_today, start_of_today + datetime.timedelta(days=1))            

            if last_entry_id:
                new_entries = list(filter(lambda x: x["id"] > last_entry_id, todays_entries))
                if new_entries :
                    new_totals = aggregate_entries(new_entries)

                    self.attrs[ATTR_MINUTES] += new_totals["minutes"]
                    self.attrs[ATTR_LAST_ENTRY_ID] = new_totals["last_entry_id"]
                else:
                    if not todays_entries:
                        # No new entries today
                        self.attrs[ATTR_MINUTES] = 0
                        self.attrs[ATTR_LAST_ENTRY_ID] = None
            else:
                today_totals = aggregate_entries(todays_entries)
                self.attrs[ATTR_MINUTES] = today_totals["minutes"]
                self.attrs[ATTR_LAST_ENTRY_ID] = today_totals["last_entry_id"]

            self._state = round(self.attrs[ATTR_MINUTES] / 60.0, 1)

This works well until I restart Home Assistant. Then I no longer get anything from self.attrs[ATTR_LAST_ENTRY_ID] on first update and my stats become incorrect (for days when there are more than 10 entries).

Can this be solved with standard Home Assistant APIs?

1 Like

I have found an article that helped me solve the problem: https://aarongodfrey.dev/programming/restoring-an-entity-in-home-assistant/

The key was to use RestoreEntity instead of Entity as a base for my sensor.

1 Like