Python homeassistant.exceptions.HomeAssistantError() Examples

The following are 30 code examples of homeassistant.exceptions.HomeAssistantError(). 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.exceptions , or try the search function .
Example #1
Source File: camera.py    From hass-config with GNU General Public License v3.0 6 votes vote down vote up
def websocket_video_data(hass, connection, msg):
    camera = _get_camera_from_entity_id(hass, msg['entity_id'])
    _LOGGER.debug('video_data for ' + str(camera.unique_id))

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

    except HomeAssistantError:
        connection.send_message(websocket_api.error_message(
            msg['id'], 'video_fetch_failed', 'Unable to fetch video')) 
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_data(hass, connection, msg):
    try:
        camera = get_entity_from_domain(hass, DOMAIN, msg['entity_id'])
        _LOGGER.debug('video_data for ' + str(camera.unique_id))

        video = await camera.async_get_video()
        connection.send_message(websocket_api.result_message(
            msg['id'], {
                'content_type': 'video/mp4',
                'content': base64.b64encode(video).decode('utf-8')
            }
        ))
    except HomeAssistantError as error:
        connection.send_message(websocket_api.error_message(
            msg['id'], 'video_data_ws', "Unable to get video data ({})".format(str(error))))
        _LOGGER.warning("{} video data websocket failed".format(msg['entity_id'])) 
Example #3
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 #4
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 #5
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 #6
Source File: __init__.py    From spotcast with Apache License 2.0 6 votes vote down vote up
def __init__(self, hass, call_device_name, call_entity_id):
        """Initialize a spotify cast device."""
        self.hass = hass

        # Get device name from either device_name or entity_id
        device_name = None
        if call_device_name is None:
            entity_id = call_entity_id
            if entity_id is None:
                raise HomeAssistantError("Either entity_id or device_name must be specified")
            entity_states = hass.states.get(entity_id)
            if entity_states is None:
                _LOGGER.error("Could not find entity_id: %s", entity_id)
            else:
                device_name = entity_states.attributes.get("friendly_name")
        else:
            device_name = call_device_name

        if device_name is None or device_name.strip() == "":
            raise HomeAssistantError("device_name is empty")

        # Find chromecast device
        self.castDevice = self.getChromecastDevice(device_name)
        _LOGGER.debug("Found cast device: %s", self.castDevice)
        self.castDevice.wait() 
Example #7
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 #8
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 #9
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 #10
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 #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 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 #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_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 #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_video_to_file_service(hass, call):
    for entity_id in call.data['entity_id']:
        try:
            camera = get_entity_from_domain(hass, DOMAIN, entity_id)
            filename = call.data[ATTR_FILENAME]
            filename.hass = hass
            video_file = filename.async_render(variables={ATTR_ENTITY_ID: camera})
            _LOGGER.info("{} video to file {}".format(entity_id, filename))

            # check if we allow to access to that file
            if not hass.config.is_allowed_path(video_file):
                _LOGGER.error("Can't write %s, no access to path!", video_file)
                return

            image = await camera.async_get_video()

            def _write_image(to_file, image_data):
                with open(to_file, 'wb') as img_file:
                    img_file.write(image_data)

            await hass.async_add_executor_job(_write_image, video_file, image)
            hass.bus.fire('aarlo_video_ready', {
                'entity_id': entity_id,
                'file': video_file
            })
        except OSError as err:
            _LOGGER.error("Can't write image to file: %s", err)
        except HomeAssistantError:
            _LOGGER.warning("{} video to file service failed".format(entity_id))
        _LOGGER.debug("{0} video to file finished".format(entity_id)) 
Example #14
Source File: camera.py    From hass-aarlo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def async_camera_snapshot_to_file_service(hass, call):
    for entity_id in call.data['entity_id']:
        try:
            camera = get_entity_from_domain(hass, DOMAIN, entity_id)
            filename = call.data[ATTR_FILENAME]
            filename.hass = hass
            snapshot_file = filename.async_render(variables={ATTR_ENTITY_ID: camera})
            _LOGGER.info("{} snapshot(filename={})".format(entity_id, filename))

            # check if we allow to access to that file
            if not hass.config.is_allowed_path(snapshot_file):
                _LOGGER.error("Can't write %s, no access to path!", snapshot_file)
                return

            image = await camera.async_get_snapshot()

            def _write_image(to_file, image_data):
                with open(to_file, 'wb') as img_file:
                    img_file.write(image_data)

            await hass.async_add_executor_job(_write_image, snapshot_file, image)
            hass.bus.fire('aarlo_snapshot_ready', {
                'entity_id': entity_id,
                'file': snapshot_file
            })
        except OSError as err:
            _LOGGER.error("Can't write image to file: %s", err)
        except HomeAssistantError:
            _LOGGER.warning("{} snapshot to file service failed".format(entity_id)) 
Example #15
Source File: camera.py    From hass-aarlo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def async_camera_snapshot_service(hass, call):
    for entity_id in call.data['entity_id']:
        try:
            _LOGGER.info("{} snapshot".format(entity_id))
            camera = get_entity_from_domain(hass, DOMAIN, entity_id)
            await camera.async_get_snapshot()
            hass.bus.fire('aarlo_snapshot_ready', {
                'entity_id': entity_id,
            })
        except HomeAssistantError:
            _LOGGER.warning("{} snapshot service failed".format(entity_id)) 
Example #16
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 #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_mode_service(hass, call):
    for entity_id in call.data['entity_id']:
        try:
            mode = call.data['mode']
            get_entity_from_domain(hass, DOMAIN, entity_id).set_mode_in_ha(mode)
            _LOGGER.info("{0} setting mode to {1}".format(entity_id, mode))
        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 websocket_stop_activity(hass, connection, msg):
    try:
        camera = get_entity_from_domain(hass, DOMAIN, msg['entity_id'])
        _LOGGER.debug('stop_activity for ' + str(camera.unique_id))

        stopped = await camera.async_stop_activity()
        connection.send_message(websocket_api.result_message(
            msg['id'], {
                'stopped': stopped
            }
        ))
    except HomeAssistantError as error:
        connection.send_message(websocket_api.error_message(
            msg['id'], 'stop_activity_ws', "Unable to stop activity ({})".format(str(error))))
        _LOGGER.warning("{} stop activity websocket failed".format(msg['entity_id'])) 
Example #19
Source File: __init__.py    From spotcast with Apache License 2.0 5 votes vote down vote up
def get_spotify_token(self):
        import spotify_token as st
        try:
            self._access_token, self._token_expires = st.start_session(self.sp_dc, self.sp_key)
            expires = self._token_expires - int(time.time())
            return self._access_token, expires
        except:
            raise HomeAssistantError("Could not get spotify token") 
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_request_snapshot(hass, connection, msg):
    try:
        camera = get_entity_from_domain(hass, DOMAIN, msg['entity_id'])
        _LOGGER.debug('request_snapshot_image for ' + str(camera.unique_id))

        await camera.async_request_snapshot()
        connection.send_message(websocket_api.result_message(
            msg['id'], {
                'snapshot requested'
            }
        ))
    except HomeAssistantError as error:
        connection.send_message(websocket_api.error_message(
            msg['id'], 'requst_snapshot_ws', "Unable to request snapshot ({})".format(str(error))))
        _LOGGER.warning("{} snapshot request 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: __init__.py    From hass-aarlo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def async_aarlo_siren_off(hass, call):
    for entity_id in call.data['entity_id']:
        try:
            device = get_entity_from_domain(hass, [ALARM_DOMAIN, CAMERA_DOMAIN], entity_id)
            device.siren_off()
            _LOGGER.info("{} siren off".format(entity_id))
        except HomeAssistantError:
            _LOGGER.info("{} siren not found".format(entity_id)) 
Example #23
Source File: __init__.py    From hass-aarlo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def async_aarlo_siren_on(hass, call):
    for entity_id in call.data['entity_id']:
        try:
            volume = call.data['volume']
            duration = call.data['duration']
            device = get_entity_from_domain(hass, [ALARM_DOMAIN, CAMERA_DOMAIN], entity_id)
            device.siren_on(duration=duration, volume=volume)
            _LOGGER.info("{} siren on {}/{}".format(entity_id, volume, duration))
        except HomeAssistantError:
            _LOGGER.info("{} siren device not found".format(entity_id)) 
Example #24
Source File: __init__.py    From hass-aarlo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_entity_from_domain(hass, domains, entity_id):
    domains = domains if isinstance(domains, list) else [domains]
    for domain in domains:
        component = hass.data.get(domain)
        if component is None:
            raise HomeAssistantError("{} component not set up".format(domain))
        entity = component.get_entity(entity_id)
        if entity is not None:
            return entity
    raise HomeAssistantError("{} not found in {}".format(entity_id, ",".join(domains))) 
Example #25
Source File: alarm_control_panel.py    From hass-config with GNU 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 #26
Source File: camera.py    From hass-config with GNU General Public License v3.0 5 votes vote down vote up
def websocket_stream_url(hass, connection, msg):
    camera = _get_camera_from_entity_id(hass, msg['entity_id'])
    _LOGGER.debug('stream_url for ' + str(camera.unique_id))
    try:
        stream = await camera.async_stream_source()
        connection.send_message(websocket_api.result_message(
            msg['id'], {
                'url': stream
            }
        ))

    except HomeAssistantError:
        connection.send_message(websocket_api.error_message(
            msg['id'], 'image_fetch_failed', 'Unable to fetch stream')) 
Example #27
Source File: camera.py    From hass-config with GNU General Public License v3.0 5 votes vote down vote up
def _get_camera_from_entity_id(hass, entity_id):
    component = hass.data.get(DOMAIN)
    if component is None:
        raise HomeAssistantError('Camera component not set up')

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

    return camera 
Example #28
Source File: __init__.py    From HomeAssistant_Components with Apache License 2.0 5 votes vote down vote up
def _load_json(filename):
    """Wrapper, because we actually want to handle invalid json."""
    try:
        return load_json(filename)
    except HomeAssistantError:
        pass
    return {} 
Example #29
Source File: __init__.py    From spotcast with Apache License 2.0 5 votes vote down vote up
def getSpotifyDeviceId(self, client):
        # Look for device
        devices_available = client.devices()
        for device in devices_available["devices"]:
            if device["id"] == self.spotifyController.device:
                return device["id"]


        _LOGGER.error(
            'No device with id "{}" known by Spotify'.format(self.spotifyController.device)
        )
        _LOGGER.error("Known devices: {}".format(devices_available["devices"]))
        raise HomeAssistantError("Failed to get device id from Spotify") 
Example #30
Source File: __init__.py    From spotcast with Apache License 2.0 5 votes vote down vote up
def startSpotifyController(self, access_token, expires):
        from pychromecast.controllers.spotify import SpotifyController

        sp = SpotifyController(access_token, expires)
        self.castDevice.register_handler(sp)
        sp.launch_app()

        if not sp.is_launched and not sp.credential_error:
            raise HomeAssistantError("Failed to launch spotify controller due to timeout")
        if not sp.is_launched and sp.credential_error:
            raise HomeAssistantError("Failed to launch spotify controller due to credentials error")

        self.spotifyController = sp