mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-12-02 18:36:28 +01:00
fix(config): migrate Home Assistant config paths with device list positions
Device collections were lists before they became maps keyed by device id, so a Home Assistant config path such as devices/batteries/0/min_soc_percentage addressed the first battery. The migration moved the battery to its device id but kept the list position in the path. The adapter then reported the path as no existing setting on every run and no longer applied the Home Assistant value. Paths with a list position now get the key the device migrates to, for batteries, electric vehicles, inverters and home appliances. Paths of collections that are maps already are kept. A list position without a device is kept and logged as warning. If the same setting is also mapped by device id, the list position wins, as only it addressed a device in a list. Additional changes The device key prefixes and the key rule are shared with the device list migration The upgrade guide says that the Home Assistant config paths follow the device ids Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
committed by
Bobby Noelte
co-authored by
Claude Opus 5.5
parent
aad5db46e9
commit
12527597b1
@@ -30,9 +30,10 @@ Device collections now use stable names. For example, `devices.batteries.0` beco
|
|||||||
your migrated configuration; do not assume the example name. An explicit `device_id`
|
your migrated configuration; do not assume the example name. An explicit `device_id`
|
||||||
must match its map key, and the inverter must refer to the correct battery ID.
|
must match its map key, and the inverter must refer to the correct battery ID.
|
||||||
|
|
||||||
Supported old device lists migrate automatically. External configuration paths in
|
Supported old device lists migrate automatically. The configuration paths of the Home
|
||||||
automations and scripts do not. Check those paths and the saved configuration after
|
Assistant adapter (`adapter.homeassistant.config_entity_ids`) follow the device IDs.
|
||||||
migration. Battery wear cost is named `levelized_cost_of_storage_amt_kwh`.
|
External configuration paths in automations and scripts do not. Check those paths and the
|
||||||
|
saved configuration after migration. Battery wear cost is named `levelized_cost_of_storage_amt_kwh`.
|
||||||
|
|
||||||
The new GENETIC currently supports one inverter, one stationary battery, one EV and
|
The new GENETIC currently supports one inverter, one stationary battery, one EV and
|
||||||
multiple household appliances. Surplus devices and a battery not linked to the inverter are
|
multiple household appliances. Surplus devices and a battery not linked to the inverter are
|
||||||
|
|||||||
@@ -34,12 +34,29 @@ if TYPE_CHECKING:
|
|||||||
|
|
||||||
_KEEP_DEFAULT = object()
|
_KEEP_DEFAULT = object()
|
||||||
|
|
||||||
|
# Device collections that were lists and are maps keyed by device id now, with the
|
||||||
|
# prefix of the key a device without device_id gets: "bat" + list position -> "bat0".
|
||||||
|
_DEVICE_KEY_PREFIXES = {
|
||||||
|
"batteries": "bat",
|
||||||
|
"electric_vehicles": "ev",
|
||||||
|
"inverters": "inv",
|
||||||
|
"home_appliances": "appliance",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
# -----------------------------
|
# -----------------------------
|
||||||
# Migration helpers
|
# Migration helpers
|
||||||
# -----------------------------
|
# -----------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _device_key(item: Dict[str, Any], prefix: str, index: int) -> Any:
|
||||||
|
"""Return the map key of the device at list position *index* of an old device list.
|
||||||
|
|
||||||
|
The key is the device's own ``device_id``, otherwise *prefix* + *index*.
|
||||||
|
"""
|
||||||
|
return item.get("device_id") or f"{prefix}{index}"
|
||||||
|
|
||||||
|
|
||||||
def _list_to_device_dict(
|
def _list_to_device_dict(
|
||||||
prefix: str,
|
prefix: str,
|
||||||
migrate_item: Callable[[Dict[str, Any]], None] | None = None,
|
migrate_item: Callable[[Dict[str, Any]], None] | None = None,
|
||||||
@@ -64,9 +81,7 @@ def _list_to_device_dict(
|
|||||||
if not isinstance(original, dict):
|
if not isinstance(original, dict):
|
||||||
raise ValueError("Device settings must be an object")
|
raise ValueError("Device settings must be an object")
|
||||||
item = dict(original)
|
item = dict(original)
|
||||||
key = (
|
key = _device_key(item, prefix, index) if isinstance(value, list) else index
|
||||||
(item.get("device_id") or f"{prefix}{index}") if isinstance(value, list) else index
|
|
||||||
)
|
|
||||||
if not isinstance(key, str):
|
if not isinstance(key, str):
|
||||||
raise ValueError("Device identifiers must be strings")
|
raise ValueError("Device identifiers must be strings")
|
||||||
if key in result:
|
if key in result:
|
||||||
@@ -299,6 +314,76 @@ def _migrate_config_entity_ids(value: Any) -> Any:
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _migrate_config_entity_device_positions(config_data: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
|
"""Rewrite Home Assistant config paths that address a device by its list position.
|
||||||
|
|
||||||
|
Device collections were lists, so ``devices/batteries/0/min_soc_percentage`` addressed the
|
||||||
|
first battery. The path gets the key the device migrates to (see `_list_to_device_dict`),
|
||||||
|
e.g. ``devices/batteries/battery1/min_soc_percentage``. Paths of collections that are maps
|
||||||
|
already are kept. A list position without a device is kept and logged as warning. If a
|
||||||
|
rewritten path is configured by device id as well, the rewritten one wins, as only the
|
||||||
|
list position addressed a device in a list.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
config_data (Dict[str, Any]): The configuration data to migrate.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dict[str, Any]: The configuration data, with the rewritten paths in a copy.
|
||||||
|
"""
|
||||||
|
adapter = config_data.get("adapter")
|
||||||
|
if not isinstance(adapter, dict):
|
||||||
|
return config_data
|
||||||
|
homeassistant = adapter.get("homeassistant")
|
||||||
|
if not isinstance(homeassistant, dict):
|
||||||
|
return config_data
|
||||||
|
entity_ids = homeassistant.get("config_entity_ids")
|
||||||
|
if not isinstance(entity_ids, dict):
|
||||||
|
return config_data
|
||||||
|
devices = config_data.get("devices")
|
||||||
|
if not isinstance(devices, dict):
|
||||||
|
devices = {}
|
||||||
|
|
||||||
|
result: Dict[str, Any] = {}
|
||||||
|
by_position: Dict[str, Any] = {}
|
||||||
|
for path, entity_id in entity_ids.items():
|
||||||
|
parts = path.strip("/").split("/") if isinstance(path, str) else []
|
||||||
|
if not (
|
||||||
|
len(parts) >= 3
|
||||||
|
and parts[0] == "devices"
|
||||||
|
and parts[1] in _DEVICE_KEY_PREFIXES
|
||||||
|
and parts[2].isdecimal()
|
||||||
|
and not isinstance(devices.get(parts[1]), dict)
|
||||||
|
):
|
||||||
|
result[path] = entity_id
|
||||||
|
continue
|
||||||
|
index = int(parts[2])
|
||||||
|
items = devices.get(parts[1])
|
||||||
|
item = items[index] if isinstance(items, list) and index < len(items) else None
|
||||||
|
key = (
|
||||||
|
_device_key(item, _DEVICE_KEY_PREFIXES[parts[1]], index)
|
||||||
|
if isinstance(item, dict)
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
if not isinstance(key, str):
|
||||||
|
logger.warning(
|
||||||
|
f"Home Assistant config entity '{entity_id}' for '{path}': there is no device "
|
||||||
|
f"at list position {index}. Address the device by its device_id."
|
||||||
|
)
|
||||||
|
result[path] = entity_id
|
||||||
|
continue
|
||||||
|
by_position["/".join(["devices", parts[1], key, *parts[3:]])] = entity_id
|
||||||
|
for path, entity_id in by_position.items():
|
||||||
|
if result.get(path, entity_id) != entity_id:
|
||||||
|
logger.warning(
|
||||||
|
f"Home Assistant config entity '{result[path]}' for '{path}' is replaced by "
|
||||||
|
f"'{entity_id}', which addressed the device by its list position."
|
||||||
|
)
|
||||||
|
result[path] = entity_id
|
||||||
|
|
||||||
|
homeassistant = {**homeassistant, "config_entity_ids": result}
|
||||||
|
return {**config_data, "adapter": {**adapter, "homeassistant": homeassistant}}
|
||||||
|
|
||||||
|
|
||||||
# -----------------------------
|
# -----------------------------
|
||||||
# Global migration map constant
|
# Global migration map constant
|
||||||
# -----------------------------
|
# -----------------------------
|
||||||
@@ -339,14 +424,14 @@ MIGRATION_MAP: Dict[
|
|||||||
# fields that are computed now are dropped
|
# fields that are computed now are dropped
|
||||||
"devices/batteries": (
|
"devices/batteries": (
|
||||||
"devices/batteries",
|
"devices/batteries",
|
||||||
_list_to_device_dict("bat", _migrate_battery_item),
|
_list_to_device_dict(_DEVICE_KEY_PREFIXES["batteries"], _migrate_battery_item),
|
||||||
),
|
),
|
||||||
"devices/batteries/0/initial_soc_percentage": None,
|
"devices/batteries/0/initial_soc_percentage": None,
|
||||||
# - electric_vehicles
|
# - electric_vehicles
|
||||||
# same item migration as for batteries
|
# same item migration as for batteries
|
||||||
"devices/electric_vehicles": (
|
"devices/electric_vehicles": (
|
||||||
"devices/electric_vehicles",
|
"devices/electric_vehicles",
|
||||||
_list_to_device_dict("ev", _migrate_battery_item),
|
_list_to_device_dict(_DEVICE_KEY_PREFIXES["electric_vehicles"], _migrate_battery_item),
|
||||||
),
|
),
|
||||||
"devices/electric_vehicles/0/initial_soc_percentage": None,
|
"devices/electric_vehicles/0/initial_soc_percentage": None,
|
||||||
# - inverters
|
# - inverters
|
||||||
@@ -354,12 +439,12 @@ MIGRATION_MAP: Dict[
|
|||||||
# efficiencies come from the inverter profile now
|
# efficiencies come from the inverter profile now
|
||||||
"devices/inverters": (
|
"devices/inverters": (
|
||||||
"devices/inverters",
|
"devices/inverters",
|
||||||
_list_to_device_dict("inv", _migrate_inverter_item),
|
_list_to_device_dict(_DEVICE_KEY_PREFIXES["inverters"], _migrate_inverter_item),
|
||||||
),
|
),
|
||||||
# - home_appliances
|
# - home_appliances
|
||||||
"devices/home_appliances": (
|
"devices/home_appliances": (
|
||||||
"devices/home_appliances",
|
"devices/home_appliances",
|
||||||
_list_to_device_dict("appliance"),
|
_list_to_device_dict(_DEVICE_KEY_PREFIXES["home_appliances"]),
|
||||||
),
|
),
|
||||||
# elecfee
|
# elecfee
|
||||||
# =======
|
# =======
|
||||||
@@ -511,6 +596,8 @@ def migrate_config_data(config_data: Dict[str, Any]) -> "SettingsEOSDefaults":
|
|||||||
pv_settings = normalize_akkudoktor_settings(config_data.get("pvforecast"))
|
pv_settings = normalize_akkudoktor_settings(config_data.get("pvforecast"))
|
||||||
if isinstance(pv_settings, dict):
|
if isinstance(pv_settings, dict):
|
||||||
config_data["pvforecast"] = pv_settings
|
config_data["pvforecast"] = pv_settings
|
||||||
|
# Before the device lists become maps: config paths with list positions follow the device id.
|
||||||
|
config_data = _migrate_config_entity_device_positions(config_data)
|
||||||
|
|
||||||
new_config = SettingsEOSDefaults()
|
new_config = SettingsEOSDefaults()
|
||||||
if isinstance(pv_settings, dict) and "akkudoktor" in pv_settings:
|
if isinstance(pv_settings, dict) and "akkudoktor" in pv_settings:
|
||||||
|
|||||||
@@ -660,6 +660,123 @@ class TestDeviceMigration:
|
|||||||
"general/latitude": "sensor.latitude",
|
"general/latitude": "sensor.latitude",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
def test_migration_of_home_assistant_config_paths_with_list_positions(self) -> None:
|
||||||
|
"""Devices were lists: config paths with a list position follow the device id."""
|
||||||
|
raw = {
|
||||||
|
"devices": {
|
||||||
|
"batteries": [{"device_id": "battery1", "capacity_wh": 10000}],
|
||||||
|
# No device_id: the device migrates to the key "ev0".
|
||||||
|
"electric_vehicles": [{"capacity_wh": 60000}],
|
||||||
|
"inverters": [{"device_id": "inverter1", "max_power_w": 8000}],
|
||||||
|
"home_appliances": [
|
||||||
|
{"device_id": "dishwasher", "consumption_wh": 2000, "duration_h": 3},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"adapter": {
|
||||||
|
"homeassistant": {
|
||||||
|
"config_entity_ids": {
|
||||||
|
"devices/batteries/0/capacity_wh": "input_number.capacity",
|
||||||
|
"devices/batteries/0/min_soc_percentage": "input_number.min_soc",
|
||||||
|
"devices/batteries/0/max_charge_power_w": "input_number.charge_limit",
|
||||||
|
"devices/electric_vehicles/0/min_soc_percentage": "input_number.ev_min_soc",
|
||||||
|
"devices/inverters/0/max_power_w": "input_number.inverter_power",
|
||||||
|
"devices/home_appliances/0/consumption_wh": "input_number.dishwasher_wh",
|
||||||
|
# Already addressed by device id.
|
||||||
|
"devices/batteries/battery1/max_soc_percentage": "input_number.max_soc",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
migrated = migrate_config_data(raw)
|
||||||
|
entity_ids = migrated.adapter.homeassistant.config_entity_ids
|
||||||
|
assert entity_ids == {
|
||||||
|
"devices/batteries/battery1/profile_adjustment/nominal_capacity_wh": (
|
||||||
|
"input_number.capacity"
|
||||||
|
),
|
||||||
|
"devices/batteries/battery1/min_soc_percentage": "input_number.min_soc",
|
||||||
|
"devices/batteries/battery1/profile_adjustment/max_charge_power_w": (
|
||||||
|
"input_number.charge_limit"
|
||||||
|
),
|
||||||
|
"devices/batteries/battery1/profile_adjustment/max_discharge_power_w": (
|
||||||
|
"input_number.charge_limit"
|
||||||
|
),
|
||||||
|
"devices/electric_vehicles/ev0/min_soc_percentage": "input_number.ev_min_soc",
|
||||||
|
"devices/inverters/inverter1/profile_adjustment/nominal_power_w": (
|
||||||
|
"input_number.inverter_power"
|
||||||
|
),
|
||||||
|
"devices/home_appliances/dishwasher/consumption_wh": "input_number.dishwasher_wh",
|
||||||
|
"devices/batteries/battery1/max_soc_percentage": "input_number.max_soc",
|
||||||
|
}
|
||||||
|
# Every path names an existing setting, as the Home Assistant adapter requires.
|
||||||
|
assert entity_ids is not None
|
||||||
|
for path in entity_ids:
|
||||||
|
migrated.get_nested_value(path)
|
||||||
|
|
||||||
|
def test_migration_keeps_home_assistant_config_paths_of_device_maps(self) -> None:
|
||||||
|
"""Device maps are keyed by device id already, also when an id looks like a position."""
|
||||||
|
raw = {
|
||||||
|
"devices": {"batteries": {"0": {"device_id": "0", "min_soc_percentage": 10}}},
|
||||||
|
"adapter": {
|
||||||
|
"homeassistant": {
|
||||||
|
"config_entity_ids": {
|
||||||
|
"devices/batteries/0/min_soc_percentage": "input_number.min_soc",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
migrated = migrate_config_data(raw)
|
||||||
|
assert migrated.adapter.homeassistant.config_entity_ids == {
|
||||||
|
"devices/batteries/0/min_soc_percentage": "input_number.min_soc",
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_migration_warns_about_a_home_assistant_config_path_without_device(self) -> None:
|
||||||
|
"""A list position without a device is kept and named in a warning."""
|
||||||
|
from loguru import logger
|
||||||
|
|
||||||
|
raw = {
|
||||||
|
"devices": {"batteries": [{"device_id": "battery1"}]},
|
||||||
|
"adapter": {
|
||||||
|
"homeassistant": {
|
||||||
|
"config_entity_ids": {
|
||||||
|
"devices/batteries/1/min_soc_percentage": "input_number.min_soc",
|
||||||
|
"devices/electric_vehicles/0/min_soc_percentage": "input_number.ev",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
messages: list[str] = []
|
||||||
|
sink_id = logger.add(
|
||||||
|
lambda message: messages.append(message.record["message"]), level="WARNING"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
migrated = migrate_config_data(raw)
|
||||||
|
finally:
|
||||||
|
logger.remove(sink_id)
|
||||||
|
assert migrated.adapter.homeassistant.config_entity_ids == {
|
||||||
|
"devices/batteries/1/min_soc_percentage": "input_number.min_soc",
|
||||||
|
"devices/electric_vehicles/0/min_soc_percentage": "input_number.ev",
|
||||||
|
}
|
||||||
|
assert any("devices/batteries/1/min_soc_percentage" in m for m in messages)
|
||||||
|
assert any("devices/electric_vehicles/0/min_soc_percentage" in m for m in messages)
|
||||||
|
|
||||||
|
def test_migration_prefers_the_home_assistant_config_path_with_list_position(self) -> None:
|
||||||
|
"""With device lists only the list position addressed a device; it wins over the id."""
|
||||||
|
raw = {
|
||||||
|
"devices": {"batteries": [{"device_id": "battery1"}]},
|
||||||
|
"adapter": {
|
||||||
|
"homeassistant": {
|
||||||
|
"config_entity_ids": {
|
||||||
|
"devices/batteries/battery1/min_soc_percentage": "input_number.by_id",
|
||||||
|
"devices/batteries/0/min_soc_percentage": "input_number.by_position",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
migrated = migrate_config_data(raw)
|
||||||
|
assert migrated.adapter.homeassistant.config_entity_ids == {
|
||||||
|
"devices/batteries/battery1/min_soc_percentage": "input_number.by_position",
|
||||||
|
}
|
||||||
|
|
||||||
def test_migrate_config_file_keeps_charge_power_limit(self, tmp_path: Path):
|
def test_migrate_config_file_keeps_charge_power_limit(self, tmp_path: Path):
|
||||||
"""The legacy charge power limit survives the file migration."""
|
"""The legacy charge power limit survives the file migration."""
|
||||||
config_file = tmp_path / "EOS.config.json"
|
config_file = tmp_path / "EOS.config.json"
|
||||||
|
|||||||
Reference in New Issue
Block a user