Exemplo n.º 1
0
def get_states(ctx: Configuration) -> List[Dict[str, Any]]:
    """Return all states."""
    try:
        req = restapi(ctx, METH_GET, hass.URL_API_STATES)
    except HomeAssistantCliError as ex:
        raise HomeAssistantCliError(
            "Unexpected error getting state: {}".format(ex))

    if req.status_code == 200:
        data = req.json()  # type: List[Dict[str, Any]]
        return data

    raise HomeAssistantCliError("Error while getting all states: {}".format(
        req.text))
Exemplo n.º 2
0
def get_services(ctx: Configuration,) -> List[Dict[str, Any]]:
    """Get list of services."""
    try:
        req = restapi(ctx, METH_GET, hass.URL_API_SERVICES)
    except HomeAssistantCliError as ex:
        raise HomeAssistantCliError(
            "Unexpected error getting services: {}".format(ex)
        )

    if req.status_code == 200:
        return cast(List[Dict[str, Any]], req.json())

    raise HomeAssistantCliError(
        "Error while getting all services: {}".format(req.text)
    )
Exemplo n.º 3
0
def get_config(ctx: Configuration) -> Dict[str, Any]:
    """Return the running configuration."""
    try:
        req = restapi(ctx, METH_GET, hass.URL_API_CONFIG)
    except HomeAssistantCliError as ex:
        raise HomeAssistantCliError(
            "Unexpected error getting configuration: {}".format(ex)
        )

    if req.status_code == 200:
        return cast(Dict[str, str], req.json())

    raise HomeAssistantCliError(
        "Error while getting all configuration: {}".format(req.text)
    )
Exemplo n.º 4
0
def get_events(ctx: Configuration) -> Dict[str, Any]:
    """Return all events."""
    try:
        req = restapi(ctx, METH_GET, hass.URL_API_EVENTS)
    except HomeAssistantCliError as ex:
        raise HomeAssistantCliError(
            "Unexpected error getting events: {}".format(ex)
        )

    if req.status_code == 200:
        return cast(Dict[str, Any], req.json())

    raise HomeAssistantCliError(
        "Error while getting all events: {}".format(req.text)
    )
Exemplo n.º 5
0
def render_template(ctx: Configuration, template: str, variables: Dict) -> str:
    """Render template."""
    data = {"template": template, "variables": variables}

    try:
        req = restapi(ctx, METH_POST, hass.URL_API_TEMPLATE, data)
    except HomeAssistantCliError as exception:
        raise HomeAssistantCliError(
            "Error applying template: {}".format(exception))

    if req.status_code not in (200, 201):
        raise HomeAssistantCliError("Error applying template: {} - {}".format(
            req.status_code, req.text))
    else:
        return req.text
Exemplo n.º 6
0
    async def fetcher() -> Optional[Dict]:
        async with aiohttp.ClientSession() as session:
            async with session.ws_connect(
                resolve_server(ctx) + "/api/websocket"
            ) as wsconn:

                await wsconn.send_str(
                    json.dumps({'type': 'auth', 'access_token': ctx.token})
                )

                frame['id'] = 1

                await wsconn.send_str(json.dumps(frame))

                while True:
                    msg = await wsconn.receive()
                    if msg.type == aiohttp.WSMsgType.ERROR:
                        break
                    elif msg.type == aiohttp.WSMsgType.CLOSED:
                        break
                    elif msg.type == aiohttp.WSMsgType.TEXT:
                        mydata = json.loads(msg.data)  # type: Dict

                        if callback:
                            callback(mydata)
                        elif mydata['type'] == 'result':
                            return mydata
                        elif mydata['type'] == 'auth_invalid':
                            raise HomeAssistantCliError(mydata.get('message'))
        return None
Exemplo n.º 7
0
def set_state(ctx: Configuration, entity_id: str,
              data: Dict) -> Dict[str, Any]:
    """Set/update state for entity id."""
    try:
        req = restapi(ctx, METH_POST,
                      hass.URL_API_STATES_ENTITY.format(entity_id), data)
    except HomeAssistantCliError as exception:
        raise HomeAssistantCliError(
            "Error updating state for entity {}: {}".format(
                entity_id, exception))

    if req.status_code not in (200, 201):
        raise HomeAssistantCliError(
            "Error changing state for entity {}: {} - {}".format(
                entity_id, req.status_code, req.text))
    return cast(Dict[str, Any], req.json())
Exemplo n.º 8
0
def restapi(ctx: Configuration,
            method: str,
            path: str,
            data: Optional[Dict] = None) -> requests.Response:
    """Make a call to the Home Assistant REST API."""
    if data is None:
        data_str = None
    else:
        data_str = json.dumps(data, cls=JSONEncoder)

    if not ctx.session:
        ctx.session = requests.Session()
        ctx.session.verify = not ctx.insecure
        if ctx.cert:
            ctx.session.cert = ctx.cert

        _LOGGER.debug(
            "Session: verify(%s), cert(%s)",
            ctx.session.verify,
            ctx.session.cert,
        )

    headers = {CONTENT_TYPE: hass.CONTENT_TYPE_JSON}  # type: Dict[str, Any]

    if ctx.token:
        headers["Authorization"] = "Bearer {}".format(ctx.token)
    if ctx.password:
        headers["x-ha-access"] = ctx.password

    url = urllib.parse.urljoin(resolve_server(ctx) + path, "")

    try:
        if method == METH_GET:
            return requests.get(url, params=data_str, headers=headers)

        return requests.request(method, url, data=data_str, headers=headers)

    except requests.exceptions.ConnectionError:
        raise HomeAssistantCliError("Error connecting to {}".format(url))

    except requests.exceptions.Timeout:
        error = "Timeout when talking to {}".format(url)
        _LOGGER.exception(error)
        raise HomeAssistantCliError(error)
Exemplo n.º 9
0
 def _msghandler(msg: Dict) -> None:
     if msg['type'] == 'event':
         ctx.echo(
             format_output(
                 ctx,
                 msg['event'],
                 columns=ctx.columns if ctx.columns else cols,
             ))
     elif msg['type'] == 'auth_invalid':
         raise HomeAssistantCliError(msg.get('message'))
Exemplo n.º 10
0
def remove_state(ctx: Configuration, entity_id: str) -> bool:
    """Call API to remove state for entity_id.

    If success return True, if could not find the entity return False.
    Otherwise raise exception with details.
    """
    try:
        req = restapi(ctx, METH_DELETE,
                      hass.URL_API_STATES_ENTITY.format(entity_id))

        if req.status_code == 200:
            return True
        if req.status_code == 404:
            return False
    except HomeAssistantCliError:
        raise HomeAssistantCliError("Unexpected error removing state")

    raise HomeAssistantCliError("Error removing state: {} - {}".format(
        req.status_code, req.text))
Exemplo n.º 11
0
def get_raw_error_log(ctx: Configuration) -> str:
    """Return the error log."""
    try:
        req = restapi(ctx, METH_GET, hass.URL_API_ERROR_LOG)
        req.raise_for_status()
    except HomeAssistantCliError as ex:
        raise HomeAssistantCliError(
            "Unexpected error getting error log: {}".format(ex))

    return req.text
Exemplo n.º 12
0
def get_state(ctx: Configuration, entity_id: str) -> Optional[Dict[str, Any]]:
    """Get entity state. If ok, return dictionary with state.

    If no entity found return None - otherwise excepton raised
    with details.
    """
    try:
        req = restapi(ctx, METH_GET,
                      hass.URL_API_STATES_ENTITY.format(entity_id))
    except HomeAssistantCliError as ex:
        raise HomeAssistantCliError(
            "Unexpected error getting state: {}".format(ex))

    if req.status_code == 200:
        return cast(Dict[str, Any], req.json())
    if req.status_code == 404:
        return None

    raise HomeAssistantCliError("Error while getting Entity {}: {}".format(
        entity_id, req.text))
Exemplo n.º 13
0
def get_info(ctx: Configuration) -> Dict[str, Any]:
    """Get basic info about the Home Assistant instance."""
    try:
        req = restapi(ctx, METH_GET, hass.URL_API_DISCOVERY_INFO)

        req.raise_for_status()

        return (cast(Dict[str,
                          Any], req.json()) if req.status_code == 200 else {})

    except (HomeAssistantCliError, ValueError):
        raise HomeAssistantCliError("Unexpected error retrieving information")
Exemplo n.º 14
0
def call_service(
    ctx: Configuration,
    domain: str,
    service: str,
    service_data: Optional[Dict] = None,
) -> List[Dict[str, Any]]:
    """Call a service."""
    try:
        req = restapi(
            ctx,
            METH_POST,
            hass.URL_API_SERVICES_SERVICE.format(domain, service),
            service_data,
        )
    except HomeAssistantCliError as ex:
        raise HomeAssistantCliError("Error calling service: {}".format(ex))

    if req.status_code != 200:
        raise HomeAssistantCliError("Error calling service: {} - {}".format(
            req.status_code, req.text))

    return cast(List[Dict[str, Any]], req.json())
Exemplo n.º 15
0
def fire_event(
        ctx: Configuration,
        event_type: str,
        data: Optional[Dict[str, Any]] = None) -> Optional[Dict[str, Any]]:
    """Fire an event at remote API."""
    try:
        req = restapi(ctx, METH_POST,
                      hass.URL_API_EVENTS_EVENT.format(event_type), data)

        if req.status_code != 200:
            _LOGGER.error("Error firing event: %d - %s", req.status_code,
                          req.text)

        return cast(Dict[str, Any], req.json())

    except HomeAssistantCliError as exception:
        raise HomeAssistantCliError("Error firing event: {}".format(exception))