What is the best way to first delete sensors and then create new ones?
The following code works at startup. However, when the time interval is called, no more entities are deleted, before new ones should created. When I create a new one I always get the error that an entity with this id already exists. So how can I reliably delete entities?
def _init_regular_updates(self) -> None:
"""Schedule regular updates based on configured time interval."""
async_track_time_interval(
self._hass,
self._update_async_track_time_interval,
self._coordinator.update_interval,
cancel_on_shutdown=True,
)
@callback
def _update_async_track_time_interval(self, now: datetime | None = None) -> None:
"""Async update"""
self._update()
def _remove_entity(self) -> None:
entity_reg = er.async_get(self._hass)
start = 1
#start = len(self._managed_devices) + 1
#for device in list(self._managed_devices):
# self._managed_devices.remove(device)
# self._hass.add_job(device.async_remove())
max_iterations=1000
for i in range(start,max_iterations):
unique_id= f"{self._unique_id}_{count}"
entity = entity_reg.async_get_entity_id(SENSOR_PLATFORM, DOMAIN, unique_id)
LOGGER.warning(f"Removing id {unique_id} with entity {entity}")
if entity is None:
return
LOGGER.warning("Removing...")
entity_reg.async_remove(entity)
def _update(self) -> None:
"""Update Sensors."""
self._remove_entity()
self._add_entity()