Skip to content

Persist sensor values and device config across restarts - #233

Open
meiser79 wants to merge 5 commits into
robertzaage:mainfrom
meiser79:state_cache
Open

meiser79 wants to merge 5 commits into
robertzaage:mainfrom
meiser79:state_cache

Conversation

@meiser79

@meiser79 meiser79 commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Home Assistant entities backed by GroBro's MQTT state topic dropped to "unknown" whenever HA (or GroBro itself) restarted, most noticeably for battery sensors after the battery storage was disconnected: once the inverter/battery stops reporting bat*-keys, the published payload permanently loses those fields and no retained/future message can recover them.

Changes

Offline value handling (grobro/ha/client.py)

GroBro keeps a per-device value cache and fills in any value missing from a fresh payload (absent or None) before publishing:

Value type Brief gap Missing in 3 consecutive payloads / DEVICE_TIMEOUT After restart
Live readings (power, current, voltage, frequency, load %) last known value 0 0
State-like values (SoC, battery/cell voltages, temperature, status, serials) last known value last known value last known value
Energy counters (total_increasing / total) not cached not cached not cached
  • Live readings are detected via device_class (power/apparent_power/reactive_power/current/voltage/frequency), falling back to the unit (W/kW/VA/var/A/mA/V/Hz). A register can override this with "offline": "zero" or "hold" in its homeassistant block (new optional model field).
  • Overrides in the register files:
    • "hold" for battery and cell voltages (NOAH/NEXA min/max cell voltages, NEO/XH2 Vbat, BMS_BatteryVolt, BMS_ConstantVolt, SPF Battery_Voltage): a battery keeps its voltage just like its SoC when the device stops reporting, e.g. after stopping at the discharge limit, so 0 V would be as wrong as 0 %.
    • "zero" for live percentages (RealOPPercent on MOD/NEO/XH2, Load_Percent on NEO/XH2, SPF Load_Percentage and fan speeds).
  • Energy counters are excluded because HA already handles gaps in those correctly, and a cached value could get reinstated after a legitimate reset (e.g. the daily _today counters at midnight), which combined with FILTER_DATA_GLITCHES could suppress the correct lower value as a false glitch.
  • On DEVICE_TIMEOUT, a payload with zeroed live readings is published before the availability update; the availability behavior itself is unchanged.
  • The cache is persisted to state_cache_<device_id>.json at most every 300 s per device and on shutdown, written atomically via a .tmp file (avoids SD card wear and corrupted files).
  • On MQTT (re)connect, the cached payload is republished (honoring PUBLISH_SENSORS_RETAINED) so entities don't have to wait for the next device poll.

Storage location

  • Device configs (config_<device_id>.json) and the new state cache move from the working directory (/app, wiped on every HA app rebuild) to CONFIG_DIR (default /config), backed by a dedicated addon_config map (read_only: false) in config.yaml instead of the previous share:rw mapping.
  • The directory is created if missing; if that fails (e.g. plain Docker without permissions), GroBro logs a warning and keeps running without persistence instead of crashing.
  • DUMP_MESSAGES output moves from /dump (generic) / /share/GroBro/dump (HA app) to <CONFIG_DIR>/dump. The DUMP_DIR option is removed from config.yaml (options and schema) and as env var.

Configuration

  • PUBLISH_SENSORS_RETAINED is added to config.yaml/translations so it's actually exposed in the HA app UI (it already existed as an env var but Supervisor never passed it through).

Docs and tests

  • CONFIGURATION.md, DEVELOPMENT.md and CHANGELOG.md updated: DUMP_DIR removed, CONFIG_DIR, the offline value handling and the offline register field documented, and a note that plain (non-app) Docker users need to mount a volume at /config for this data to survive a restart.
  • Tests redirect CONFIG_DIR to a per-test tmp dir (tests/conftest.py) and cover backfill, hold/zero behavior and recovery, None handling, energy-counter exclusion, persistence/reload, device timeout, throttled saving, register overrides, retain handling on reconnect and an unusable config dir.

Battery entities: no orphans after restart, disconnected batteries keep their values

After a GroBro restart the battery count was unknown until the first input register payload arrived. A device config message usually comes first, and the discovery published then assumed 4 batteries, so HA created bat2-bat4 entities that the next discovery (with the detected bat_cnt) dropped again. Simply omitting a component from a device discovery payload does not remove it in HA, so they were left as orphans (reported e.g. by Spook).

  • With MAX_BAT: auto, the highest detected battery count is kept per device and persisted as max_bat in state_cache_<device_id>.json (format {"values": ..., "max_bat": ...}). It only ever grows; payloads without battery info (no bat_cnt, no serial parts) leave it unchanged. Setting MAX_BAT to a number is the way to drop a battery for good.
  • Before the count is known, devices whose count can be detected (bat_cnt / bat*_ser_part_1 registers, i.e. NOAH) assume a single battery instead of 4. Entities of further batteries are added once a payload reports them. Devices without detection (e.g. NEXA) keep the default of 4.
  • Once the count is known (detected/persisted or MAX_BAT), entities of batteries above it are sent as {"platform": "sensor"}, the documented way to remove a single component from a device discovery. This also cleans up orphans left by earlier versions. While the count is only a guess, they are left out instead, so existing entities aren't removed and re-added on every restart.
  • A disconnected battery keeps its entities. The NOAH keeps reporting registers of batteries beyond bat_cnt as 0 / empty; these are treated as missing, so SoC, temperature and serial keep their last known value instead of showing 0.

Breaking changes

  • Data now lives under /config (HA app: its own addon_config folder). Existing dumps in /share/GroBro/dump are not moved.
  • DUMP_DIR has been removed.
  • Plain Docker users should add --volume ./grobro-config:/config to keep configs and cached values across restarts.

Note: PUBLISH_SENSORS_RETAINED alone does not fix the battery case, since a retained message is overwritten as soon as an incomplete payload is published; the backfill above is what keeps it complete.

🤖 Generated with Claude Code

@criticallimit

Copy link
Copy Markdown
Collaborator

wouldn´t these changes deliver wrong values for Home assistant (energy) statistics?
As long as the value stays the same till a new value is delivered the statistic will count this over time.

@meiser79

Copy link
Copy Markdown
Contributor Author

@criticallimit Hi, valid point, thanks for highlighting!! I now excluded "total_increasing" and "total" sensors from the caching.

@criticallimit

Copy link
Copy Markdown
Collaborator

If you want you can have a look at my version: https://github.com/criticallimit/GroBro

There a few more changes to Roberts GroBro. But for you maybe most interesting is that sensors are not retained but all settings are.

My version is only based on Grobro but with many other (not obviously visible, but important) changes. You can install it beside the original GroBro and switch between both making only one addon active

@robertzaage

Copy link
Copy Markdown
Owner

If you want you can have a look at my version: https://github.com/criticallimit/GroBro

There a few more changes to Roberts GroBro. But for you maybe most interesting is that sensors are not retained but all settings are.

My version is only based on Grobro but with many other (not obviously visible, but important) changes. You can install it beside the original GroBro and switch between both making only one addon active

@criticallimit I just added you to the inner circle of collaborators who are allowed to work on this project. I really appreciate your ongoing support for GroBro and would like to invite you to implement your ideas and future improvements here directly. Of course breaking changes, which require the user to reconfigure something or would break automations after release, always need a discussion in the issue section first, so that I have the chance to highlight those in our release notes.

@meiser79
meiser79 force-pushed the state_cache branch 2 times, most recently from 97426f0 to d91b860 Compare October 3, 2026 18:28
@meiser79

meiser79 commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor Author

If you want you can have a look at my version: https://github.com/criticallimit/GroBro

There a few more changes to Roberts GroBro. But for you maybe most interesting is that sensors are not retained but all settings are.

My version is only based on Grobro but with many other (not obviously visible, but important) changes. You can install it beside the original GroBro and switch between both making only one addon active

@criticallimit Hi, I tried your version and the sensors are unavailable which I wanted to avoid.

image

What's your way to fix this issue?

@criticallimit

Copy link
Copy Markdown
Collaborator

@meiser79
I´m not shure if I can follow. When a sensor is shown unavailable it is unavailable.
A switched-off Noah is unavailable, a Noah which is sometimes unavailable due to wifi range problems is unavailable too during that time.
So, I don´t understand your problem. If your system is working correctly there are no unavailable sensors as long as everything is ok.
Did I miss something? As long as the Master-Noah is alive and connected Bat sensor should show the Value and not unavailable.
image

@meiser79

Copy link
Copy Markdown
Contributor Author

@criticallimit I'd like to have the same behaviour as in the integration for my micro inverter (EZ-M1). It looks much nicer instead of all these "unavailable" sensors with question marks.

image

@criticallimit

criticallimit commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

@meiser79

setting of "Geräte-Timeout" doesn´t solve the problem?
image

If that doesn´t solve your problem you can create a template sensor which is shown in your dashboard. Based on values or states of the original sensor this template sensor can show your desired state or value.For example:
Bildschirmfoto

@codecov-commenter

codecov-commenter commented Nov 11, 2026 •

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 96.89441% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
grobro/ha/client.py 96.83% 5 Missing ⚠️

📢 Thoughts on this report? Let us know!

Home Assistant entities backed by GroBro's MQTT state topic dropped to
"unknown" whenever HA (or GroBro itself) restarted, most noticeably for
battery sensors after the battery storage was disconnected: once the
inverter/battery stops reporting bat*-keys, the published payload
permanently loses those fields and no retained/future message can
recover them.

- grobro/ha/client.py: keep a per-device value cache and fill in any
  value missing from a fresh payload (absent or None) before
  publishing:
  - brief gaps keep the last known reading;
  - after OFFLINE_MISS_THRESHOLD (3) consecutive payloads without it,
    or when the device hits DEVICE_TIMEOUT, live readings (device_class
    power/apparent_power/reactive_power/current/voltage/frequency, or
    unit W/kW/VA/var/A/mA/V/Hz) drop to 0, while state-like values
    (SoC, temperature, status, serials) keep their last known value;
  - a register can override this with "offline": "zero" | "hold" in
    its homeassistant block (new optional model field);
  - total_increasing/total registers (the kWh energy counters feeding
    the HA Energy dashboard) are not cached: HA already handles gaps in
    those correctly on its own, and caching them risked reinstating a
    stale (too high) value after a legitimate reset (e.g. the daily
    "_today" counters at midnight), which combined with
    FILTER_DATA_GLITCHES could then suppress the correct lower value as
    a false glitch.
  The cache is persisted to state_cache_<device_id>.json at most every
  VALUE_CACHE_SAVE_INTERVAL (300 s) per device and on shutdown, written
  atomically via a .tmp file to avoid SD card wear and corruption. On
  startup it is reloaded with live readings set to 0. On MQTT
  (re)connect, the cached payload is republished (honoring
  PUBLISH_SENSORS_RETAINED) so entities don't have to wait for the
  next device poll either.
- Move the device config cache (config_<device_id>.json) and the new
  state cache from the working directory (/app, wiped on every addon
  rebuild) to CONFIG_DIR (default /config), backed by a dedicated
  addon_config map (read_only: false) in config.yaml instead of the
  previous share:rw mapping. The directory is created if missing; if
  that fails (e.g. plain Docker without permissions), GroBro logs a
  warning and keeps running without persistence instead of crashing.
- Move DUMP_MESSAGES output from /dump (generic) / /share/GroBro/dump
  (addon) to <CONFIG_DIR>/dump for the same reason, and drop the
  DUMP_DIR option from config.yaml (options and schema) and its env var.
- Add PUBLISH_SENSORS_RETAINED to config.yaml/translations so it's
  actually exposed in the addon UI (it already existed as an env var
  but Supervisor never passed it through).
- Update CONFIGURATION.md, DEVELOPMENT.md and CHANGELOG.md: drop
  DUMP_DIR from the env var reference, document CONFIG_DIR, the offline
  value handling and the "offline" register field, point DUMP_MESSAGES/
  config-cache docs at /config, and note that plain (non-addon) Docker
  users need to mount a volume at /config themselves for this data to
  survive a restart.
- Tests: redirect CONFIG_DIR to a per-test tmp dir via conftest.py and
  cover backfill, hold/zero behavior and recovery, None handling,
  energy-counter exclusion, persistence/reload, device timeout,
  throttled saving, register overrides, retain handling on reconnect
  and an unusable config dir.

Note: PUBLISH_SENSORS_RETAINED alone does not fix the battery case,
since a retained message is overwritten as soon as an incomplete
payload is published; the backfill above is what keeps it complete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
meiser79 and others added 4 commits November 11, 2026 20:25
After a GroBro restart the battery count is unknown until the first
input register payload arrives. A device config message usually comes
first, and set_config() published the discovery with the default of 4
batteries, so HA created bat2-bat4 entities that the next discovery
(with the detected bat_cnt) dropped again. Simply omitting a component
from a device discovery payload does not remove it in HA, leaving them
as orphans (reported e.g. by Spook).

- _resolve_max_bat(): for devices whose battery count can be detected
  (bat_cnt or bat*_ser_part_1 registers, i.e. NOAH), fall back to the
  bat_cnt persisted in the value cache, then to 1 instead of 4. Entities
  of further batteries are added once a payload reports them, which
  leaves no orphans. Devices without detection (e.g. NEXA) keep the
  default of 4.
- Discovery: once the battery count is known (detected or MAX_BAT),
  entities of batteries above it are sent as {"platform": "sensor"},
  the documented way to remove a single component from a device
  discovery. This also cleans up orphans left by earlier versions.
  While the count is only a guess, they are left out instead, so
  existing entities aren't removed and re-added on every restart.
- Tests: reset _MAX_BAT_CACHE between tests, cover the new default,
  cached bat_cnt, removal entries and the NEXA default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With MAX_BAT=auto the battery count followed the latest bat_cnt. When a
battery was disconnected, bat_cnt dropped, so discovery removed its
entities (via the {"platform": "sensor"} removal entries) and the value
cache stopped holding its values; reconnecting it recreated them and
lost any user customizations. The NOAH also keeps reporting registers of
batteries beyond bat_cnt as 0 / empty, which would have shown a SoC of 0
instead of the last known value.

- _resolve_max_bat(): in auto mode the detected count only ever grows.
  Payloads without battery info (no bat_cnt, no serial parts) leave it
  unchanged instead of falling back to 4. Setting MAX_BAT to a number is
  the way to drop a battery for good.
- Persist the count as max_bat in state_cache_<device_id>.json (now
  {"values": ..., "max_bat": ...}) and restore it on startup, so it is
  known right away and removal entries apply from the first discovery.
  This replaces the fallback to the cached bat_cnt.
- Values of batteries beyond the currently reported count are treated as
  missing, so they keep their last known value (SoC, temperature and
  serial are all "hold" values).
- Docs/translations: describe the new MAX_BAT auto behavior.
- Tests: persisted count after restart, disconnected battery keeps
  entities and values, payload without battery info keeps the count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The offline behavior derived from device_class/unit put every voltage
into the "zero" group and every percentage into "hold". That's wrong for
two kinds of registers:

- Battery and cell voltages: a battery keeps its voltage just like its
  SoC when the device stops reporting (e.g. after stopping at the
  discharge limit), so showing 0 V is as wrong as 0 %. Set
  "offline": "hold" for NOAH/NEXA min/max cell voltages, NEO/XH2 Vbat
  and BMS_BatteryVolt, SPF Battery_Voltage and the BMS CV setpoint
  (BMS_ConstantVolt).
- Load/output percentages and fan speeds are live readings: set
  "offline": "zero" for RealOPPercent (MOD/NEO/XH2), Load_Percent
  (NEO/XH2), SPF Load_Percentage and both SPF fan speeds.

SoC registers already kept their last value (device_class battery).
Battery currents and powers keep dropping to 0.

- Tests: check across all device types that SoC and battery/cell
  voltages are held and load/output percentages and fan speeds zeroed.
- Docs/changelog: mention the overrides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Config register 4 (data_interval) is in seconds on the NOAH: it reads 5
and the device publishes its state every 5 seconds. The NEXA uses the
same datalogger firmware, and its protocol description also gives
seconds. GroBro writes the value unchanged, so "1 min" set in Home
Assistant would have become 1 second.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants