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