]> git.basschouten.com Git - openhab-addons.git/blob
eed7c979e605159eba8da03407db9d6c43f93290
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.netatmo.internal.handler;
14
15 import static java.util.Comparator.*;
16 import static org.openhab.binding.netatmo.internal.NetatmoBindingConstants.*;
17
18 import java.io.ByteArrayInputStream;
19 import java.io.InputStream;
20 import java.lang.reflect.Constructor;
21 import java.net.URI;
22 import java.nio.charset.StandardCharsets;
23 import java.time.LocalDateTime;
24 import java.util.ArrayDeque;
25 import java.util.Collection;
26 import java.util.Deque;
27 import java.util.HashMap;
28 import java.util.Map;
29 import java.util.Objects;
30 import java.util.Optional;
31 import java.util.Set;
32 import java.util.concurrent.ExecutionException;
33 import java.util.concurrent.ScheduledFuture;
34 import java.util.concurrent.TimeUnit;
35 import java.util.concurrent.TimeoutException;
36 import java.util.function.BiFunction;
37
38 import javax.ws.rs.core.UriBuilder;
39
40 import org.eclipse.jdt.annotation.NonNullByDefault;
41 import org.eclipse.jdt.annotation.Nullable;
42 import org.eclipse.jetty.client.HttpClient;
43 import org.eclipse.jetty.client.api.ContentResponse;
44 import org.eclipse.jetty.client.api.Request;
45 import org.eclipse.jetty.client.util.InputStreamContentProvider;
46 import org.eclipse.jetty.http.HttpHeader;
47 import org.eclipse.jetty.http.HttpMethod;
48 import org.eclipse.jetty.http.HttpStatus;
49 import org.eclipse.jetty.http.HttpStatus.Code;
50 import org.openhab.binding.netatmo.internal.api.AircareApi;
51 import org.openhab.binding.netatmo.internal.api.ApiError;
52 import org.openhab.binding.netatmo.internal.api.AuthenticationApi;
53 import org.openhab.binding.netatmo.internal.api.HomeApi;
54 import org.openhab.binding.netatmo.internal.api.ListBodyResponse;
55 import org.openhab.binding.netatmo.internal.api.NetatmoException;
56 import org.openhab.binding.netatmo.internal.api.RestManager;
57 import org.openhab.binding.netatmo.internal.api.SecurityApi;
58 import org.openhab.binding.netatmo.internal.api.WeatherApi;
59 import org.openhab.binding.netatmo.internal.api.data.NetatmoConstants.FeatureArea;
60 import org.openhab.binding.netatmo.internal.api.data.NetatmoConstants.Scope;
61 import org.openhab.binding.netatmo.internal.api.data.NetatmoConstants.ServiceError;
62 import org.openhab.binding.netatmo.internal.api.dto.HomeDataModule;
63 import org.openhab.binding.netatmo.internal.api.dto.NAMain;
64 import org.openhab.binding.netatmo.internal.api.dto.NAModule;
65 import org.openhab.binding.netatmo.internal.config.ApiHandlerConfiguration;
66 import org.openhab.binding.netatmo.internal.config.BindingConfiguration;
67 import org.openhab.binding.netatmo.internal.config.ConfigurationLevel;
68 import org.openhab.binding.netatmo.internal.deserialization.NADeserializer;
69 import org.openhab.binding.netatmo.internal.discovery.NetatmoDiscoveryService;
70 import org.openhab.binding.netatmo.internal.servlet.GrantServlet;
71 import org.openhab.binding.netatmo.internal.servlet.WebhookServlet;
72 import org.openhab.core.config.core.Configuration;
73 import org.openhab.core.library.types.DecimalType;
74 import org.openhab.core.thing.Bridge;
75 import org.openhab.core.thing.ChannelUID;
76 import org.openhab.core.thing.Thing;
77 import org.openhab.core.thing.ThingStatus;
78 import org.openhab.core.thing.ThingStatusDetail;
79 import org.openhab.core.thing.ThingUID;
80 import org.openhab.core.thing.binding.BaseBridgeHandler;
81 import org.openhab.core.thing.binding.ThingHandlerService;
82 import org.openhab.core.types.Command;
83 import org.osgi.service.http.HttpService;
84 import org.slf4j.Logger;
85 import org.slf4j.LoggerFactory;
86
87 /**
88  * {@link ApiBridgeHandler} is the handler for a Netatmo API and connects it to the framework.
89  *
90  * @author GaĆ«l L'hopital - Initial contribution
91  *
92  */
93 @NonNullByDefault
94 public class ApiBridgeHandler extends BaseBridgeHandler {
95     private static final int TIMEOUT_S = 20;
96
97     private final Logger logger = LoggerFactory.getLogger(ApiBridgeHandler.class);
98     private final BindingConfiguration bindingConf;
99     private final AuthenticationApi connectApi;
100     private final HttpClient httpClient;
101     private final NADeserializer deserializer;
102     private final HttpService httpService;
103
104     private Optional<ScheduledFuture<?>> connectJob = Optional.empty();
105     private Map<Class<? extends RestManager>, RestManager> managers = new HashMap<>();
106     private @Nullable WebhookServlet webHookServlet;
107     private @Nullable GrantServlet grantServlet;
108     private Deque<LocalDateTime> requestsTimestamps;
109     private final ChannelUID requestCountChannelUID;
110
111     public ApiBridgeHandler(Bridge bridge, HttpClient httpClient, NADeserializer deserializer,
112             BindingConfiguration configuration, HttpService httpService) {
113         super(bridge);
114         this.bindingConf = configuration;
115         this.connectApi = new AuthenticationApi(this, scheduler);
116         this.httpClient = httpClient;
117         this.deserializer = deserializer;
118         this.httpService = httpService;
119         this.requestsTimestamps = new ArrayDeque<>(200);
120         this.requestCountChannelUID = new ChannelUID(getThing().getUID(), GROUP_MONITORING, CHANNEL_REQUEST_COUNT);
121     }
122
123     @Override
124     public void initialize() {
125         logger.debug("Initializing Netatmo API bridge handler.");
126         updateStatus(ThingStatus.UNKNOWN);
127         GrantServlet servlet = new GrantServlet(this, httpService);
128         servlet.startListening();
129         grantServlet = servlet;
130         scheduler.execute(() -> openConnection(null, null));
131     }
132
133     public void openConnection(@Nullable String code, @Nullable String redirectUri) {
134         ApiHandlerConfiguration configuration = getConfiguration();
135         ConfigurationLevel level = configuration.check();
136         switch (level) {
137             case EMPTY_CLIENT_ID:
138             case EMPTY_CLIENT_SECRET:
139                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, level.message);
140                 break;
141             case REFRESH_TOKEN_NEEDED:
142                 if (code == null || redirectUri == null) {
143                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, level.message);
144                     break;
145                 } // else we can proceed to get the token refresh
146             case COMPLETED:
147                 try {
148                     logger.debug("Connecting to Netatmo API.");
149
150                     String refreshToken = connectApi.authorize(configuration, code, redirectUri);
151
152                     if (configuration.refreshToken.isBlank()) {
153                         Configuration thingConfig = editConfiguration();
154                         thingConfig.put(ApiHandlerConfiguration.REFRESH_TOKEN, refreshToken);
155                         updateConfiguration(thingConfig);
156                         configuration = getConfiguration();
157                     }
158
159                     if (!configuration.webHookUrl.isBlank()) {
160                         SecurityApi securityApi = getRestManager(SecurityApi.class);
161                         if (securityApi != null) {
162                             WebhookServlet servlet = new WebhookServlet(this, httpService, deserializer, securityApi,
163                                     configuration.webHookUrl, configuration.webHookPostfix);
164                             servlet.startListening();
165                             this.webHookServlet = servlet;
166                         }
167                     }
168
169                     updateStatus(ThingStatus.ONLINE);
170
171                     getThing().getThings().stream().filter(Thing::isEnabled).map(Thing::getHandler)
172                             .filter(Objects::nonNull).map(CommonInterface.class::cast)
173                             .forEach(CommonInterface::expireData);
174
175                 } catch (NetatmoException e) {
176                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
177                     prepareReconnection(code, redirectUri);
178                 }
179                 break;
180         }
181     }
182
183     public ApiHandlerConfiguration getConfiguration() {
184         return getConfigAs(ApiHandlerConfiguration.class);
185     }
186
187     private void prepareReconnection(@Nullable String code, @Nullable String redirectUri) {
188         connectApi.disconnect();
189         freeConnectJob();
190         connectJob = Optional.of(scheduler.schedule(() -> openConnection(code, redirectUri),
191                 getConfiguration().reconnectInterval, TimeUnit.SECONDS));
192     }
193
194     private void freeConnectJob() {
195         connectJob.ifPresent(j -> j.cancel(true));
196         connectJob = Optional.empty();
197     }
198
199     @Override
200     public void dispose() {
201         logger.debug("Shutting down Netatmo API bridge handler.");
202         WebhookServlet localWebHook = this.webHookServlet;
203         if (localWebHook != null) {
204             localWebHook.dispose();
205         }
206         GrantServlet localGrant = this.grantServlet;
207         if (localGrant != null) {
208             localGrant.dispose();
209         }
210         connectApi.dispose();
211         freeConnectJob();
212         super.dispose();
213     }
214
215     @Override
216     public void handleCommand(ChannelUID channelUID, Command command) {
217         logger.debug("Netatmo Bridge is read-only and does not handle commands");
218     }
219
220     @SuppressWarnings("unchecked")
221     public <T extends RestManager> @Nullable T getRestManager(Class<T> clazz) {
222         if (!managers.containsKey(clazz)) {
223             try {
224                 Constructor<T> constructor = clazz.getConstructor(getClass());
225                 T instance = constructor.newInstance(this);
226                 Set<Scope> expected = instance.getRequiredScopes();
227                 if (connectApi.matchesScopes(expected)) {
228                     managers.put(clazz, instance);
229                 } else {
230                     logger.info("Unable to instantiate {}, expected scope {} is not active", clazz, expected);
231                 }
232             } catch (SecurityException | ReflectiveOperationException e) {
233                 logger.warn("Error invoking RestManager constructor for class {} : {}", clazz, e.getMessage());
234             }
235         }
236         return (T) managers.get(clazz);
237     }
238
239     public synchronized <T> T executeUri(URI uri, HttpMethod method, Class<T> clazz, @Nullable String payload,
240             @Nullable String contentType, int retryCount) throws NetatmoException {
241         try {
242             logger.trace("executeUri {}  {} ", method.toString(), uri);
243
244             Request request = httpClient.newRequest(uri).method(method).timeout(TIMEOUT_S, TimeUnit.SECONDS);
245
246             String auth = connectApi.getAuthorization();
247             if (auth != null) {
248                 request.header(HttpHeader.AUTHORIZATION, auth);
249             }
250
251             if (payload != null && contentType != null
252                     && (HttpMethod.POST.equals(method) || HttpMethod.PUT.equals(method))) {
253                 InputStream stream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
254                 try (InputStreamContentProvider inputStreamContentProvider = new InputStreamContentProvider(stream)) {
255                     request.content(inputStreamContentProvider, contentType);
256                 }
257             }
258
259             if (isLinked(requestCountChannelUID)) {
260                 LocalDateTime now = LocalDateTime.now();
261                 LocalDateTime oneHourAgo = now.minusHours(1);
262                 requestsTimestamps.addLast(now);
263                 while (requestsTimestamps.getFirst().isBefore(oneHourAgo)) {
264                     requestsTimestamps.removeFirst();
265                 }
266                 updateState(requestCountChannelUID, new DecimalType(requestsTimestamps.size()));
267             }
268             ContentResponse response = request.send();
269
270             Code statusCode = HttpStatus.getCode(response.getStatus());
271             String responseBody = new String(response.getContent(), StandardCharsets.UTF_8);
272             logger.trace("executeUri returned : code {} body {}", statusCode, responseBody);
273
274             if (statusCode != Code.OK) {
275                 try {
276                     ApiError error = deserializer.deserialize(ApiError.class, responseBody);
277                     throw new NetatmoException(error);
278                 } catch (NetatmoException e) {
279                     logger.debug("Error deserializing payload from error response", e);
280                     throw new NetatmoException(statusCode.getMessage());
281                 }
282             }
283             return deserializer.deserialize(clazz, responseBody);
284         } catch (NetatmoException e) {
285             if (e.getStatusCode() == ServiceError.MAXIMUM_USAGE_REACHED) {
286                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
287                 prepareReconnection(null, null);
288             }
289             throw e;
290         } catch (InterruptedException e) {
291             Thread.currentThread().interrupt();
292             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
293             throw new NetatmoException(String.format("%s: \"%s\"", e.getClass().getName(), e.getMessage()));
294         } catch (TimeoutException | ExecutionException e) {
295             if (retryCount > 0) {
296                 logger.debug("Request timedout, retry counter : {}", retryCount);
297                 return executeUri(uri, method, clazz, payload, contentType, retryCount - 1);
298             }
299             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "@text/request-time-out");
300             prepareReconnection(null, null);
301             throw new NetatmoException(String.format("%s: \"%s\"", e.getClass().getName(), e.getMessage()));
302         }
303     }
304
305     public void identifyAllModulesAndApplyAction(BiFunction<NAModule, ThingUID, Optional<ThingUID>> action) {
306         ThingUID accountUID = getThing().getUID();
307         try {
308             AircareApi airCareApi = getRestManager(AircareApi.class);
309             if (airCareApi != null) { // Search Healthy Home Coaches
310                 ListBodyResponse<NAMain> body = airCareApi.getHomeCoachData(null).getBody();
311                 if (body != null) {
312                     body.getElements().stream().forEach(homeCoach -> action.apply(homeCoach, accountUID));
313                 }
314             }
315             WeatherApi weatherApi = getRestManager(WeatherApi.class);
316             if (weatherApi != null) { // Search owned or favorite stations
317                 weatherApi.getFavoriteAndGuestStationsData().stream().forEach(station -> {
318                     if (!station.isReadOnly() || getReadFriends()) {
319                         action.apply(station, accountUID).ifPresent(stationUID -> station.getModules().values().stream()
320                                 .forEach(module -> action.apply(module, stationUID)));
321                     }
322                 });
323             }
324             HomeApi homeApi = getRestManager(HomeApi.class);
325             if (homeApi != null) { // Search those depending from a home that has modules + not only weather modules
326                 homeApi.getHomesData(null, null).stream()
327                         .filter(h -> !(h.getFeatures().isEmpty()
328                                 || h.getFeatures().contains(FeatureArea.WEATHER) && h.getFeatures().size() == 1))
329                         .forEach(home -> {
330                             action.apply(home, accountUID).ifPresent(homeUID -> {
331                                 home.getKnownPersons().forEach(person -> action.apply(person, homeUID));
332
333                                 Map<String, ThingUID> bridgesUids = new HashMap<>();
334
335                                 home.getRooms().values().stream().forEach(room -> {
336                                     room.getModuleIds().stream().map(id -> home.getModules().get(id))
337                                             .map(m -> m != null ? m.getType().feature : FeatureArea.NONE)
338                                             .filter(f -> FeatureArea.ENERGY.equals(f)).findAny().ifPresent(f -> {
339                                                 action.apply(room, homeUID)
340                                                         .ifPresent(roomUID -> bridgesUids.put(room.getId(), roomUID));
341                                             });
342                                 });
343
344                                 // Creating modules that have no bridge first, avoiding weather station itself
345                                 home.getModules().values().stream()
346                                         .filter(module -> module.getType().feature != FeatureArea.WEATHER)
347                                         .sorted(comparing(HomeDataModule::getBridge, nullsFirst(naturalOrder())))
348                                         .forEach(module -> {
349                                             String bridgeId = module.getBridge();
350                                             if (bridgeId == null) {
351                                                 action.apply(module, homeUID).ifPresent(
352                                                         moduleUID -> bridgesUids.put(module.getId(), moduleUID));
353                                             } else {
354                                                 action.apply(module, bridgesUids.getOrDefault(bridgeId, homeUID));
355                                             }
356                                         });
357                             });
358                         });
359             }
360         } catch (NetatmoException e) {
361             logger.warn("Error while identifying all modules : {}", e.getMessage());
362         }
363     }
364
365     public boolean getReadFriends() {
366         return bindingConf.readFriends;
367     }
368
369     public boolean isConnected() {
370         return connectApi.isConnected();
371     }
372
373     public String getId() {
374         return (String) getThing().getConfiguration().get(ApiHandlerConfiguration.CLIENT_ID);
375     }
376
377     public UriBuilder formatAuthorizationUrl() {
378         return AuthenticationApi.getAuthorizationBuilder(getId());
379     }
380
381     @Override
382     public Collection<Class<? extends ThingHandlerService>> getServices() {
383         return Set.of(NetatmoDiscoveryService.class);
384     }
385
386     public Optional<WebhookServlet> getWebHookServlet() {
387         return Optional.ofNullable(webHookServlet);
388     }
389 }