Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add homeassistant.add_label_to_entity service #717

Merged
merged 1 commit into from
Apr 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""Spook - Your homie."""

from __future__ import annotations

from typing import TYPE_CHECKING

import voluptuous as vol

from homeassistant.components.homeassistant import DOMAIN
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import (
config_validation as cv,
entity_registry as er,
label_registry as lr,
)

from ....services import AbstractSpookAdminService

if TYPE_CHECKING:
from homeassistant.core import ServiceCall


class SpookService(AbstractSpookAdminService):
"""Home Assistant service to add a label to an entity."""

domain = DOMAIN
service = "add_label_to_entity"
schema = {
vol.Required("label_id"): vol.All(cv.ensure_list, [cv.string]),
vol.Required("entity_id"): vol.All(cv.ensure_list, [cv.string]),
}

async def async_handle_service(self, call: ServiceCall) -> None:
"""Handle the service call."""
label_registry = lr.async_get(self.hass)
for label_id in call.data["label_id"]:
if not label_registry.async_get_label(label_id):
msg = f"Label {label_id} not found"
raise HomeAssistantError(msg)

entity_registry = er.async_get(self.hass)
for entity_id in call.data["entity_id"]:
if entity_entry := entity_registry.async_get(entity_id):
labels = entity_entry.labels.copy()
labels.update(call.data["label_id"])
entity_registry.async_update_entity(entity_id, labels=labels)
21 changes: 21 additions & 0 deletions custom_components/spook/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -557,6 +557,27 @@ homeassistant_add_label_to_device:
device:
multiple: true

homeassistant_add_label_to_entity:
name: Add a label to an entity 👻
description: >-
Adds a label to an entity. If multiple labels or multiple entities are
provided, all combinations will be added.
fields:
label_id:
name: Label ID
description: The ID(s) of the label(s) to add the entity/entities.
required: true
selector:
label:
multiple: true
entity_id:
name: Entity ID
description: The ID(s) of the entity/entities to add the label(s) to.
required: true
selector:
entity:
multiple: true

homeassistant_delete_label:
name: Delete a label 👻
description: >-
Expand Down