homeassistant-config/custom_components/dimmer/__init__.py

74 lines
2.4 KiB
Python

""" Service to increase/decrease light brightness"""
import logging
import voluptuous as vol
from homeassistant.components.light import ATTR_BRIGHTNESS, DOMAIN as LIGHT_DOMAIN, ATTR_TRANSITION
from homeassistant.const import SERVICE_TURN_ON, ATTR_ENTITY_ID
# The domain of your component. Should be equal to the name of your component.
from homeassistant.helpers.service import async_extract_entity_ids
DOMAIN = "dimmer"
# List of component names (string) your component depends upon.
# We depend on group because group will be loaded after all the components that
# initialize devices have been setup.
DEPENDENCIES = ['group', 'light']
# Name of the service that we expose.
SERVICE_DIM = 'dim'
# Shortcut for the logger
_LOGGER = logging.getLogger(__name__)
# Validate that all required config options are given.
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({})
}, extra=vol.ALLOW_EXTRA)
async def async_setup(hass, config):
"""Setup example component."""
async def async_dim_service(service):
params = service.data.copy()
entity_ids = await async_extract_entity_ids(hass, service, expand_group=True)
offset = params.get('offset', None)
factor = params.get('factor', None)
min_brightness = params.get('min_brightness', 6)
transition = params.get(ATTR_TRANSITION, None)
if factor is None and offset is None:
offset = 50
assert not (factor is not None and offset is not None)
def clip_value(level):
level = int(level)
if level < min_brightness:
return min_brightness
if level > 255:
return 255
return level
for entity_id in entity_ids:
brightness = hass.states.get(entity_id).attributes.get('brightness', 0)
state = hass.states.get(entity_id).state
if state == 'off':
continue
if factor is not None:
data = {ATTR_BRIGHTNESS: clip_value(brightness * factor)}
if offset is not None:
data = {ATTR_BRIGHTNESS: clip_value(brightness + offset)}
data[ATTR_ENTITY_ID] = entity_id
if transition:
data[ATTR_TRANSITION] = transition
await hass.services.async_call(LIGHT_DOMAIN, SERVICE_TURN_ON, data)
hass.services.async_register(DOMAIN, SERVICE_DIM, async_dim_service)
return True