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