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();
}
}
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);
}
}
}
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.");
}
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);
}
}
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();
}
});
}
Aggregations