Programmatically create entities

Hey there,

I guess this has been asked a bazillion times already and I found similar topics, but not 100% what I was looking for.

So I’m looking into programmatically create a switch entity per room my vacuum knows. I achieved that easily with a python script, no problem:

vacuumEntity = data.get("vacuum")

if vacuumEntity is None:
  logger.error("No vacuum entity given. Exiting...")
else:
  logger.info("vacuumEntity: {:s}".format(vacuumEntity))

  if hass.states.get(vacuumEntity) is None:
    logger.error("Given vacuum entity '{:s}' doesn't exist. Exiting...".format(vacuumEntity))
  else:
    vacuumEntityNoDomain = vacuumEntity.lstrip('vacuum.')

    for roomNumber in range(0, 255):
      hass.states.remove("switch.{:s}_room_{:d}_selected".format(vacuumEntityNoDomain, roomNumber))
    
    roomIds = []
    if "rooms" in hass.states.get(vacuumEntity).attributes:
      for map, rooms in hass.states.get(vacuumEntity).attributes["rooms"].items():
        for room in rooms:
          if room["id"] not in roomIds:
            roomIds.append(room["id"])
    logger.info(roomIds)
    
    if len(roomIds) > 0:
      for roomId in roomIds:
        hass.states.set(entity_id="switch.{:s}_room_{:d}_selected".format(vacuumEntityNoDomain, roomId), new_state="off", attributes={"room_id": roomId})

BUT: The issue is I cannot use the switch.toggle, switch.turn_on, switch.turn_off actions, because (I guess) they are not really knows to HA; I just created a state in the state machine.

How can I achieve to have “valid” entities created that HA knows? I would love to dynamically re-create these room entities, similar to what you can achieve with group.set, where you can create group entities at runtime.

Sure, my rooms barely change in my house, sure I can hardcode them. It’s more a learning thing and checking if this is possible at all :slight_smile:

Thanks and greetings,

Andy!

1 Like