]> git.basschouten.com Git - openhab-addons.git/blob
c9d1c167bd326c5f7c103476b6a603941921152b
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.bticinosmarther.internal.api;
14
15 import static org.eclipse.jetty.http.HttpMethod.*;
16 import static org.openhab.binding.bticinosmarther.internal.SmartherBindingConstants.*;
17
18 import java.io.IOException;
19 import java.util.ArrayList;
20 import java.util.Collections;
21 import java.util.IdentityHashMap;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Objects;
25 import java.util.concurrent.ScheduledExecutorService;
26 import java.util.function.Function;
27
28 import javax.measure.quantity.Temperature;
29
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.eclipse.jetty.client.HttpClient;
33 import org.eclipse.jetty.client.api.ContentResponse;
34 import org.eclipse.jetty.client.api.Request;
35 import org.eclipse.jetty.client.util.StringContentProvider;
36 import org.eclipse.jetty.http.HttpMethod;
37 import org.eclipse.jetty.http.HttpStatus;
38 import org.openhab.binding.bticinosmarther.internal.api.dto.Chronothermostat;
39 import org.openhab.binding.bticinosmarther.internal.api.dto.Enums.MeasureUnit;
40 import org.openhab.binding.bticinosmarther.internal.api.dto.Module;
41 import org.openhab.binding.bticinosmarther.internal.api.dto.ModuleStatus;
42 import org.openhab.binding.bticinosmarther.internal.api.dto.Plant;
43 import org.openhab.binding.bticinosmarther.internal.api.dto.Plants;
44 import org.openhab.binding.bticinosmarther.internal.api.dto.Program;
45 import org.openhab.binding.bticinosmarther.internal.api.dto.Subscription;
46 import org.openhab.binding.bticinosmarther.internal.api.dto.Topology;
47 import org.openhab.binding.bticinosmarther.internal.api.exception.SmartherAuthorizationException;
48 import org.openhab.binding.bticinosmarther.internal.api.exception.SmartherGatewayException;
49 import org.openhab.binding.bticinosmarther.internal.api.exception.SmartherTokenExpiredException;
50 import org.openhab.binding.bticinosmarther.internal.model.ModuleSettings;
51 import org.openhab.binding.bticinosmarther.internal.util.ModelUtil;
52 import org.openhab.binding.bticinosmarther.internal.util.StringUtil;
53 import org.openhab.core.auth.client.oauth2.AccessTokenResponse;
54 import org.openhab.core.auth.client.oauth2.OAuthClientService;
55 import org.openhab.core.auth.client.oauth2.OAuthException;
56 import org.openhab.core.auth.client.oauth2.OAuthResponseException;
57 import org.openhab.core.library.types.QuantityType;
58 import org.openhab.core.library.unit.SIUnits;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 import com.google.gson.JsonSyntaxException;
63 import com.google.gson.reflect.TypeToken;
64
65 /**
66  * The {@code SmartherApi} class is used to communicate with the BTicino/Legrand API gateway.
67  *
68  * @author Fabio Possieri - Initial contribution
69  */
70 @NonNullByDefault
71 public class SmartherApi {
72
73     private static final String CONTENT_TYPE = "application/json";
74     private static final String BEARER = "Bearer ";
75
76     // API gateway request headers
77     private static final String HEADER_ACCEPT = "Accept";
78     // API gateway request attributes
79     private static final String ATTR_FUNCTION = "function";
80     private static final String ATTR_MODE = "mode";
81     private static final String ATTR_PROGRAMS = "programs";
82     private static final String ATTR_NUMBER = "number";
83     private static final String ATTR_SETPOINT = "setPoint";
84     private static final String ATTR_VALUE = "value";
85     private static final String ATTR_UNIT = "unit";
86     private static final String ATTR_ACTIVATION_TIME = "activationTime";
87     private static final String ATTR_ENDPOINT_URL = "EndPointUrl";
88     // API gateway operation paths
89     private static final String PATH_PLANTS = "/plants";
90     private static final String PATH_TOPOLOGY = PATH_PLANTS + "/%s/topology";
91     private static final String PATH_MODULE = "/chronothermostat/thermoregulation/addressLocation/plants/%s/modules/parameter/id/value/%s";
92     private static final String PATH_PROGRAMS = "/programlist";
93     private static final String PATH_SUBSCRIPTIONS = "/subscription";
94     private static final String PATH_SUBSCRIBE = PATH_PLANTS + "/%s/subscription";
95     private static final String PATH_UNSUBSCRIBE = PATH_SUBSCRIBE + "/%s";
96
97     private final Logger logger = LoggerFactory.getLogger(SmartherApi.class);
98
99     private final OAuthClientService oAuthClientService;
100     private final String oAuthSubscriptionKey;
101     private final SmartherApiConnector connector;
102
103     /**
104      * Constructs a {@code SmartherApi} to the API gateway with the specified OAuth2 attributes (subscription key and
105      * client service), scheduler service and http client.
106      *
107      * @param clientService
108      *            the OAuth2 authorization client service to be used
109      * @param subscriptionKey
110      *            the OAuth2 subscription key to be used with the given client service
111      * @param scheduler
112      *            the scheduler to be used to reschedule calls when rate limit exceeded or call not succeeded
113      * @param httpClient
114      *            the http client to be used to make http calls to the API gateway
115      */
116     public SmartherApi(final OAuthClientService clientService, final String subscriptionKey,
117             final ScheduledExecutorService scheduler, final HttpClient httpClient) {
118         this.oAuthClientService = clientService;
119         this.oAuthSubscriptionKey = subscriptionKey;
120         this.connector = new SmartherApiConnector(scheduler, httpClient);
121     }
122
123     /**
124      * Returns the plants registered under the Smarther account the bridge has been configured with.
125      *
126      * @return the list of registered plants, or an empty {@link List} in case of no plants found
127      *
128      * @throws SmartherGatewayException in case of communication issues with the API gateway
129      */
130     public List<Plant> getPlants() throws SmartherGatewayException {
131         try {
132             final ContentResponse response = requestBasic(GET, PATH_PLANTS);
133             if (response.getStatus() == HttpStatus.NO_CONTENT_204) {
134                 return new ArrayList<>();
135             } else {
136                 return ModelUtil.gsonInstance().fromJson(response.getContentAsString(), Plants.class).getPlants();
137             }
138         } catch (JsonSyntaxException e) {
139             throw new SmartherGatewayException(e.getMessage());
140         }
141     }
142
143     /**
144      * Returns the chronothermostat modules registered in the given plant.
145      *
146      * @param plantId
147      *            the identifier of the plant
148      *
149      * @return the list of registered modules, or an empty {@link List} in case the plant contains no module
150      *
151      * @throws SmartherGatewayException in case of communication issues with the API gateway
152      */
153     public List<Module> getPlantModules(String plantId) throws SmartherGatewayException {
154         try {
155             final ContentResponse response = requestBasic(GET, String.format(PATH_TOPOLOGY, plantId));
156             final Topology topology = ModelUtil.gsonInstance().fromJson(response.getContentAsString(), Topology.class);
157             return topology.getModules();
158         } catch (JsonSyntaxException e) {
159             throw new SmartherGatewayException(e.getMessage());
160         }
161     }
162
163     /**
164      * Returns the current status of a given chronothermostat module.
165      *
166      * @param plantId
167      *            the identifier of the plant
168      * @param moduleId
169      *            the identifier of the chronothermostat module inside the plant
170      *
171      * @return the current status of the chronothermostat module
172      *
173      * @throws SmartherGatewayException in case of communication issues with the API gateway
174      */
175     public ModuleStatus getModuleStatus(String plantId, String moduleId) throws SmartherGatewayException {
176         try {
177             final ContentResponse response = requestModule(GET, plantId, moduleId, null);
178             ModuleStatus moduleStatus = ModelUtil.gsonInstance().fromJson(response.getContentAsString(),
179                     ModuleStatus.class);
180             return Objects.requireNonNull(moduleStatus);
181         } catch (JsonSyntaxException e) {
182             throw new SmartherGatewayException(e.getMessage());
183         }
184     }
185
186     /**
187      * Sends new settings to be applied to a given chronothermostat module.
188      *
189      * @param settings
190      *            the module settings to be applied
191      *
192      * @return {@code true} if the settings have been successfully applied, {@code false} otherwise
193      *
194      * @throws SmartherGatewayException in case of communication issues with the API gateway
195      */
196     public boolean setModuleStatus(ModuleSettings settings) throws SmartherGatewayException {
197         // Prepare request payload
198         Map<String, Object> rootMap = new IdentityHashMap<>();
199         rootMap.put(ATTR_FUNCTION, settings.getFunction().getValue());
200         rootMap.put(ATTR_MODE, settings.getMode().getValue());
201         switch (settings.getMode()) {
202             case AUTOMATIC:
203                 // {"function":"heating","mode":"automatic","programs":[{"number":0}]}
204                 Map<String, Integer> programMap = new IdentityHashMap<String, Integer>();
205                 programMap.put(ATTR_NUMBER, Integer.valueOf(settings.getProgram()));
206                 List<Map<String, Integer>> programsList = new ArrayList<>();
207                 programsList.add(programMap);
208                 rootMap.put(ATTR_PROGRAMS, programsList);
209                 break;
210             case MANUAL:
211                 // {"function":"heating","mode":"manual","setPoint":{"value":0.0,"unit":"C"},"activationTime":"X"}
212                 QuantityType<Temperature> newTemperature = settings.getSetPointTemperature(SIUnits.CELSIUS);
213                 if (newTemperature == null) {
214                     throw new SmartherGatewayException("Invalid temperature unit transformation");
215                 }
216                 Map<String, Object> setPointMap = new IdentityHashMap<String, Object>();
217                 setPointMap.put(ATTR_VALUE, newTemperature.doubleValue());
218                 setPointMap.put(ATTR_UNIT, MeasureUnit.CELSIUS.getValue());
219                 rootMap.put(ATTR_SETPOINT, setPointMap);
220                 rootMap.put(ATTR_ACTIVATION_TIME, settings.getActivationTime());
221                 break;
222             case BOOST:
223                 // {"function":"heating","mode":"boost","activationTime":"X"}
224                 rootMap.put(ATTR_ACTIVATION_TIME, settings.getActivationTime());
225                 break;
226             case OFF:
227                 // {"function":"heating","mode":"off"}
228                 break;
229             case PROTECTION:
230                 // {"function":"heating","mode":"protection"}
231                 break;
232         }
233         final String jsonPayload = ModelUtil.gsonInstance().toJson(rootMap);
234
235         // Send request to server
236         final ContentResponse response = requestModule(POST, settings.getPlantId(), settings.getModuleId(),
237                 jsonPayload);
238         return (response.getStatus() == HttpStatus.OK_200);
239     }
240
241     /**
242      * Returns the automatic mode programs registered for the given chronothermostat module.
243      *
244      * @param plantId
245      *            the identifier of the plant
246      * @param moduleId
247      *            the identifier of the chronothermostat module inside the plant
248      *
249      * @return the list of registered programs, or an empty {@link List} in case of no programs found
250      *
251      * @throws SmartherGatewayException in case of communication issues with the API gateway
252      */
253     public List<Program> getModulePrograms(String plantId, String moduleId) throws SmartherGatewayException {
254         try {
255             final ContentResponse response = requestModule(GET, plantId, moduleId, PATH_PROGRAMS, null);
256             final ModuleStatus moduleStatus = ModelUtil.gsonInstance().fromJson(response.getContentAsString(),
257                     ModuleStatus.class);
258
259             final Chronothermostat chronothermostat = moduleStatus.toChronothermostat();
260             return (chronothermostat != null) ? chronothermostat.getPrograms() : Collections.emptyList();
261         } catch (JsonSyntaxException e) {
262             throw new SmartherGatewayException(e.getMessage());
263         }
264     }
265
266     /**
267      * Returns the subscriptions registered to the C2C Webhook, where modules status notifications are currently sent
268      * for all the plants.
269      *
270      * @return the list of registered subscriptions, or an empty {@link List} in case of no subscriptions found
271      *
272      * @throws SmartherGatewayException in case of communication issues with the API gateway
273      */
274     public List<Subscription> getSubscriptions() throws SmartherGatewayException {
275         try {
276             final ContentResponse response = requestBasic(GET, PATH_SUBSCRIPTIONS);
277             if (response.getStatus() == HttpStatus.NO_CONTENT_204) {
278                 return new ArrayList<>();
279             } else {
280                 List<Subscription> subscriptions = ModelUtil.gsonInstance().fromJson(response.getContentAsString(),
281                         new TypeToken<List<Subscription>>() {
282                         }.getType());
283                 if (subscriptions == null) {
284                     throw new SmartherGatewayException("fromJson returned null");
285                 }
286                 return subscriptions;
287             }
288         } catch (JsonSyntaxException e) {
289             throw new SmartherGatewayException(e.getMessage());
290         }
291     }
292
293     /**
294      * Subscribes a plant to the C2C Webhook to start receiving modules status notifications.
295      *
296      * @param plantId
297      *            the identifier of the plant to be subscribed
298      * @param notificationUrl
299      *            the url notifications will have to be sent to for the given plant
300      *
301      * @return the identifier this subscription has been registered under
302      *
303      * @throws SmartherGatewayException in case of communication issues with the API gateway
304      */
305     public String subscribePlant(String plantId, String notificationUrl) throws SmartherGatewayException {
306         try {
307             // Prepare request payload
308             Map<String, Object> rootMap = new IdentityHashMap<String, Object>();
309             rootMap.put(ATTR_ENDPOINT_URL, notificationUrl);
310             final String jsonPayload = ModelUtil.gsonInstance().toJson(rootMap);
311             // Send request to server
312             final ContentResponse response = requestBasic(POST, String.format(PATH_SUBSCRIBE, plantId), jsonPayload);
313             // Handle response payload
314             final Subscription subscription = ModelUtil.gsonInstance().fromJson(response.getContentAsString(),
315                     Subscription.class);
316             return subscription.getSubscriptionId();
317         } catch (JsonSyntaxException e) {
318             throw new SmartherGatewayException(e.getMessage());
319         }
320     }
321
322     /**
323      * Unsubscribes a plant from the C2C Webhook to stop receiving modules status notifications.
324      *
325      * @param plantId
326      *            the identifier of the plant to be unsubscribed
327      * @param subscriptionId
328      *            the identifier of the subscription to be removed for the given plant
329      *
330      * @return {@code true} if the plant is successfully unsubscribed, {@code false} otherwise
331      *
332      * @throws SmartherGatewayException in case of communication issues with the API gateway
333      */
334     public boolean unsubscribePlant(String plantId, String subscriptionId) throws SmartherGatewayException {
335         final ContentResponse response = requestBasic(DELETE, String.format(PATH_UNSUBSCRIBE, plantId, subscriptionId));
336         return (response.getStatus() == HttpStatus.OK_200);
337     }
338
339     // ===========================================================================
340     //
341     // Internal API call handling methods
342     //
343     // ===========================================================================
344
345     /**
346      * Calls the API gateway with the given http method, request url and actual data.
347      *
348      * @param method
349      *            the http method to make the call with
350      * @param url
351      *            the API operation url to call
352      * @param requestData
353      *            the actual data to send in the request body, may be {@code null}
354      *
355      * @return the response received from the API gateway
356      *
357      * @throws {@link SmartherGatewayException}
358      *             in case of communication issues with the API gateway
359      */
360     private ContentResponse requestBasic(HttpMethod method, String url, @Nullable String requestData)
361             throws SmartherGatewayException {
362         return request(method, SMARTHER_API_URL + url, requestData);
363     }
364
365     /**
366      * Calls the API gateway with the given http method and request url.
367      *
368      * @param method
369      *            the http method to make the call with
370      * @param url
371      *            the API operation url to call
372      *
373      * @return the response received from the API gateway
374      *
375      * @throws {@link SmartherGatewayException}
376      *             in case of communication issues with the API gateway
377      */
378     private ContentResponse requestBasic(HttpMethod method, String url) throws SmartherGatewayException {
379         return requestBasic(method, url, null);
380     }
381
382     /**
383      * Calls the API gateway with the given http method, plant id, module id, request path and actual data.
384      *
385      * @param method
386      *            the http method to make the call with
387      * @param plantId
388      *            the identifier of the plant to use
389      * @param moduleId
390      *            the identifier of the module to use
391      * @param path
392      *            the API operation relative path to call, may be {@code null}
393      * @param requestData
394      *            the actual data to send in the request body, may be {@code null}
395      *
396      * @return the response received from the API gateway
397      *
398      * @throws {@link SmartherGatewayException}
399      *             in case of communication issues with the API gateway
400      */
401     private ContentResponse requestModule(HttpMethod method, String plantId, String moduleId, @Nullable String path,
402             @Nullable String requestData) throws SmartherGatewayException {
403         final String url = String.format(PATH_MODULE, plantId, moduleId) + StringUtil.defaultString(path);
404         return requestBasic(method, url, requestData);
405     }
406
407     /**
408      * Calls the API gateway with the given http method, plant id, module id and actual data.
409      *
410      * @param method
411      *            the http method to make the call with
412      * @param plantId
413      *            the identifier of the plant to use
414      * @param moduleId
415      *            the identifier of the module to use
416      * @param requestData
417      *            the actual data to send in the request body, may be {@code null}
418      *
419      * @return the response received from the API gateway
420      *
421      * @throws {@link SmartherGatewayException}
422      *             in case of communication issues with the API gateway
423      */
424     private ContentResponse requestModule(HttpMethod method, String plantId, String moduleId,
425             @Nullable String requestData) throws SmartherGatewayException {
426         return requestModule(method, plantId, moduleId, null, requestData);
427     }
428
429     /**
430      * Calls the API gateway with the given http method, request url and actual data.
431      *
432      * @param method
433      *            the http method to make the call with
434      * @param url
435      *            the API operation url to call
436      * @param requestData
437      *            the actual data to send in the request body, may be {@code null}
438      *
439      * @return the response received from the API gateway
440      *
441      * @throws {@link SmartherGatewayException}
442      *             in case of communication issues with the API gateway
443      */
444     private ContentResponse request(HttpMethod method, String url, @Nullable String requestData)
445             throws SmartherGatewayException {
446         logger.debug("Request: ({}) {} - {}", method, url, StringUtil.defaultString(requestData));
447         Function<HttpClient, Request> call = httpClient -> httpClient.newRequest(url).method(method)
448                 .header(HEADER_ACCEPT, CONTENT_TYPE)
449                 .content(new StringContentProvider(StringUtil.defaultString(requestData)), CONTENT_TYPE);
450
451         try {
452             final AccessTokenResponse accessTokenResponse = oAuthClientService.getAccessTokenResponse();
453             final String accessToken = (accessTokenResponse == null) ? null : accessTokenResponse.getAccessToken();
454
455             if (accessToken == null || accessToken.isEmpty()) {
456                 throw new SmartherAuthorizationException(String
457                         .format("No gateway accesstoken. Did you authorize smarther via %s ?", AUTH_SERVLET_ALIAS));
458             } else {
459                 return requestWithRetry(call, accessToken);
460             }
461         } catch (SmartherGatewayException e) {
462             throw e;
463         } catch (OAuthException | OAuthResponseException e) {
464             throw new SmartherAuthorizationException(e.getMessage(), e);
465         } catch (IOException e) {
466             throw new SmartherGatewayException(e.getMessage(), e);
467         }
468     }
469
470     /**
471      * Manages a generic call to the API gateway using the given authorization access token.
472      * Retries the call if the access token is expired (refreshing it on behalf of further calls).
473      *
474      * @param call
475      *            the http call to make
476      * @param accessToken
477      *            the authorization access token to use
478      *
479      * @return the response received from the API gateway
480      *
481      * @throws {@link OAuthException}
482      *             in case of issues during the OAuth process
483      * @throws {@link OAuthResponseException}
484      *             in case of response issues during the OAuth process
485      * @throws {@link IOException}
486      *             in case of I/O issues of some sort
487      */
488     private ContentResponse requestWithRetry(final Function<HttpClient, Request> call, final String accessToken)
489             throws OAuthException, OAuthResponseException, IOException {
490         try {
491             return this.connector.request(call, this.oAuthSubscriptionKey, BEARER + accessToken);
492         } catch (SmartherTokenExpiredException e) {
493             // Retry with new access token
494             try {
495                 return this.connector.request(call, this.oAuthSubscriptionKey,
496                         BEARER + this.oAuthClientService.refreshToken().getAccessToken());
497             } catch (SmartherTokenExpiredException ex) {
498                 // This should never happen in normal conditions
499                 throw new SmartherAuthorizationException(String.format("Cannot refresh token: %s", ex.getMessage()));
500             }
501         }
502     }
503 }