I’m building an integration for a power station which has sensors for battery data from the BMS, etc. The unit may also have one or two add-on batteries. I’ve created disabled entities for the extra batteries but am trying to devise a way to automatically enable them if data specific to each entity is detected on the appropriate MQTT topic. What I am missing is the appropriate call to enable the entity after the fact…
I am creating the entity using async_add_entities:
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Add entities to Home Assistant."""
entities = [
MySensor(
device,
"EB1",
"batt1SoC",
unit=UNIT_PERCENT,
device_class="BATTERY",
state_class="MEASUREMENT",
dec=2,
enabled=False,
),
MySensor(
device,
"EB2",
"batt2SoC",
unit=UNIT_PERCENT,
device_class="BATTERY",
state_class="MEASUREMENT",
dec=2,
enabled=False,
),
]
async_add_entities(entities)
And the base class does this:
class BaseEntity(Entity):
"""Base class for entities."""
_attr_should_poll = False
_attr_has_entity_name = True
_attr_entity_registry_visible_default = True
def __init__(
self,
device: MyDevice,
entity_name: str,
mqtt_key: str,
platform: str,
json_template: str = None,
entity_category: str = None,
enabled: bool = True,
) -> None:
"""Initialize the entity."""
self.device = device
self.mqtt_key = mqtt_key
self.json_template = json_template
self._attr_name = entity_name
self.entity_id = f"{platform}.{device.device_id}-{slugify(entity_name)}"
self._attr_unique_id = f"{device.device_sn}-{slugify(entity_name)}"
self._attr_device_info = device.device_info
self._attr_entity_category = (
EntityCategory[entity_category] if entity_category else None
)
self._attr_state = None
self._attr_native_value = None
self._attr_entity_registry_enabled_default = enabled
This successfully creates a disabled entity in the registry which can be manually enabled in th UI… But I’m having trouble identifying the correct call (or way to code) for enabling the entity, programmatically, when/if my integration detects that data for it is available…
I’m also wondering if using this method will always start these “dynamic” entities in a disabled state when HA is restarted and/or how to detect if they are no longer present and dynamically disable them. Since extra batteries can be attached or detached it would be nice to have an elegant way to handle that. I can create all entities and just allow them to be “unknown” unless/until data arrives for them and return to “unknown” on HA restart but that seems a little ugly to me.
This is my first full scale HA integration so any assistance is appreciated.