feat: refactor services to be more organized

This commit is contained in:
Niklas 2025-01-17 16:02:38 +01:00
parent 647efb0e61
commit 1d8fe7a6ab
4 changed files with 76 additions and 54 deletions

View File

@ -4,17 +4,17 @@ from __future__ import annotations
import logging
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform, CONF_HOST, CONF_PORT, CONF_NAME, ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN
from homeassistant.const import Platform, CONF_HOST, CONF_PORT, CONF_NAME
from homeassistant.core import HomeAssistant, callback
from .const import (
DOMAIN,
DATA_COORDINATOR,
DATA_CONFIG,
DEFAULT_PORT, SERVICE_SET_ANIMATION_SPEED, SERVICE_SCHEMA_ANIMATION_SPEED, ATTR_SPEED,
DEFAULT_PORT
)
from .coordinator import SmartHomeDataUpdateCoordinator
from .services import async_setup_services, async_unload_services
_LOGGER = logging.getLogger(__name__)
@ -27,64 +27,40 @@ PLATFORMS: list[Platform] = [
Platform.BINARY_SENSOR,
]
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Smart Home from a config entry."""
hass.data.setdefault(DOMAIN, {})
coordinator = SmartHomeDataUpdateCoordinator(
hass,
config=entry.data,
entry_id=entry.entry_id,
)
await coordinator.async_config_entry_first_refresh()
hass.data[DOMAIN][entry.entry_id] = {
DATA_COORDINATOR: coordinator,
DATA_CONFIG: entry.data,
}
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
# Register services
async def service_handler(call: ServiceCall) -> None:
"""Handle the services."""
# coordinator = hass.data[DOMAIN][entry.entry_id][DATA_COORDINATOR]
if call.service == SERVICE_SET_ANIMATION_SPEED:
# Get all light entities from the call
target_entities = call.data.get(ATTR_ENTITY_ID)
speed = call.data.get(ATTR_SPEED)
for entity_id in target_entities:
# Find the light entity
entity = hass.data[LIGHT_DOMAIN].get_entity(entity_id)
if entity and hasattr(entity, "set_animation_speed"):
await entity.set_animation_speed(speed)
else:
_LOGGER.warning(
"Entity %s doesn't support animation speed adjustment",
entity_id
)
hass.services.async_register(
DOMAIN,
SERVICE_SET_ANIMATION_SPEED,
service_handler,
schema=SERVICE_SCHEMA_ANIMATION_SPEED,
)
await async_setup_services(hass)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
coordinator: SmartHomeDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][DATA_COORDINATOR]
await coordinator.async_shutdown()
hass.data[DOMAIN].pop(entry.entry_id)
# Unregister services
hass.services.async_remove(DOMAIN, SERVICE_SET_ANIMATION_SPEED)
await async_unload_services(hass)
return unload_ok

View File

@ -1,11 +1,6 @@
"""Constants for the Smart Home integration."""
import voluptuous as vol
from typing import Final
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.helpers import config_validation as cv
DOMAIN: Final = "smart_home"
CONF_HOST: Final = "host"
@ -20,12 +15,3 @@ STEP_USER: Final = "user"
DATA_COORDINATOR: Final = "coordinator"
DATA_CONFIG: Final = "config"
SERVICE_SET_ANIMATION_SPEED = "set_animation_speed"
ATTR_SPEED = "speed"
SERVICE_SCHEMA_ANIMATION_SPEED = vol.Schema({
vol.Required(ATTR_ENTITY_ID): cv.comp_entity_ids,
vol.Required(ATTR_SPEED): vol.All(
vol.Coerce(int), vol.Range(min=1, max=255)
),
})

View File

@ -168,10 +168,12 @@ class SmartHomeLight(SmartHomeEntity, LightEntity):
if ATTR_EFFECT in kwargs:
# Convert HA effect name back to API animation mode
effect_name = kwargs[ATTR_EFFECT]
if effect_name in self._effect_map:
data["animation"] = self._effect_map[effect_name]
effect_key = list(self._effect_map.keys())[list(self._effect_map.values()).index(effect_name)]
if effect_key is not None:
# get effect key from value
data["animation"] = effect_key
else:
_LOGGER.warning("Unknown effect name: %s. Valid effects are: %s", effect_name, list(self._effect_map.keys()))
_LOGGER.warning("Unknown effect name: %s (%s). Valid effects are: %s", effect_name, effect_key, list(self._effect_map.keys()))
_LOGGER.debug("Sending data to API: %s", data)
async with aiohttp.ClientSession() as session:

View File

@ -0,0 +1,58 @@
"""Service for adjusting animation speed of RGB lights."""
from __future__ import annotations
import logging
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
SERVICE_SET_ANIMATION_SPEED = "set_animation_speed"
ATTR_SPEED = "speed"
SERVICE_SCHEMA_ANIMATION_SPEED = vol.Schema({
vol.Required(ATTR_ENTITY_ID): cv.comp_entity_ids,
vol.Required(ATTR_SPEED): vol.All(
vol.Coerce(int), vol.Range(min=1, max=255)
),
})
async def async_setup_services(hass: HomeAssistant) -> None:
"""Set up the Light Animation services."""
# Register services
async def service_handler(call: ServiceCall) -> None:
"""Handle the services."""
# coordinator = hass.data[DOMAIN][entry.entry_id][DATA_COORDINATOR]
if call.service == SERVICE_SET_ANIMATION_SPEED:
# Get all light entities from the call
target_entities = call.data.get(ATTR_ENTITY_ID)
speed = call.data.get(ATTR_SPEED)
for entity_id in target_entities:
# Find the light entity
entity = hass.data[LIGHT_DOMAIN].get_entity(entity_id)
if entity and hasattr(entity, "set_animation_speed"):
await entity.set_animation_speed(speed)
else:
_LOGGER.warning(
"Entity %s doesn't support animation speed adjustment",
entity_id
)
hass.services.async_register(
DOMAIN,
SERVICE_SET_ANIMATION_SPEED,
service_handler,
schema=SERVICE_SCHEMA_ANIMATION_SPEED,
)
async def async_unload_services(hass: HomeAssistant) -> None:
# Unregister services
hass.services.async_remove(DOMAIN, SERVICE_SET_ANIMATION_SPEED)