<s> """<STR_LIT>""" <EOL> import itertools as it <EOL> import logging <EOL> import homeassistant . core as ha <EOL> from homeassistant . helpers . entity import split_entity_id <EOL> from homeassistant . helpers . service import extract_entity_ids <EOL> from homeassistant . loader import get_component <EOL> from homeassistant . const import ( <EOL> ATTR_ENTITY_ID , SERVICE_TURN_ON , SERVICE_TURN_OFF , SERVICE_TOGGLE ) <EOL> _LOGGER = logging . getLogger ( __name__ ) <EOL> def is_on ( hass , entity_id = None ) : <EOL> """<STR_LIT>""" <EOL> if entity_id : <EOL> group = get_component ( '<STR_LIT>' ) <EOL> entity_ids = group . expand_entity_ids ( hass , [ entity_id ] ) <EOL> else : <EOL> entity_ids = hass . states . entity_ids ( ) <EOL> for entity_id in entity_ids : <EOL> domain = split_entity_id ( entity_id ) [ <NUM_LIT:0> ] <EOL> module = get_component ( domain ) <EOL> try : <EOL> if module . is_on ( hass , entity_id ) : <EOL> return True <EOL> except AttributeError : <EOL> _LOGGER . exception ( "<STR_LIT>" , <EOL> module , entity_id ) <EOL> return False <EOL> def turn_on ( hass , entity_id = None , ** service_data ) : <EOL> """<STR_LIT>""" <EOL> if entity_id is not None : <EOL> service_data [ ATTR_ENTITY_ID ] = entity_id <EOL> hass . services . call ( ha . DOMAIN , SERVICE_TURN_ON , service_data ) <EOL> def turn_off ( hass , entity_id = None , ** service_data ) : <EOL> """<STR_LIT>""" <EOL> if entity_id is not None : <EOL> service_data [ ATTR_ENTITY_ID ] = entity_id <EOL> hass . services . call ( ha . DOMAIN , SERVICE_TURN_OFF , service_data ) <EOL> def toggle ( hass , entity_id = None , ** service_data ) : <EOL> """<STR_LIT>""" <EOL> if entity_id is not None : <EOL> service_data [ ATTR_ENTITY_ID ] = entity_id <EOL> hass . services . call ( ha . DOMAIN , SERVICE_TOGGLE , service_data ) <EOL> def setup ( hass , config ) : <EOL> """<STR_LIT>""" <EOL> def handle_turn_service ( service ) : <EOL> """<STR_LIT>""" <EOL> entity_ids = extract_entity_ids ( hass , service ) <EOL> if not entity_ids : <EOL> _LOGGER . error ( <EOL> "<STR_LIT>" , <EOL> service . service ) <EOL> return <EOL> by_domain = it . groupby ( sorted ( entity_ids ) , <EOL> lambda item : split_entity_id ( item ) [ <NUM_LIT:0> ] ) <EOL> for domain , ent_ids in by_domain : <EOL> blocking = hass . services . has_service ( domain , service . service ) <EOL> data = dict ( service . data ) <EOL> data [ ATTR_ENTITY_ID ] = list ( ent_ids ) <EOL> hass . services . call ( domain , service . service , data , blocking ) <EOL> hass . services . register ( ha . DOMAIN , SERVICE_TURN_OFF , handle_turn_service ) <EOL> hass . services . register ( ha . DOMAIN , SERVICE_TURN_ON , handle_turn_service ) <EOL> hass . services . register ( ha . DOMAIN , SERVICE_TOGGLE , handle_turn_service ) <EOL> return True </s>
