Search in sources :

Example 1 with HydrawiseConnectionException

use of org.openhab.binding.hydrawise.internal.api.HydrawiseConnectionException in project openhab-addons by openhab.

the class HydrawiseGraphQLClient method sendGraphQLRequest.

private String sendGraphQLRequest(String content) throws HydrawiseConnectionException, HydrawiseAuthenticationException {
    logger.trace("Sending Request: {}", content);
    ContentResponse response;
    final AtomicInteger responseCode = new AtomicInteger(0);
    final StringBuilder responseMessage = new StringBuilder();
    try {
        AccessTokenResponse token = oAuthService.getAccessTokenResponse();
        if (token == null) {
            throw new HydrawiseAuthenticationException("Login required");
        }
        response = httpClient.newRequest(GRAPH_URL).method(HttpMethod.POST).content(new StringContentProvider(content), "application/json").header("Authorization", token.getTokenType() + " " + token.getAccessToken()).onResponseFailure(new Response.FailureListener() {

            @Override
            public void onFailure(@Nullable Response response, @Nullable Throwable failure) {
                int status = response != null ? response.getStatus() : -1;
                String reason = response != null ? response.getReason() : "Null response";
                logger.trace("onFailure code: {} message: {}", status, reason);
                responseCode.set(status);
                responseMessage.append(reason);
            }
        }).send();
        String stringResponse = response.getContentAsString();
        logger.trace("Received Response: {}", stringResponse);
        return stringResponse;
    } catch (InterruptedException | TimeoutException | OAuthException | IOException e) {
        logger.debug("Could not send request", e);
        throw new HydrawiseConnectionException(e);
    } catch (OAuthResponseException e) {
        throw new HydrawiseAuthenticationException(e.getMessage());
    } catch (ExecutionException e) {
        // this allows us to catch this in a callback and handle accordingly
        switch(responseCode.get()) {
            case 401:
            case 403:
                throw new HydrawiseAuthenticationException(responseMessage.toString());
            default:
                throw new HydrawiseConnectionException(e);
        }
    }
}
Also used : OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) IOException(java.io.IOException) MutationResponse(org.openhab.binding.hydrawise.internal.api.graphql.dto.MutationResponse) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) QueryResponse(org.openhab.binding.hydrawise.internal.api.graphql.dto.QueryResponse) HydrawiseConnectionException(org.openhab.binding.hydrawise.internal.api.HydrawiseConnectionException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HydrawiseAuthenticationException(org.openhab.binding.hydrawise.internal.api.HydrawiseAuthenticationException) ExecutionException(java.util.concurrent.ExecutionException) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) TimeoutException(java.util.concurrent.TimeoutException)

Example 2 with HydrawiseConnectionException

use of org.openhab.binding.hydrawise.internal.api.HydrawiseConnectionException in project openhab-addons by openhab.

the class HydrawiseGraphQLClient method queryControllers.

/**
 * Sends a GrapQL query for controller data
 *
 * @return QueryResponse
 * @throws HydrawiseConnectionException
 * @throws HydrawiseAuthenticationException
 */
@Nullable
public QueryResponse queryControllers() throws HydrawiseConnectionException, HydrawiseAuthenticationException {
    QueryRequest query;
    try {
        query = new QueryRequest(getQueryString());
    } catch (IOException e) {
        throw new HydrawiseConnectionException(e);
    }
    String queryJson = gson.toJson(query);
    String response = sendGraphQLQuery(queryJson);
    return gson.fromJson(response, QueryResponse.class);
}
Also used : QueryRequest(org.openhab.binding.hydrawise.internal.api.graphql.dto.QueryRequest) HydrawiseConnectionException(org.openhab.binding.hydrawise.internal.api.HydrawiseConnectionException) IOException(java.io.IOException) Nullable(org.eclipse.jdt.annotation.Nullable)

Example 3 with HydrawiseConnectionException

use of org.openhab.binding.hydrawise.internal.api.HydrawiseConnectionException in project openhab-addons by openhab.

the class HydrawiseAccountHandler method poll.

private void poll(boolean retry) {
    try {
        QueryResponse response = apiClient.queryControllers();
        if (response == null) {
            throw new HydrawiseConnectionException("Malformed response");
        }
        if (response.errors != null && response.errors.size() > 0) {
            throw new HydrawiseConnectionException(response.errors.stream().map(error -> error.message).reduce("", (messages, message) -> messages + message + ". "));
        }
        if (getThing().getStatus() != ThingStatus.ONLINE) {
            updateStatus(ThingStatus.ONLINE);
        }
        lastData = response.data.me;
        controllerListeners.forEach(listener -> {
            listener.onData(response.data.me.controllers);
        });
    } catch (HydrawiseConnectionException e) {
        if (retry) {
            logger.debug("Retrying failed poll", e);
            poll(false);
        } else {
            logger.debug("Will try again during next poll period", e);
            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
        }
    } catch (HydrawiseAuthenticationException e) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
        clearPolling();
    }
}
Also used : ScheduledFuture(java.util.concurrent.ScheduledFuture) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) LoggerFactory(org.slf4j.LoggerFactory) ThingHandlerService(org.openhab.core.thing.binding.ThingHandlerService) HydrawiseCloudControllerDiscoveryService(org.openhab.binding.hydrawise.internal.discovery.HydrawiseCloudControllerDiscoveryService) ArrayList(java.util.ArrayList) HttpClient(org.eclipse.jetty.client.HttpClient) AccessTokenRefreshListener(org.openhab.core.auth.client.oauth2.AccessTokenRefreshListener) Nullable(org.eclipse.jdt.annotation.Nullable) Configuration(org.openhab.core.config.core.Configuration) ChannelUID(org.openhab.core.thing.ChannelUID) HydrawiseConnectionException(org.openhab.binding.hydrawise.internal.api.HydrawiseConnectionException) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) ThingStatus(org.openhab.core.thing.ThingStatus) Command(org.openhab.core.types.Command) Logger(org.slf4j.Logger) OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) Collection(java.util.Collection) IOException(java.io.IOException) HydrawiseControllerListener(org.openhab.binding.hydrawise.internal.HydrawiseControllerListener) ThingStatusDetail(org.openhab.core.thing.ThingStatusDetail) HydrawiseAuthenticationException(org.openhab.binding.hydrawise.internal.api.HydrawiseAuthenticationException) TimeUnit(java.util.concurrent.TimeUnit) HydrawiseAccountConfiguration(org.openhab.binding.hydrawise.internal.config.HydrawiseAccountConfiguration) List(java.util.List) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) OAuthClientService(org.openhab.core.auth.client.oauth2.OAuthClientService) OAuthFactory(org.openhab.core.auth.client.oauth2.OAuthFactory) BaseBridgeHandler(org.openhab.core.thing.binding.BaseBridgeHandler) QueryResponse(org.openhab.binding.hydrawise.internal.api.graphql.dto.QueryResponse) Collections(java.util.Collections) Customer(org.openhab.binding.hydrawise.internal.api.graphql.dto.Customer) HydrawiseGraphQLClient(org.openhab.binding.hydrawise.internal.api.graphql.HydrawiseGraphQLClient) Bridge(org.openhab.core.thing.Bridge) HydrawiseConnectionException(org.openhab.binding.hydrawise.internal.api.HydrawiseConnectionException) HydrawiseAuthenticationException(org.openhab.binding.hydrawise.internal.api.HydrawiseAuthenticationException) QueryResponse(org.openhab.binding.hydrawise.internal.api.graphql.dto.QueryResponse)

Example 4 with HydrawiseConnectionException

use of org.openhab.binding.hydrawise.internal.api.HydrawiseConnectionException in project openhab-addons by openhab.

the class HydrawiseControllerHandler method handleCommand.

@Override
public void handleCommand(ChannelUID channelUID, Command command) {
    logger.debug("handleCommand channel {} Command {}", channelUID.getAsString(), command.toFullString());
    if (getThing().getStatus() != ThingStatus.ONLINE) {
        logger.debug("Controller is NOT ONLINE and is not responding to commands");
        return;
    }
    // remove our cached state for this, will be safely updated on next poll
    stateMap.remove(channelUID.getAsString());
    if (command instanceof RefreshType) {
        // we already removed this from the cache
        return;
    }
    HydrawiseGraphQLClient client = apiClient();
    if (client == null) {
        logger.debug("API client not found");
        return;
    }
    String group = channelUID.getGroupId();
    String channelId = channelUID.getIdWithoutGroup();
    boolean allCommand = CHANNEL_GROUP_ALLZONES.equals(group);
    Zone zone = zoneMaps.get(group);
    if (!allCommand && zone == null) {
        logger.debug("Zone not found {}", group);
        return;
    }
    try {
        switch(channelId) {
            case CHANNEL_ZONE_RUN_CUSTOM:
                if (!(command instanceof QuantityType<?>)) {
                    logger.warn("Invalid command type for run custom {}", command.getClass().getName());
                    return;
                }
                QuantityType<?> time = ((QuantityType<?>) command).toUnit(Units.SECOND);
                if (time == null) {
                    return;
                }
                if (allCommand) {
                    client.runAllRelays(controllerId, time.intValue());
                } else if (zone != null) {
                    client.runRelay(zone.id, time.intValue());
                }
                break;
            case CHANNEL_ZONE_RUN:
                if (!(command instanceof OnOffType)) {
                    logger.warn("Invalid command type for run {}", command.getClass().getName());
                    return;
                }
                if (allCommand) {
                    if (command == OnOffType.ON) {
                        client.runAllRelays(controllerId);
                    } else {
                        client.stopAllRelays(controllerId);
                    }
                } else if (zone != null) {
                    if (command == OnOffType.ON) {
                        client.runRelay(zone.id);
                    } else {
                        client.stopRelay(zone.id);
                    }
                }
                break;
            case CHANNEL_ZONE_SUSPEND:
                if (!(command instanceof OnOffType)) {
                    logger.warn("Invalid command type for suspend {}", command.getClass().getName());
                    return;
                }
                if (allCommand) {
                    if (command == OnOffType.ON) {
                        client.suspendAllRelays(controllerId, OffsetDateTime.now(ZoneOffset.UTC).plus(DEFAULT_SUSPEND_TIME_HOURS, ChronoUnit.HOURS).format(DATE_FORMATTER));
                    } else {
                        client.resumeAllRelays(controllerId);
                    }
                } else if (zone != null) {
                    if (command == OnOffType.ON) {
                        client.suspendRelay(zone.id, OffsetDateTime.now(ZoneOffset.UTC).plus(DEFAULT_SUSPEND_TIME_HOURS, ChronoUnit.HOURS).format(DATE_FORMATTER));
                    } else {
                        client.resumeRelay(zone.id);
                    }
                }
                break;
            case CHANNEL_ZONE_SUSPENDUNTIL:
                if (!(command instanceof DateTimeType)) {
                    logger.warn("Invalid command type for suspend {}", command.getClass().getName());
                    return;
                }
                if (allCommand) {
                    client.suspendAllRelays(controllerId, ((DateTimeType) command).getZonedDateTime().format(DATE_FORMATTER));
                } else if (zone != null) {
                    client.suspendRelay(zone.id, ((DateTimeType) command).getZonedDateTime().format(DATE_FORMATTER));
                }
                break;
            default:
                logger.warn("Uknown channelId {}", channelId);
                return;
        }
        HydrawiseAccountHandler handler = getAccountHandler();
        if (handler != null) {
            handler.refreshData(DEFAULT_REFRESH_SECONDS);
        }
    } catch (HydrawiseCommandException | HydrawiseConnectionException e) {
        logger.debug("Could not issue command", e);
    } catch (HydrawiseAuthenticationException e) {
        logger.debug("Credentials not valid");
    }
}
Also used : Zone(org.openhab.binding.hydrawise.internal.api.graphql.dto.Zone) HydrawiseCommandException(org.openhab.binding.hydrawise.internal.api.HydrawiseCommandException) RefreshType(org.openhab.core.types.RefreshType) DateTimeType(org.openhab.core.library.types.DateTimeType) HydrawiseConnectionException(org.openhab.binding.hydrawise.internal.api.HydrawiseConnectionException) HydrawiseGraphQLClient(org.openhab.binding.hydrawise.internal.api.graphql.HydrawiseGraphQLClient) QuantityType(org.openhab.core.library.types.QuantityType) OnOffType(org.openhab.core.library.types.OnOffType) HydrawiseAuthenticationException(org.openhab.binding.hydrawise.internal.api.HydrawiseAuthenticationException)

Example 5 with HydrawiseConnectionException

use of org.openhab.binding.hydrawise.internal.api.HydrawiseConnectionException in project openhab-addons by openhab.

the class HydrawiseLocalHandler method configureInternal.

private void configureInternal() {
    clearPolling();
    stateMap.clear();
    relayMap.clear();
    try {
        HydrawiseLocalConfiguration configuration = getConfig().as(HydrawiseLocalConfiguration.class);
        this.refresh = Math.max(configuration.refresh, MIN_REFRESH_SECONDS);
        logger.trace("Connecting to host {}", configuration.host);
        client.setCredentials(configuration.host, configuration.username, configuration.password);
        LocalScheduleResponse response = client.getLocalSchedule();
        if (response != null) {
            updateZones(response);
            initPolling(refresh);
        } else {
            logger.debug("Could not connect to service");
            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Invalid response from service");
        }
    } catch (HydrawiseConnectionException e) {
        logger.debug("Could not connect to service");
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
    } catch (HydrawiseAuthenticationException e) {
        logger.debug("Credentials not valid");
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Credentials not valid");
    }
}
Also used : LocalScheduleResponse(org.openhab.binding.hydrawise.internal.api.local.dto.LocalScheduleResponse) HydrawiseConnectionException(org.openhab.binding.hydrawise.internal.api.HydrawiseConnectionException) HydrawiseAuthenticationException(org.openhab.binding.hydrawise.internal.api.HydrawiseAuthenticationException) HydrawiseLocalConfiguration(org.openhab.binding.hydrawise.internal.config.HydrawiseLocalConfiguration)

Aggregations

HydrawiseConnectionException (org.openhab.binding.hydrawise.internal.api.HydrawiseConnectionException)7 HydrawiseAuthenticationException (org.openhab.binding.hydrawise.internal.api.HydrawiseAuthenticationException)6 IOException (java.io.IOException)3 ExecutionException (java.util.concurrent.ExecutionException)2 TimeoutException (java.util.concurrent.TimeoutException)2 Nullable (org.eclipse.jdt.annotation.Nullable)2 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)2 HydrawiseCommandException (org.openhab.binding.hydrawise.internal.api.HydrawiseCommandException)2 HydrawiseGraphQLClient (org.openhab.binding.hydrawise.internal.api.graphql.HydrawiseGraphQLClient)2 QueryResponse (org.openhab.binding.hydrawise.internal.api.graphql.dto.QueryResponse)2 AccessTokenResponse (org.openhab.core.auth.client.oauth2.AccessTokenResponse)2 OAuthException (org.openhab.core.auth.client.oauth2.OAuthException)2 OAuthResponseException (org.openhab.core.auth.client.oauth2.OAuthResponseException)2 OnOffType (org.openhab.core.library.types.OnOffType)2 QuantityType (org.openhab.core.library.types.QuantityType)2 RefreshType (org.openhab.core.types.RefreshType)2 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 List (java.util.List)1