I am currently developing a Homeassistant Custom Integration where I have a config_flow to handle the options config_entries.OptionsFlow
.
As the options change may add new entities based on the configuration I added the following code to my async def async_setup_entry(hass, config_entry, async_add_entities):
async def async_setup_entry(hass, config_entry, async_add_entities):
_LOGGER.debug("async_setup_entry: Setting up the sensor")
items = config_entry.data.get(CONF_ITEMS, [])
scan_interval = config_entry.data.get(CONF_SCAN_INTERVAL, 60)
item_amounts = config_entry.data.get(CONF_ITEM_AMOUNTS, {})
item_sensors = []
total_sensor = MyTotalSensor(hass, config_entry, items, item_amounts, item_sensors, timedelta(seconds=scan_interval))
for item in items:
item_amount = item_amounts.get(item, 1) # Default to 1 if not specified
item_sensor = MyItemSensor(token, item_amount , total_sensor)
item_sensors.append(item_sensor)
# Add the sensors to Home Assistant
async_add_entities([total_sensor] + item_sensors, True)
# Handle config update listener
async def _update_listener(hass, config_entry):
_LOGGER.info(f"Updating Sensors due to configuration change: {config_entry}")
await hass.config_entries.async_forward_entry_unload(config_entry, "sensor")
await async_setup_entry(hass, config_entry, async_add_entities)
config_entry.async_on_unload(config_entry.add_update_listener(_update_listener))
Unfortunately this leads to strange behaviour as the update for some reason calls async_setup_entry
twice.
MyTotalSensor has an update method which is called periodically:
How is the best approach to implement such updating via options that can add sensor entities? Can anyone guide me to an example for such sequence?