yourjelly / home-assistant_owie

MIT License
1 stars 1 forks source link

Reloading Home Assistant loses battery status #1

Open yourjelly opened 1 year ago

yourjelly commented 1 year ago

Reloading the integration resets battery level to 0% until the next update.

Desired condition is that the last known battery state is restored.

Mr-HaleYa commented 1 year ago

Unfortunately, the location you pointed out where you want to load the old data is impossible since the entities are not initialized yet. They will appear as if they don't exist. You can test it with this code. I've got code that does what you want on my fork, I'll do a PR soon. Bit of a hack but it works


def slugify(input_string):
    # Remove special characters and replace spaces with underscores
    slug = re.sub(r'[^a-zA-Z0-9]+', '_', input_string).lower()
    return slug

...

class OwieData(object):
...
    def __init__(self, owie_ip, owie_name, hass):
        _LOGGER.debug("Initial OwieData")
        """Initialize the info object."""
        self._owie_address = f"http://{owie_ip}/autoupdate"
        self._owie_entity = f"sensor.{slugify(owie_name)}"
        self.hass = hass
        self.info = {}

        # Fetch the last state of OwieBatterySensor
        _LOGGER.debug("_owie_entity: {}".format(self._owie_entity))
        last_state = self.hass.states.get(self._owie_entity)
        _LOGGER.debug("last_state: {}".format(last_state))

        if last_state:
            # Use the last state's value for 'OVERRIDDEN_SOC' if available
            self.info.setdefault('OVERRIDDEN_SOC', last_state.state)
        else:
            # Set a default value if no last state is available
            self.info.setdefault('OVERRIDDEN_SOC', '0')

        self.info.setdefault('TOTAL_VOLTAGE', '0')
        self.info.setdefault('CURRENT_AMPS', '0')
        self.info.setdefault('UPTIME', 'Offline')
...