Skip to content

Commit 7a0d6bd

Browse files
committed
Fixed restorr of manual sensor
1 parent a7f9134 commit 7a0d6bd

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

custom_components/cardata/number.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
from homeassistant.core import HomeAssistant
3737
from homeassistant.helpers.device_registry import DeviceInfo
3838
from homeassistant.helpers.entity_platform import AddEntitiesCallback
39+
from homeassistant.helpers.entity_registry import async_entries_for_config_entry, async_get
3940
from homeassistant.helpers.restore_state import RestoreEntity
4041

4142
from .const import DOMAIN, MANUAL_CAPACITY_DESCRIPTOR
@@ -58,6 +59,7 @@ async def async_setup_entry(
5859
coordinator = runtime.coordinator
5960

6061
entities: list[NumberEntity] = []
62+
created_vins: set[str] = set()
6163

6264
# Create manual battery capacity input for each known EV/PHEV vehicle
6365
for vin in coordinator.data.keys():
@@ -74,8 +76,47 @@ async def async_setup_entry(
7476
entry_id=entry.entry_id,
7577
)
7678
)
79+
created_vins.add(vin)
7780
_LOGGER.debug("Created manual battery capacity input for %s (%s)", vehicle_name, redact_vin(vin))
7881

82+
# Restore previously created entities from entity registry (even if VIN not currently online)
83+
entity_registry = async_get(hass)
84+
for entity_entry in async_entries_for_config_entry(entity_registry, entry.entry_id):
85+
if entity_entry.domain != "number":
86+
continue
87+
88+
unique_id = entity_entry.unique_id
89+
if not unique_id or "_" not in unique_id:
90+
continue
91+
92+
# Check if this is a manual capacity entity
93+
if not unique_id.endswith(f"_{MANUAL_CAPACITY_DESCRIPTOR}"):
94+
continue
95+
96+
# Extract VIN from unique_id
97+
vin = unique_id.replace(f"_{MANUAL_CAPACITY_DESCRIPTOR}", "")
98+
99+
# Skip if already created above
100+
if vin in created_vins:
101+
continue
102+
103+
# Restore entity even if vehicle is offline or not in coordinator.data yet
104+
vehicle_name = coordinator.names.get(vin, redact_vin(vin))
105+
entities.append(
106+
ManualBatteryCapacityNumber(
107+
coordinator=coordinator,
108+
vin=vin,
109+
vehicle_name=vehicle_name,
110+
entry_id=entry.entry_id,
111+
)
112+
)
113+
created_vins.add(vin)
114+
_LOGGER.debug(
115+
"Restored manual battery capacity input for %s (%s) from entity registry",
116+
vehicle_name,
117+
redact_vin(vin),
118+
)
119+
79120
if entities:
80121
async_add_entities(entities)
81122
_LOGGER.debug("Added %d number entities", len(entities))

0 commit comments

Comments
 (0)