Search in sources :

Example 1 with AuthorizationException

use of org.openhab.binding.homeconnect.internal.client.exception.AuthorizationException in project openhab-addons by openhab.

the class HomeConnectHoodHandler method updateSelectedProgramStateDescription.

@Override
protected void updateSelectedProgramStateDescription() {
    // update hood program actions
    if (isBridgeOffline() || !isThingAccessibleViaServerSentEvents()) {
        return;
    }
    Optional<HomeConnectApiClient> apiClient = getApiClient();
    if (apiClient.isPresent()) {
        try {
            ArrayList<StateOption> stateOptions = new ArrayList<>();
            getPrograms().forEach(availableProgram -> {
                if (PROGRAM_HOOD_AUTOMATIC.equals(availableProgram.getKey())) {
                    stateOptions.add(new StateOption(COMMAND_AUTOMATIC, mapStringType(availableProgram.getKey())));
                } else if (PROGRAM_HOOD_DELAYED_SHUT_OFF.equals(availableProgram.getKey())) {
                    stateOptions.add(new StateOption(COMMAND_DELAYED_SHUT_OFF, mapStringType(availableProgram.getKey())));
                } else if (PROGRAM_HOOD_VENTING.equals(availableProgram.getKey())) {
                    try {
                        List<AvailableProgramOption> availableProgramOptions = apiClient.get().getProgramOptions(getThingHaId(), PROGRAM_HOOD_VENTING);
                        if (availableProgramOptions == null || availableProgramOptions.isEmpty()) {
                            throw new CommunicationException("Program " + PROGRAM_HOOD_VENTING + " is unsupported");
                        }
                        availableProgramOptions.forEach(option -> {
                            if (OPTION_HOOD_VENTING_LEVEL.equalsIgnoreCase(option.getKey())) {
                                option.getAllowedValues().stream().filter(s -> !STAGE_FAN_OFF.equalsIgnoreCase(s)).forEach(s -> stateOptions.add(createVentingStateOption(s)));
                            } else if (OPTION_HOOD_INTENSIVE_LEVEL.equalsIgnoreCase(option.getKey())) {
                                option.getAllowedValues().stream().filter(s -> !STAGE_INTENSIVE_STAGE_OFF.equalsIgnoreCase(s)).forEach(s -> stateOptions.add(createVentingStateOption(s)));
                            }
                        });
                    } catch (CommunicationException | ApplianceOfflineException | AuthorizationException e) {
                        logger.warn("Could not fetch hood program options. error={}", e.getMessage());
                        stateOptions.add(createVentingStateOption(STAGE_FAN_STAGE_01));
                        stateOptions.add(createVentingStateOption(STAGE_FAN_STAGE_02));
                        stateOptions.add(createVentingStateOption(STAGE_FAN_STAGE_03));
                        stateOptions.add(createVentingStateOption(STAGE_FAN_STAGE_04));
                        stateOptions.add(createVentingStateOption(STAGE_FAN_STAGE_05));
                        stateOptions.add(createVentingStateOption(STAGE_INTENSIVE_STAGE_1));
                        stateOptions.add(createVentingStateOption(STAGE_INTENSIVE_STAGE_2));
                    }
                }
            });
            stateOptions.add(new StateOption(COMMAND_STOP, "Stop"));
            getThingChannel(CHANNEL_HOOD_ACTIONS_STATE).ifPresent(channel -> getDynamicStateDescriptionProvider().setStateOptions(channel.getUID(), stateOptions));
        } catch (CommunicationException | ApplianceOfflineException | AuthorizationException e) {
            logger.debug("Could not fetch available programs. thing={}, haId={}, error={}", getThingLabel(), getThingHaId(), e.getMessage());
            removeSelectedProgramStateDescription();
        }
    } else {
        removeSelectedProgramStateDescription();
    }
}
Also used : AvailableProgramOption(org.openhab.binding.homeconnect.internal.client.model.AvailableProgramOption) StringType(org.openhab.core.library.types.StringType) AuthorizationException(org.openhab.binding.homeconnect.internal.client.exception.AuthorizationException) LoggerFactory(org.slf4j.LoggerFactory) OnOffType(org.openhab.core.library.types.OnOffType) ArrayList(java.util.ArrayList) Thing(org.openhab.core.thing.Thing) Map(java.util.Map) ChannelUID(org.openhab.core.thing.ChannelUID) Data(org.openhab.binding.homeconnect.internal.client.model.Data) CommunicationException(org.openhab.binding.homeconnect.internal.client.exception.CommunicationException) ApplianceOfflineException(org.openhab.binding.homeconnect.internal.client.exception.ApplianceOfflineException) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) HomeConnectApiClient(org.openhab.binding.homeconnect.internal.client.HomeConnectApiClient) Command(org.openhab.core.types.Command) Logger(org.slf4j.Logger) Collections.emptyList(java.util.Collections.emptyList) AvailableProgramOption(org.openhab.binding.homeconnect.internal.client.model.AvailableProgramOption) UnDefType(org.openhab.core.types.UnDefType) StateOption(org.openhab.core.types.StateOption) HomeConnectBindingConstants(org.openhab.binding.homeconnect.internal.HomeConnectBindingConstants) String.format(java.lang.String.format) List(java.util.List) PercentType(org.openhab.core.library.types.PercentType) Optional(java.util.Optional) HomeConnectDynamicStateDescriptionProvider(org.openhab.binding.homeconnect.internal.type.HomeConnectDynamicStateDescriptionProvider) HomeConnectApiClient(org.openhab.binding.homeconnect.internal.client.HomeConnectApiClient) CommunicationException(org.openhab.binding.homeconnect.internal.client.exception.CommunicationException) AuthorizationException(org.openhab.binding.homeconnect.internal.client.exception.AuthorizationException) ArrayList(java.util.ArrayList) ApplianceOfflineException(org.openhab.binding.homeconnect.internal.client.exception.ApplianceOfflineException) StateOption(org.openhab.core.types.StateOption)

Example 2 with AuthorizationException

use of org.openhab.binding.homeconnect.internal.client.exception.AuthorizationException in project openhab-addons by openhab.

the class HttpHelper method getAuthorizationHeader.

public static String getAuthorizationHeader(OAuthClientService oAuthClientService) throws AuthorizationException, CommunicationException {
    synchronized (AUTHORIZATION_HEADER_MONITOR) {
        try {
            AccessTokenResponse accessTokenResponse = oAuthClientService.getAccessTokenResponse();
            // refresh the token if it's about to expire
            if (accessTokenResponse != null && accessTokenResponse.isExpired(LocalDateTime.now(), OAUTH_EXPIRE_BUFFER)) {
                LoggerFactory.getLogger(HttpHelper.class).debug("Requesting a refresh of the access token.");
                accessTokenResponse = oAuthClientService.refreshToken();
            }
            if (accessTokenResponse != null) {
                String lastToken = lastAccessToken;
                if (lastToken == null) {
                    LoggerFactory.getLogger(HttpHelper.class).debug("The used access token was created at {}", accessTokenResponse.getCreatedOn().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
                } else if (!lastToken.equals(accessTokenResponse.getAccessToken())) {
                    LoggerFactory.getLogger(HttpHelper.class).debug("The access token changed. New one created at {}", accessTokenResponse.getCreatedOn().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
                }
                lastAccessToken = accessTokenResponse.getAccessToken();
                LoggerFactory.getLogger(HttpHelper.class).debug("Current access token: {}", accessTokenResponse.getAccessToken());
                return BEARER + accessTokenResponse.getAccessToken();
            } else {
                LoggerFactory.getLogger(HttpHelper.class).error("No access token available! Fatal error.");
                throw new AuthorizationException("No access token available!");
            }
        } catch (IOException e) {
            String errorMessage = e.getMessage();
            throw new CommunicationException(errorMessage != null ? errorMessage : "IOException", e);
        } catch (OAuthException | OAuthResponseException e) {
            String errorMessage = e.getMessage();
            throw new AuthorizationException(errorMessage != null ? errorMessage : "oAuth exception", e);
        }
    }
}
Also used : OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) CommunicationException(org.openhab.binding.homeconnect.internal.client.exception.CommunicationException) AuthorizationException(org.openhab.binding.homeconnect.internal.client.exception.AuthorizationException) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) IOException(java.io.IOException) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse)

Example 3 with AuthorizationException

use of org.openhab.binding.homeconnect.internal.client.exception.AuthorizationException in project openhab-addons by openhab.

the class HomeConnectDiscoveryService method startScan.

@Override
protected void startScan() {
    logger.debug("Starting device scan.");
    var bridgeHandler = this.bridgeHandler;
    if (bridgeHandler != null) {
        HomeConnectApiClient apiClient = bridgeHandler.getApiClient();
        try {
            List<HomeAppliance> appliances = apiClient.getHomeAppliances();
            logger.debug("Scan found {} devices.", appliances.size());
            // add found devices
            for (HomeAppliance appliance : appliances) {
                @Nullable ThingTypeUID thingTypeUID = getThingTypeUID(appliance);
                if (thingTypeUID != null) {
                    logger.debug("Found {} ({}).", appliance.getHaId(), appliance.getType().toUpperCase());
                    Map<String, Object> properties = Map.of(HA_ID, appliance.getHaId());
                    String name = appliance.getBrand() + " " + appliance.getName() + " (" + appliance.getHaId() + ")";
                    DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(new ThingUID(BINDING_ID, appliance.getType(), bridgeHandler.getThing().getUID().getId(), appliance.getHaId())).withThingType(thingTypeUID).withProperties(properties).withRepresentationProperty(HA_ID).withBridge(bridgeHandler.getThing().getUID()).withLabel(name).build();
                    thingDiscovered(discoveryResult);
                } else {
                    logger.debug("Ignoring unsupported device {} of type {}.", appliance.getHaId(), appliance.getType());
                }
            }
        } catch (CommunicationException | AuthorizationException e) {
            logger.debug("Exception during scan.", e);
        }
    }
    logger.debug("Finished device scan.");
}
Also used : CommunicationException(org.openhab.binding.homeconnect.internal.client.exception.CommunicationException) AuthorizationException(org.openhab.binding.homeconnect.internal.client.exception.AuthorizationException) DiscoveryResult(org.openhab.core.config.discovery.DiscoveryResult) HomeConnectApiClient(org.openhab.binding.homeconnect.internal.client.HomeConnectApiClient) HomeAppliance(org.openhab.binding.homeconnect.internal.client.model.HomeAppliance) ThingUID(org.openhab.core.thing.ThingUID) ThingTypeUID(org.openhab.core.thing.ThingTypeUID) Nullable(org.eclipse.jdt.annotation.Nullable)

Example 4 with AuthorizationException

use of org.openhab.binding.homeconnect.internal.client.exception.AuthorizationException in project openhab-addons by openhab.

the class AbstractHomeConnectThingHandler method refreshThingStatus.

/**
 * Check bridge status and refresh connection status of thing accordingly.
 */
protected void refreshThingStatus() {
    Optional<HomeConnectApiClient> apiClient = getApiClient();
    apiClient.ifPresent(client -> {
        try {
            HomeAppliance homeAppliance = client.getHomeAppliance(getThingHaId());
            if (!homeAppliance.isConnected()) {
                updateStatus(OFFLINE);
            } else {
                updateStatus(ONLINE);
            }
            accessible.set(true);
        } catch (CommunicationException e) {
            logger.debug("Update status to OFFLINE. Home Connect service is not reachable or a problem occurred!  thing={}, haId={}, error={}.", getThingLabel(), getThingHaId(), e.getMessage());
            updateStatus(OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Home Connect service is not reachable or a problem occurred! (" + e.getMessage() + ").");
            accessible.set(false);
        } catch (AuthorizationException e) {
            logger.debug("Update status to OFFLINE. Home Connect service is not reachable or a problem occurred!  thing={}, haId={}, error={}", getThingLabel(), getThingHaId(), e.getMessage());
            updateStatus(OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Home Connect service is not reachable or a problem occurred! (" + e.getMessage() + ").");
            accessible.set(false);
            handleAuthenticationError(e);
        }
    });
    if (apiClient.isEmpty()) {
        updateStatus(OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED);
        accessible.set(false);
    }
}
Also used : HomeConnectApiClient(org.openhab.binding.homeconnect.internal.client.HomeConnectApiClient) CommunicationException(org.openhab.binding.homeconnect.internal.client.exception.CommunicationException) AuthorizationException(org.openhab.binding.homeconnect.internal.client.exception.AuthorizationException) HomeAppliance(org.openhab.binding.homeconnect.internal.client.model.HomeAppliance)

Example 5 with AuthorizationException

use of org.openhab.binding.homeconnect.internal.client.exception.AuthorizationException in project openhab-addons by openhab.

the class HomeConnectBridgeHandler method initialize.

@Override
public void initialize() {
    // let the bridge configuration servlet know about this handler
    homeConnectServlet.addBridgeHandler(this);
    // create oAuth service
    ApiBridgeConfiguration config = getConfiguration();
    String tokenUrl = (config.isSimulator() ? API_SIMULATOR_BASE_URL : API_BASE_URL) + OAUTH_TOKEN_PATH;
    String authorizeUrl = (config.isSimulator() ? API_SIMULATOR_BASE_URL : API_BASE_URL) + OAUTH_AUTHORIZE_PATH;
    String oAuthServiceHandleId = thing.getUID().getAsString() + (config.isSimulator() ? "simulator" : "");
    oAuthClientService = oAuthFactory.createOAuthClientService(oAuthServiceHandleId, tokenUrl, authorizeUrl, config.getClientId(), config.getClientSecret(), OAUTH_SCOPE, true);
    this.oAuthServiceHandleId = oAuthServiceHandleId;
    logger.debug("Initialize oAuth client service. tokenUrl={}, authorizeUrl={}, oAuthServiceHandleId={}, scope={}, oAuthClientService={}", tokenUrl, authorizeUrl, oAuthServiceHandleId, OAUTH_SCOPE, oAuthClientService);
    // create api client
    apiClient = new HomeConnectApiClient(httpClient, oAuthClientService, config.isSimulator(), apiRequestHistory, config);
    eventSourceClient = new HomeConnectEventSourceClient(clientBuilder, eventSourceFactory, oAuthClientService, config.isSimulator(), scheduler, eventHistory);
    updateStatus(ThingStatus.UNKNOWN);
    scheduler.submit(() -> {
        try {
            @Nullable AccessTokenResponse accessTokenResponse = oAuthClientService.getAccessTokenResponse();
            if (accessTokenResponse == null) {
                updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING, "Please authenticate your account at http(s)://[YOUROPENHAB]:[YOURPORT]/homeconnect (e.g. http://192.168.178.100:8080/homeconnect).");
            } else {
                apiClient.getHomeAppliances();
                updateStatus(ThingStatus.ONLINE);
            }
        } catch (OAuthException | IOException | OAuthResponseException | CommunicationException | AuthorizationException e) {
            ZonedDateTime nextReinitializeDateTime = ZonedDateTime.now().plusSeconds(REINITIALIZATION_DELAY_SEC);
            String offlineMessage = String.format("Home Connect service is not reachable or a problem occurred! Retrying at %s (%s). bridge=%s", nextReinitializeDateTime.format(DateTimeFormatter.RFC_1123_DATE_TIME), e.getMessage(), getThing().getLabel());
            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, offlineMessage);
            scheduleReinitialize();
        }
    });
}
Also used : OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) CommunicationException(org.openhab.binding.homeconnect.internal.client.exception.CommunicationException) AuthorizationException(org.openhab.binding.homeconnect.internal.client.exception.AuthorizationException) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) IOException(java.io.IOException) HomeConnectApiClient(org.openhab.binding.homeconnect.internal.client.HomeConnectApiClient) HomeConnectEventSourceClient(org.openhab.binding.homeconnect.internal.client.HomeConnectEventSourceClient) ApiBridgeConfiguration(org.openhab.binding.homeconnect.internal.configuration.ApiBridgeConfiguration) ZonedDateTime(java.time.ZonedDateTime) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) Nullable(org.eclipse.jdt.annotation.Nullable)

Aggregations

AuthorizationException (org.openhab.binding.homeconnect.internal.client.exception.AuthorizationException)6 CommunicationException (org.openhab.binding.homeconnect.internal.client.exception.CommunicationException)6 HomeConnectApiClient (org.openhab.binding.homeconnect.internal.client.HomeConnectApiClient)4 Nullable (org.eclipse.jdt.annotation.Nullable)3 IOException (java.io.IOException)2 List (java.util.List)2 Map (java.util.Map)2 NonNullByDefault (org.eclipse.jdt.annotation.NonNullByDefault)2 HomeConnectBindingConstants (org.openhab.binding.homeconnect.internal.HomeConnectBindingConstants)2 HomeAppliance (org.openhab.binding.homeconnect.internal.client.model.HomeAppliance)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 Logger (org.slf4j.Logger)2 LoggerFactory (org.slf4j.LoggerFactory)2 String.format (java.lang.String.format)1 ZonedDateTime (java.time.ZonedDateTime)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 Collections.emptyList (java.util.Collections.emptyList)1