]> git.basschouten.com Git - openhab-addons.git/blob
7def5c7f2588a4310c4b7c1d73399d44a2439dba
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.hydrawise.internal.handler;
14
15 import java.io.IOException;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.List;
20 import java.util.concurrent.ScheduledFuture;
21 import java.util.concurrent.TimeUnit;
22
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.eclipse.jetty.client.HttpClient;
26 import org.openhab.binding.hydrawise.internal.HydrawiseControllerListener;
27 import org.openhab.binding.hydrawise.internal.api.HydrawiseAuthenticationException;
28 import org.openhab.binding.hydrawise.internal.api.HydrawiseConnectionException;
29 import org.openhab.binding.hydrawise.internal.api.graphql.HydrawiseGraphQLClient;
30 import org.openhab.binding.hydrawise.internal.api.graphql.dto.Customer;
31 import org.openhab.binding.hydrawise.internal.api.graphql.dto.QueryResponse;
32 import org.openhab.binding.hydrawise.internal.config.HydrawiseAccountConfiguration;
33 import org.openhab.binding.hydrawise.internal.discovery.HydrawiseCloudControllerDiscoveryService;
34 import org.openhab.core.auth.client.oauth2.AccessTokenRefreshListener;
35 import org.openhab.core.auth.client.oauth2.AccessTokenResponse;
36 import org.openhab.core.auth.client.oauth2.OAuthClientService;
37 import org.openhab.core.auth.client.oauth2.OAuthException;
38 import org.openhab.core.auth.client.oauth2.OAuthFactory;
39 import org.openhab.core.auth.client.oauth2.OAuthResponseException;
40 import org.openhab.core.config.core.Configuration;
41 import org.openhab.core.thing.Bridge;
42 import org.openhab.core.thing.ChannelUID;
43 import org.openhab.core.thing.ThingStatus;
44 import org.openhab.core.thing.ThingStatusDetail;
45 import org.openhab.core.thing.binding.BaseBridgeHandler;
46 import org.openhab.core.thing.binding.ThingHandlerService;
47 import org.openhab.core.types.Command;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  * The {@link HydrawiseAccountHandler} is responsible for handling for connecting to a Hydrawise account and polling for
53  * controller data
54  *
55  * @author Dan Cunningham - Initial contribution
56  */
57 @NonNullByDefault
58 public class HydrawiseAccountHandler extends BaseBridgeHandler implements AccessTokenRefreshListener {
59     private final Logger logger = LoggerFactory.getLogger(HydrawiseAccountHandler.class);
60     /**
61      * Minimum amount of time we can poll for updates
62      */
63     private static final int MIN_REFRESH_SECONDS = 30;
64     private static final String BASE_URL = "https://app.hydrawise.com/api/v2/";
65     private static final String AUTH_URL = BASE_URL + "oauth/access-token";
66     private static final String CLIENT_SECRET = "zn3CrjglwNV1";
67     private static final String CLIENT_ID = "hydrawise_app";
68     private static final String SCOPE = "all";
69     private final List<HydrawiseControllerListener> controllerListeners = new ArrayList<HydrawiseControllerListener>();
70     private final HydrawiseGraphQLClient apiClient;
71     private final OAuthClientService oAuthService;
72     private @Nullable ScheduledFuture<?> pollFuture;
73     private @Nullable Customer lastData;
74     private int refresh;
75
76     public HydrawiseAccountHandler(final Bridge bridge, final HttpClient httpClient, final OAuthFactory oAuthFactory) {
77         super(bridge);
78         this.oAuthService = oAuthFactory.createOAuthClientService(getThing().toString(), AUTH_URL, AUTH_URL, CLIENT_ID,
79                 CLIENT_SECRET, SCOPE, false);
80         oAuthService.addAccessTokenRefreshListener(this);
81         this.apiClient = new HydrawiseGraphQLClient(httpClient, oAuthService);
82     }
83
84     @Override
85     public void handleCommand(ChannelUID channelUID, Command command) {
86     }
87
88     @Override
89     public void initialize() {
90         logger.debug("Handler initialized.");
91         scheduler.schedule(this::configure, 0, TimeUnit.SECONDS);
92     }
93
94     @Override
95     public void dispose() {
96         logger.debug("Handler disposed.");
97         clearPolling();
98     }
99
100     @Override
101     public void onAccessTokenResponse(AccessTokenResponse tokenResponse) {
102         logger.debug("Auth Token Refreshed, expires in {}", tokenResponse.getExpiresIn());
103     }
104
105     @Override
106     public Collection<Class<? extends ThingHandlerService>> getServices() {
107         return Collections.singleton(HydrawiseCloudControllerDiscoveryService.class);
108     }
109
110     public void addControllerListeners(HydrawiseControllerListener listener) {
111         this.controllerListeners.add(listener);
112         Customer data = lastData;
113         if (data != null) {
114             listener.onData(data.controllers);
115         }
116     }
117
118     public void removeControllerListeners(HydrawiseControllerListener listener) {
119         this.controllerListeners.remove(listener);
120     }
121
122     public @Nullable HydrawiseGraphQLClient graphQLClient() {
123         return apiClient;
124     }
125
126     public @Nullable Customer lastData() {
127         return lastData;
128     }
129
130     public void refreshData(int delaySeconds) {
131         initPolling(delaySeconds, this.refresh);
132     }
133
134     private void configure() {
135         HydrawiseAccountConfiguration config = getConfig().as(HydrawiseAccountConfiguration.class);
136         try {
137             if (!config.userName.isEmpty() && !config.password.isEmpty()) {
138                 if (!config.savePassword) {
139                     Configuration editedConfig = editConfiguration();
140                     editedConfig.remove("password");
141                     updateConfiguration(editedConfig);
142                 }
143                 oAuthService.getAccessTokenByResourceOwnerPasswordCredentials(config.userName, config.password, SCOPE);
144             } else if (oAuthService.getAccessTokenResponse() == null) {
145                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Login credentials required.");
146                 return;
147             }
148             this.refresh = Math.max(config.refreshInterval, MIN_REFRESH_SECONDS);
149             initPolling(0, refresh);
150         } catch (OAuthException | IOException e) {
151             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
152         } catch (OAuthResponseException e) {
153             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Login credentials required.");
154         }
155     }
156
157     /**
158      * Starts/Restarts polling with an initial delay. This allows changes in the poll cycle for when commands are sent
159      * and we need to poll sooner then the next refresh cycle.
160      */
161     private synchronized void initPolling(int initalDelay, int refresh) {
162         clearPolling();
163         pollFuture = scheduler.scheduleWithFixedDelay(this::poll, initalDelay, refresh, TimeUnit.SECONDS);
164     }
165
166     /**
167      * Stops/clears this thing's polling future
168      */
169     private void clearPolling() {
170         ScheduledFuture<?> localFuture = pollFuture;
171         if (isFutureValid(localFuture)) {
172             if (localFuture != null) {
173                 localFuture.cancel(false);
174             }
175         }
176     }
177
178     private boolean isFutureValid(@Nullable ScheduledFuture<?> future) {
179         return future != null && !future.isCancelled();
180     }
181
182     private void poll() {
183         poll(true);
184     }
185
186     private void poll(boolean retry) {
187         try {
188             QueryResponse response = apiClient.queryControllers();
189             if (response == null) {
190                 throw new HydrawiseConnectionException("Malformed response");
191             }
192             if (response.errors != null && response.errors.size() > 0) {
193                 throw new HydrawiseConnectionException(response.errors.stream().map(error -> error.message).reduce("",
194                         (messages, message) -> messages + message + ". "));
195             }
196             if (getThing().getStatus() != ThingStatus.ONLINE) {
197                 updateStatus(ThingStatus.ONLINE);
198             }
199             lastData = response.data.me;
200             controllerListeners.forEach(listener -> {
201                 listener.onData(response.data.me.controllers);
202             });
203         } catch (HydrawiseConnectionException e) {
204             if (retry) {
205                 logger.debug("Retrying failed poll", e);
206                 poll(false);
207             } else {
208                 logger.debug("Will try again during next poll period", e);
209                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
210             }
211         } catch (HydrawiseAuthenticationException e) {
212             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
213             clearPolling();
214         }
215     }
216 }