Python homeassistant.helpers.config_validation.entity_id() Examples

The following are 30 code examples of homeassistant.helpers.config_validation.entity_id(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module homeassistant.helpers.config_validation , or try the search function .
Example #1
Source File: camera.py    From hass-aarlo with GNU Lesser General Public License v3.0 6 votes vote down vote up
def websocket_snapshot_image(hass, connection, msg):
    try:
        camera = get_entity_from_domain(hass, DOMAIN, msg['entity_id'])
        _LOGGER.debug('snapshot_image for ' + str(camera.unique_id))

        image = await camera.async_get_snapshot()
        connection.send_message(websocket_api.result_message(
            msg['id'], {
                'content_type': camera.content_type,
                'content': base64.b64encode(image).decode('utf-8')
            }
        ))
    except HomeAssistantError as error:
        connection.send_message(websocket_api.error_message(
            msg['id'], 'snapshot_image_ws', "Unable to take snapshot ({})".format(str(error))))
        _LOGGER.warning("{} snapshot image websocket failed".format(msg['entity_id'])) 
Example #2
Source File: camera.py    From hass-aarlo with GNU Lesser General Public License v3.0 6 votes vote down vote up
def websocket_video_url(hass, connection, msg):
    try:
        camera = get_entity_from_domain(hass, DOMAIN, msg['entity_id'])
        video = camera.last_video
        url = video.video_url if video is not None else None
        url_type = video.content_type if video is not None else None
        thumbnail = video.thumbnail_url if video is not None else None
        connection.send_message(websocket_api.result_message(
            msg['id'], {
                'url': url,
                'url_type': url_type,
                'thumbnail': thumbnail,
                'thumbnail_type': 'image/jpeg',
            }
        ))
    except HomeAssistantError as error:
        connection.send_message(websocket_api.error_message(
            msg['id'], 'video_url_ws', "Unable to fetch url ({})".format(str(error))))
        _LOGGER.warning("{} video url websocket failed".format(msg['entity_id'])) 
Example #3
Source File: __init__.py    From common_timer with Apache License 2.0 6 votes vote down vote up
def save_tasks(self):
        """save task config to disk"""
        tasks = [
            {
                'entity_id': attrs['entity_id'],
                'duration': attrs['duration'],
                'operation': attrs['operation'],
                'count': attrs['count'],
                'ratio': attrs['ratio']
            } 
            for entities in self._tasks.values() for entity_id, attrs in entities.items() if attrs['duration'] != '0:00:00' or attrs['count'] != 0
        ]
        # _LOGGER.debug('[stop()] save task config: <tasks=%s>',tasks)
        if not tasks:
            return
        data = {
            'tasks':tasks
        }
        yield from self._store.async_save(data) 
Example #4
Source File: __init__.py    From common_timer with Apache License 2.0 6 votes vote down vote up
def set_state(self, entity_id, state = None, attributes = None, service = None, force_update = False, context = None):
        """ set entity state. """
        if context is None:
            context = CONTEXT
        if service is None:
            _LOGGER.debug("[set_state] state machine: entity_id= {}, from {} to {}, context = {}".format(entity_id, self.get_state(entity_id), state, context))
            attr = self.get_attributes(entity_id)
            if attributes is not None:
                attr.update(attributes)
            self._hass.states.async_set(entity_id, state, attr, force_update = force_update, context = context)
        else:
            domain = entity_id.split('.')[0]
            _LOGGER.debug('[set_state] call service: entity_id =%s, context = %s',entity_id, context)
            # unused, after 0.78.0 fixed.
            # attr = self.get_attributes(entity_id)
            # if attributes is not None:
            #     attr.update(attributes)
            # change state directly with a context identification since call service can't pass context in code.
            # self._hass.states.async_set(entity_id, state, attr, force_update = force_update, context = CONTEXT)
            data = {'entity_id': entity_id}
            if state is not None:
                data.update(state)
            # call service to controll device
            # self._hass.services.async_call(domain, service, data, blocking = True, context = context )
            self._hass.async_add_job(self._hass.services.async_call(domain, service, data, context = context )) 
Example #5
Source File: __init__.py    From xknx with MIT License 6 votes vote down vote up
def _async_entity_changed(self, entity_id, old_state, new_state):
        """Handle entity change."""
        if new_state is None:
            return
        if new_state.state in (STATE_UNKNOWN, STATE_UNAVAILABLE):
            return

        if self.expose_attribute is not None:
            new_attribute = new_state.attributes.get(self.expose_attribute)
            if old_state is not None:
                old_attribute = old_state.attributes.get(self.expose_attribute)
                if old_attribute == new_attribute:
                    # don't send same value sequentially
                    return
            await self._async_set_knx_value(new_attribute)
        else:
            await self._async_set_knx_value(new_state.state) 
Example #6
Source File: __init__.py    From HomeAssistant_Components with Apache License 2.0 6 votes vote down vote up
def entity_id_to_number(self, entity_id):
        """Get a unique number for the entity id."""
        if self.type == TYPE_ALEXA:
            return entity_id

        if self.numbers is None:
            self.numbers = _load_json(self.hass.config.path(NUMBERS_FILE))

        # Google Home
        for number, ent_id in self.numbers.items():
            if entity_id == ent_id:
                return number

        number = '1'
        if self.numbers:
            number = str(max(int(k) for k in self.numbers) + 1)
        self.numbers[number] = entity_id
        save_json(self.hass.config.path(NUMBERS_FILE), self.numbers)
        return number 
Example #7
Source File: camera.py    From hass-config with GNU General Public License v3.0 6 votes vote down vote up
def websocket_snapshot_image(hass, connection, msg):
    camera = _get_camera_from_entity_id(hass, msg['entity_id'])
    _LOGGER.debug('snapshot_image for ' + str(camera.unique_id))

    try:
        image = await camera.async_get_snapshot()
        connection.send_message(websocket_api.result_message(
            msg['id'], {
                'content_type': camera.content_type,
                'content': base64.b64encode(image).decode('utf-8')
            }
        ))

    except HomeAssistantError:
        connection.send_message(websocket_api.error_message(
            msg['id'], 'image_fetch_failed', 'Unable to fetch image')) 
Example #8
Source File: __init__.py    From common_timer with Apache License 2.0 6 votes vote down vote up
def set_task(self, entity_id, operation, duration, is_loop):
        """ create new task, will overwrite previous task. """
        _LOGGER.debug('----set_task()-----')
        task = self._get_task(entity_id)
        if task is not None:
            self._queue.remove(task['handle'])
            task['duration'] = duration
            task['next_operation'] = operation
            if is_loop and 'custom:' not in operation:
                operation = 'temporary_' + operation
                state = 'off' if task['next_operation'] == 'on' else 'on'
                self.set_state(entity_id, service = 'turn_'+state, force_update = True)
            task['operation'] = operation
            task['handle'] = self._queue.insert(entity_id, duration, self.handle_task, operation = operation)  # initialize queue task
            task['exec_time'] = datetime.now() + self._queue.get_remaining_time(task['handle'])
            self._hass.async_add_job(self.update_info)  # refresh info panel
            if self._entity_id == entity_id:
                _LOGGER.debug("---set_task---")
                self.set_state(self._ui[UI_INPUT_OPERATION], state = self.get_operation(task = task))  # reset control panel ui
                self.set_state(self._ui[UI_INPUT_DURATION], state = task['duration'])
                self.set_state(self._ui[UI_SWITCH], state = 'on')
        else:
            _LOGGER.info('set up task for %s failure', entity_id) 
Example #9
Source File: camera.py    From hass-config with GNU General Public License v3.0 6 votes vote down vote up
def websocket_library(hass, connection, msg):
    camera = _get_camera_from_entity_id(hass, msg['entity_id'])
    videos = []
    _LOGGER.debug('library+' + str(msg['at_most']))
    for v in camera.last_n_videos(msg['at_most']):
        videos.append({
            'created_at': v.created_at,
            'created_at_pretty': v.created_at_pretty(camera.last_capture_date_format),
            'url': v.video_url,
            'url_type': v.content_type,
            'thumbnail': v.thumbnail_url,
            'thumbnail_type': 'image/jpeg',
            'object': v.object_type,
            'object_region': v.object_region,
            'trigger': v.object_type,
            'trigger_region': v.object_region,
        })
    connection.send_message(websocket_api.result_message(
        msg['id'], {
            'videos': videos,
        }
    )) 
Example #10
Source File: camera.py    From hass-aarlo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def async_camera_stop_recording_service(hass, call):
    for entity_id in call.data['entity_id']:
        try:
            _LOGGER.info("{} stop recording".format(entity_id))
            get_entity_from_domain(hass, DOMAIN, entity_id).stop_recording()
        except HomeAssistantError:
            _LOGGER.warning("{} stop recording service failed".format(entity_id)) 
Example #11
Source File: alarm_control_panel.py    From hass-aarlo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def websocket_siren_on(hass, connection, msg):
    base = _get_base_from_entity_id(hass, msg['entity_id'])
    _LOGGER.debug('stop_activity for ' + str(base.unique_id))

    await base.async_siren_on(duration=msg['duration'], volume=msg['volume'])
    connection.send_message(websocket_api.result_message(
        msg['id'], {
            'siren': 'on'
        }
    )) 
Example #12
Source File: camera.py    From hass-aarlo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def async_camera_siren_on_service(hass, call):
    for entity_id in call.data['entity_id']:
        try:
            volume = call.data[ATTR_VOLUME]
            duration = call.data[ATTR_DURATION]
            _LOGGER.info("{} start siren(volume={}/duration={})".format(entity_id, volume, duration))
            get_entity_from_domain(hass, DOMAIN, entity_id).siren_on(duration=duration, volume=volume)
        except HomeAssistantError:
            _LOGGER.warning("{} siren on service failed".format(entity_id)) 
Example #13
Source File: camera.py    From hass-aarlo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def async_camera_start_recording_service(hass, call):
    for entity_id in call.data['entity_id']:
        try:
            duration = call.data[ATTR_DURATION]
            _LOGGER.info("{} start recording(duration={})".format(entity_id, duration))
            camera = get_entity_from_domain(hass, DOMAIN, entity_id)
            await camera.async_start_recording(duration=duration)
        except HomeAssistantError:
            _LOGGER.warning("{} start recording service failed".format(entity_id)) 
Example #14
Source File: sensor.py    From thermal_comfort with MIT License 5 votes vote down vote up
def __init__(self, hass, device_id, temperature_entity, humidity_entity,
                 friendly_name, icon_template, entity_picture_template, sensor_type):
        """Initialize the sensor."""
        self.hass = hass
        self.entity_id = async_generate_entity_id(ENTITY_ID_FORMAT, "{}_{}".format(device_id, sensor_type), hass=hass)
        self._name = "{} {}".format(friendly_name, SENSOR_TYPES[sensor_type][1])
        self._unit_of_measurement = SENSOR_TYPES[sensor_type][2]
        self._state = None
        self._device_state_attributes = {}
        self._icon_template = icon_template
        self._entity_picture_template = entity_picture_template
        self._icon = None
        self._entity_picture = None
        self._temperature_entity = temperature_entity
        self._humidity_entity = humidity_entity
        self._device_class = SENSOR_TYPES[sensor_type][0]
        self._sensor_type = sensor_type
        self._temperature = None
        self._humidity = None

        async_track_state_change(
            self.hass, self._temperature_entity, self.temperature_state_listener)

        async_track_state_change(
            self.hass, self._humidity_entity, self.humidity_state_listener)

        temperature_state = hass.states.get(temperature_entity)
        if temperature_state and temperature_state.state != STATE_UNKNOWN:
            self._temperature = float(temperature_state.state)

        humidity_state = hass.states.get(humidity_entity)
        if humidity_state and humidity_state.state != STATE_UNKNOWN:
            self._humidity = float(humidity_state.state) 
Example #15
Source File: alarm_control_panel.py    From hass-aarlo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _get_base_from_entity_id(hass, entity_id):
    component = hass.data.get(DOMAIN)
    if component is None:
        raise HomeAssistantError('base component not set up')

    base = component.get_entity(entity_id)
    if base is None:
        raise HomeAssistantError('base not found')

    return base 
Example #16
Source File: alarm_control_panel.py    From hass-aarlo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def async_alarm_siren_on_service(hass, call):
    for entity_id in call.data['entity_id']:
        try:
            volume = call.data['volume']
            duration = call.data['duration']
            get_entity_from_domain(hass, DOMAIN, entity_id).siren_on(duration=duration, volume=volume)
            _LOGGER.info("{0} siren on {1}/{2}".format(entity_id, volume, duration))
        except HomeAssistantError:
            _LOGGER.warning("{0} is not an aarlo alarm device".format(entity_id)) 
Example #17
Source File: alarm_control_panel.py    From hass-aarlo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def async_alarm_siren_off_service(hass, call):
    for entity_id in call.data['entity_id']:
        try:
            get_entity_from_domain(hass, DOMAIN, entity_id).siren_off()
            _LOGGER.info("{0} siren off".format(entity_id))
        except HomeAssistantError:
            _LOGGER.warning("{0} is not an aarlo alarm device".format(entity_id)) 
Example #18
Source File: camera.py    From hass-aarlo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def async_camera_stop_activity_service(hass, call):
    for entity_id in call.data['entity_id']:
        try:
            _LOGGER.info("{} stop activity".format(entity_id))
            get_entity_from_domain(hass, DOMAIN, entity_id).stop_activity()
        except HomeAssistantError:
            _LOGGER.warning("{} stop activity service failed".format(entity_id)) 
Example #19
Source File: alarm_control_panel.py    From hass-aarlo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def websocket_siren_off(hass, connection, msg):
    base = _get_base_from_entity_id(hass, msg['entity_id'])
    _LOGGER.debug('stop_activity for ' + str(base.unique_id))

    await base.async_siren_off()
    connection.send_message(websocket_api.result_message(
        msg['id'], {
            'siren': 'off'
        }
    )) 
Example #20
Source File: camera.py    From hass-aarlo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def websocket_stream_url(hass, connection, msg):
    try:
        camera = get_entity_from_domain(hass, DOMAIN, msg['entity_id'])
        _LOGGER.debug('stream_url for ' + str(camera.unique_id))

        stream = await camera.async_stream_source()
        connection.send_message(websocket_api.result_message(
            msg['id'], {
                'url': stream
            }
        ))
    except HomeAssistantError as error:
        connection.send_message(websocket_api.error_message(
            msg['id'], 'stream_url_ws', "Unable to fetch stream ({})".format(str(error))))
        _LOGGER.warning("{} stream url websocket failed".format(msg['entity_id'])) 
Example #21
Source File: camera.py    From hass-aarlo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def websocket_library(hass, connection, msg):
    try:
        camera = get_entity_from_domain(hass, DOMAIN, msg['entity_id'])
        videos = []
        _LOGGER.debug('library+' + str(msg['at_most']))
        for v in camera.last_n_videos(msg['at_most']):
            videos.append({
                'created_at': v.created_at,
                'created_at_pretty': v.created_at_pretty(camera.last_capture_date_format),
                'url': v.video_url,
                'url_type': v.content_type,
                'thumbnail': v.thumbnail_url,
                'thumbnail_type': 'image/jpeg',
                'object': v.object_type,
                'object_region': v.object_region,
                'trigger': v.object_type,
                'trigger_region': v.object_region,
            })
        connection.send_message(websocket_api.result_message(
            msg['id'], {
                'videos': videos,
            }
        ))
    except HomeAssistantError as error:
        connection.send_message(websocket_api.error_message(
            msg['id'], 'library_ws', "Unable to fetch library ({})".format(str(error))))
        _LOGGER.warning("{} library websocket failed".format(msg['entity_id'])) 
Example #22
Source File: camera.py    From hass-aarlo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def websocket_siren_on(hass, connection, msg):
    try:
        camera = get_entity_from_domain(hass, DOMAIN, msg['entity_id'])
        _LOGGER.debug('stop_activity for ' + str(camera.unique_id))

        await camera.async_siren_on(duration=msg['duration'], volume=msg['volume'])
        connection.send_message(websocket_api.result_message(
            msg['id'], {
                'siren': 'on'
            }
        ))
    except HomeAssistantError as error:
        connection.send_message(websocket_api.error_message(
            msg['id'], 'siren_on_ws', "Unable to turn siren on ({})".format(str(error))))
        _LOGGER.warning("{} siren on websocket failed".format(msg['entity_id'])) 
Example #23
Source File: __init__.py    From common_timer with Apache License 2.0 5 votes vote down vote up
def cancel_task(self, entity_id):
        """ cancel task. """
        task = self._get_task(entity_id)
        if task is not None:
            self._queue.remove(task['handle'])
            task['handle'] = None
            task['remaining'] = '0:00:00'
            #reset frontend
            if self._entity_id == entity_id:
                self.set_state(self._ui[UI_SWITCH], state = 'off')
                self.set_state(self._ui[UI_INPUT_DURATION], state = task['duration'])
            self._hass.async_add_job(self.update_info)  # refresh info panel
        else:
            _LOGGER.info('cancel task of %s failure', entity_id) 
Example #24
Source File: __init__.py    From common_timer with Apache License 2.0 5 votes vote down vote up
def _get_running_tasks(self):
        """get running tasks order by exec_time"""
        tasks = [attrs for domain_entities in self._tasks.values() for entity_id, attrs in domain_entities.items() if attrs['handle'] is not None]
        return sorted(tasks, key=operator.itemgetter('exec_time')) 
Example #25
Source File: __init__.py    From common_timer with Apache License 2.0 5 votes vote down vote up
def stop_loop_task(self, entity_id, context):
        """ if entity operated by other method, stop loop task.
            according context to identify who changes state of entity.
        """
        info_config = self._info_config
        if info_config is None:
            return False

        #if entity in running tasks list
        if self._get_index_of_running_tasks(entity_id) is not None:
            task = self._get_task(entity_id)
            #if loop task and who operated
            if 'temporary' in task['operation'] and context.user_id != CONTEXT.user_id:
                _LOGGER.debug("operated by other method. <entity_id = %s, context = %s, common_timer context = %s>", entity_id, context, CONTEXT)
                #clear task info
                self._queue.remove(task['handle'])
                task['handle'] = None
                task['remaining'] = '0:00:00'
                #reset frontend
                if self._entity_id == entity_id:
                    self.set_state(self._ui[UI_SWITCH], state = 'off')
                    self.set_state(self._ui[UI_INPUT_DURATION], state = task['duration'])                
            else:
                _LOGGER.debug("operated by common_timer.py. <entity_id = %s, context = %s>", entity_id, context)
            return True
        return False 
Example #26
Source File: __init__.py    From common_timer with Apache License 2.0 5 votes vote down vote up
def _get_index_of_running_tasks(self, entity_id):
        """ return index of running_tasks. """
        if entity_id is None or self._running_tasks_ids is None:
            return None
        try:
            row = self._running_tasks_ids.index(entity_id)
            return row
        except ValueError:
            return None 
Example #27
Source File: __init__.py    From common_timer with Apache License 2.0 5 votes vote down vote up
def update(self, time):
        """ queue step forward and refresh timer display. 
            define callback to run in main thread.
        """
        self._queue.next()  # queue handler
        # refresh timer display when task is running
        if self.get_state(self._ui[UI_SWITCH]) == 'on':
            entity_id = self._entity_id
            if entity_id is None:
                _LOGGER.info("Function task: friendly_name(%s) not found in dic !", entity_id)
                return
            task = self._get_task(entity_id)
            remaining_time = self._queue.get_remaining_time(task['handle'])
            # task finish
            if remaining_time is None:
                remaining_time = task['remaining']
                if remaining_time == '0:00:00':
                    self.set_state(self._ui[UI_INPUT_DURATION], state = task['duration'])
                else:
                    self.set_state(self._ui[UI_INPUT_DURATION], state = str(remaining_time))
                self.set_state(self._ui[UI_SWITCH], state = 'off', context = CONTEXT_IGNORE)
            # task waite
            else:
                self.set_state(self._ui[UI_INPUT_DURATION], state = str(remaining_time))

    # @asyncio.coroutine 
Example #28
Source File: __init__.py    From common_timer with Apache License 2.0 5 votes vote down vote up
def set_options(self, entity_id, options, current_option = None, context = CONTEXT_IGNORE):
        """ set options for input select  """
        domain = entity_id.split('.')[0]
        if domain != 'input_select':
            _LOGGER.debug('wrong service')
            return
        data = {'entity_id': entity_id,'options': options}
        if current_option is not None:
            data['current_option'] = current_option
        self._hass.async_add_job(self._hass.services.async_call(domain, SERVICE_SET_OPTIONS, data , blocking = True, context = context)) # set blocking to wait till service is executed 
Example #29
Source File: __init__.py    From common_timer with Apache License 2.0 5 votes vote down vote up
def get_attributes(self, entity_id):
        """ return entity attributes. """
        state = self._hass.states.get(entity_id)
        if state:
            return state.as_dict().get('attributes',{})
        else:
            return None 
Example #30
Source File: __init__.py    From common_timer with Apache License 2.0 5 votes vote down vote up
def get_state(self, entity_id):
        """ return entity state. """
        state = self._hass.states.get(entity_id)
        if state:
            return state.as_dict()['state']
        else:
            return None