Example #1
0
    def post(self, request, entity_id):
        """Update state of entity."""
        try:
            data = yield from request.json()
        except ValueError:
            return self.json_message('Invalid JSON specified',
                                     HTTP_BAD_REQUEST)

        new_state = data.get('state')

        if not new_state:
            return self.json_message('No state specified', HTTP_BAD_REQUEST)

        attributes = data.get('attributes')
        force_update = data.get('force_update', False)

        is_new_state = self.hass.states.get(entity_id) is None

        # Write state
        self.hass.states.async_set(entity_id, new_state, attributes,
                                   force_update)

        # Read the state back for our response
        status_code = HTTP_CREATED if is_new_state else 200
        resp = self.json(self.hass.states.get(entity_id), status_code)

        resp.headers.add('Location', URL_API_STATES_ENTITY.format(entity_id))

        return resp
Example #2
0
def _handle_post_state_entity(handler, path_match, data):
    """Handle updating the state of an entity.

    This handles the following paths:
    /api/states/<entity_id>
    """
    entity_id = path_match.group('entity_id')

    try:
        new_state = data['state']
    except KeyError:
        handler.write_json_message("state not specified", HTTP_BAD_REQUEST)
        return

    attributes = data['attributes'] if 'attributes' in data else None

    is_new_state = handler.server.hass.states.get(entity_id) is None

    # Write state
    handler.server.hass.states.set(entity_id, new_state, attributes)

    state = handler.server.hass.states.get(entity_id)

    status_code = HTTP_CREATED if is_new_state else HTTP_OK

    handler.write_json(
        state.as_dict(),
        status_code=status_code,
        location=URL_API_STATES_ENTITY.format(entity_id))
Example #3
0
    def post(self, request, entity_id):
        """Update state of entity."""
        hass = request.app['hass']
        try:
            data = yield from request.json()
        except ValueError:
            return self.json_message('Invalid JSON specified',
                                     HTTP_BAD_REQUEST)

        new_state = data.get('state')

        if not new_state:
            return self.json_message('No state specified', HTTP_BAD_REQUEST)

        attributes = data.get('attributes')
        force_update = data.get('force_update', False)

        is_new_state = hass.states.get(entity_id) is None

        # Write state
        hass.states.async_set(entity_id, new_state, attributes, force_update)

        # Read the state back for our response
        status_code = HTTP_CREATED if is_new_state else 200
        resp = self.json(hass.states.get(entity_id), status_code)

        resp.headers.add('Location', URL_API_STATES_ENTITY.format(entity_id))

        return resp
Example #4
0
    async def post(self, request, entity_id):
        """Update state of entity."""
        hass = request.app['hass']
        try:
            data = await request.json()
        except ValueError:
            return self.json_message("Invalid JSON specified.",
                                     HTTP_BAD_REQUEST)

        new_state = data.get('state')

        if new_state is None:
            return self.json_message("No state specified.", HTTP_BAD_REQUEST)

        attributes = data.get('attributes')
        force_update = data.get('force_update', False)

        is_new_state = hass.states.get(entity_id) is None

        # Write state
        hass.states.async_set(entity_id, new_state, attributes, force_update,
                              self.context(request))

        # Read the state back for our response
        status_code = HTTP_CREATED if is_new_state else 200
        resp = self.json(hass.states.get(entity_id), status_code)

        resp.headers.add('Location', URL_API_STATES_ENTITY.format(entity_id))

        return resp
Example #5
0
def set_state(api, entity_id, new_state, attributes=None, force_update=False):
    """Tell API to update state for entity_id.

    Return True if success.
    """
    attributes = attributes or {}

    data = {
        'state': new_state,
        'attributes': attributes,
        'force_update': force_update
    }

    try:
        req = api(METHOD_POST, URL_API_STATES_ENTITY.format(entity_id), data)

        if req.status_code not in (200, 201):
            _LOGGER.error("Error changing state: %d - %s", req.status_code,
                          req.text)
            return False
        else:
            return True

    except HomeAssistantError:
        _LOGGER.exception("Error setting state")

        return False
Example #6
0
    async def post(self, request, entity_id):
        """Update state of entity."""
        if not request['hass_user'].is_admin:
            raise Unauthorized(entity_id=entity_id)
        hass = request.app['hass']
        try:
            data = await request.json()
        except ValueError:
            return self.json_message(
                "Invalid JSON specified.", HTTP_BAD_REQUEST)

        new_state = data.get('state')

        if new_state is None:
            return self.json_message("No state specified.", HTTP_BAD_REQUEST)

        attributes = data.get('attributes')
        force_update = data.get('force_update', False)

        is_new_state = hass.states.get(entity_id) is None

        # Write state
        hass.states.async_set(entity_id, new_state, attributes, force_update,
                              self.context(request))

        # Read the state back for our response
        status_code = HTTP_CREATED if is_new_state else 200
        resp = self.json(hass.states.get(entity_id), status_code)

        resp.headers.add('Location', URL_API_STATES_ENTITY.format(entity_id))

        return resp
Example #7
0
def set_state(api: API, entity_id: str, new_state: str,
              attributes: Dict = None, force_update: bool = False) -> bool:
    """Tell API to update state for entity_id.

    Return True if success.
    """
    attributes = attributes or {}

    data = {'state': new_state,
            'attributes': attributes,
            'force_update': force_update}

    try:
        req = api(METH_POST, URL_API_STATES_ENTITY.format(entity_id), data)

        if req.status_code not in (200, 201):
            _LOGGER.error("Error changing state: %d - %s",
                          req.status_code, req.text)
            return False

        return True

    except HomeAssistantError:
        _LOGGER.exception("Error setting state")

        return False
Example #8
0
def set_state(api, entity_id, new_state, attributes=None):
    """
    Tells API to update state for entity_id.
    Returns True if success.
    """

    attributes = attributes or {}

    data = {'state': new_state,
            'attributes': attributes}

    try:
        req = api(METHOD_POST,
                  URL_API_STATES_ENTITY.format(entity_id),
                  data)

        if req.status_code not in (200, 201):
            _LOGGER.error("Error changing state: %d - %s",
                          req.status_code, req.text)
            return False
        else:
            return True

    except ha.HomeAssistantError:
        _LOGGER.exception("Error setting state")

        return False
Example #9
0
    async def post(self, request, entity_id):
        """Update state of entity."""
        if not request["hass_user"].is_admin:
            raise Unauthorized(entity_id=entity_id)
        hass = request.app["hass"]
        try:
            data = await request.json()
        except ValueError:
            return self.json_message("Invalid JSON specified.", HTTP_BAD_REQUEST)

        new_state = data.get("state")

        if new_state is None:
            return self.json_message("No state specified.", HTTP_BAD_REQUEST)

        attributes = data.get("attributes")
        force_update = data.get("force_update", False)

        is_new_state = hass.states.get(entity_id) is None

        # Write state
        hass.states.async_set(
            entity_id, new_state, attributes, force_update, self.context(request)
        )

        # Read the state back for our response
        status_code = HTTP_CREATED if is_new_state else 200
        resp = self.json(hass.states.get(entity_id), status_code)

        resp.headers.add("Location", URL_API_STATES_ENTITY.format(entity_id))

        return resp
Example #10
0
def get_state(api, entity_id):
    """Query given API for state of entity_id."""
    try:
        req = api(METHOD_GET, URL_API_STATES_ENTITY.format(entity_id))

        # req.status_code == 422 if entity does not exist

        return ha.State.from_dict(req.json()) if req.status_code == 200 else None

    except (HomeAssistantError, ValueError):
        # ValueError if req.json() can't parse the json
        _LOGGER.exception("Error fetching state")

        return None
Example #11
0
def get_state(api, entity_id):
    """Query given API for state of entity_id."""
    try:
        req = api(METHOD_GET, URL_API_STATES_ENTITY.format(entity_id))

        # req.status_code == 422 if entity does not exist

        return ha.State.from_dict(req.json()) \
            if req.status_code == 200 else None

    except (HomeAssistantError, ValueError):
        # ValueError if req.json() can't parse the json
        _LOGGER.exception("Error fetching state")

        return None
Example #12
0
def remove_state(api, entity_id):
    """Call API to remove state for entity_id.

    Return True if entity is gone (removed/never existed).
    """
    try:
        req = api(METHOD_DELETE, URL_API_STATES_ENTITY.format(entity_id))

        if req.status_code in (200, 404):
            return True

        _LOGGER.error("Error removing state: %d - %s", req.status_code, req.text)
        return False
    except HomeAssistantError:
        _LOGGER.exception("Error removing state")

        return False
Example #13
0
def remove_state(api, entity_id):
    """Call API to remove state for entity_id.

    Return True if entity is gone (removed/never existed).
    """
    try:
        req = api(METHOD_DELETE, URL_API_STATES_ENTITY.format(entity_id))

        if req.status_code in (200, 404):
            return True

        _LOGGER.error("Error removing state: %d - %s", req.status_code,
                      req.text)
        return False
    except HomeAssistantError:
        _LOGGER.exception("Error removing state")

        return False
Example #14
0
    def post(self, request, entity_id):
        """Update state of entity."""
        try:
            new_state = request.json['state']
        except KeyError:
            return self.json_message('No state specified', HTTP_BAD_REQUEST)

        attributes = request.json.get('attributes')

        is_new_state = self.hass.states.get(entity_id) is None

        # Write state
        self.hass.states.set(entity_id, new_state, attributes)

        # Read the state back for our response
        resp = self.json(self.hass.states.get(entity_id))

        if is_new_state:
            resp.status_code = HTTP_CREATED

        resp.headers.add('Location', URL_API_STATES_ENTITY.format(entity_id))

        return resp
Example #15
0
    def post(self, request, entity_id):
        """Update state of entity."""
        try:
            new_state = request.json['state']
        except KeyError:
            return self.json_message('No state specified', HTTP_BAD_REQUEST)

        attributes = request.json.get('attributes')

        is_new_state = self.hass.states.get(entity_id) is None

        # Write state
        self.hass.states.set(entity_id, new_state, attributes)

        # Read the state back for our response
        resp = self.json(self.hass.states.get(entity_id))

        if is_new_state:
            resp.status_code = HTTP_CREATED

        resp.headers.add('Location', URL_API_STATES_ENTITY.format(entity_id))

        return resp