2 * Copyright (c) 2010-2024 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.bticinosmarther.internal.api;
15 import static org.eclipse.jetty.http.HttpMethod.*;
16 import static org.openhab.binding.bticinosmarther.internal.SmartherBindingConstants.*;
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;
24 import java.util.Objects;
25 import java.util.concurrent.ScheduledExecutorService;
26 import java.util.function.Function;
28 import javax.measure.quantity.Temperature;
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;
62 import com.google.gson.JsonSyntaxException;
63 import com.google.gson.reflect.TypeToken;
66 * The {@code SmartherApi} class is used to communicate with the BTicino/Legrand API gateway.
68 * @author Fabio Possieri - Initial contribution
71 public class SmartherApi {
73 private static final String CONTENT_TYPE = "application/json";
74 private static final String BEARER = "Bearer ";
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";
97 private final Logger logger = LoggerFactory.getLogger(SmartherApi.class);
99 private final OAuthClientService oAuthClientService;
100 private final String oAuthSubscriptionKey;
101 private final SmartherApiConnector connector;
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.
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
112 * the scheduler to be used to reschedule calls when rate limit exceeded or call not succeeded
114 * the http client to be used to make http calls to the API gateway
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);
124 * Returns the plants registered under the Smarther account the bridge has been configured with.
126 * @return the list of registered plants, or an empty {@link List} in case of no plants found
128 * @throws SmartherGatewayException in case of communication issues with the API gateway
130 public List<Plant> getPlants() throws SmartherGatewayException {
132 final ContentResponse response = requestBasic(GET, PATH_PLANTS);
133 if (response.getStatus() == HttpStatus.NO_CONTENT_204) {
134 return new ArrayList<>();
136 return ModelUtil.gsonInstance().fromJson(response.getContentAsString(), Plants.class).getPlants();
138 } catch (JsonSyntaxException e) {
139 throw new SmartherGatewayException(e.getMessage());
144 * Returns the chronothermostat modules registered in the given plant.
147 * the identifier of the plant
149 * @return the list of registered modules, or an empty {@link List} in case the plant contains no module
151 * @throws SmartherGatewayException in case of communication issues with the API gateway
153 public List<Module> getPlantModules(String plantId) throws SmartherGatewayException {
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());
164 * Returns the current status of a given chronothermostat module.
167 * the identifier of the plant
169 * the identifier of the chronothermostat module inside the plant
171 * @return the current status of the chronothermostat module
173 * @throws SmartherGatewayException in case of communication issues with the API gateway
175 public ModuleStatus getModuleStatus(String plantId, String moduleId) throws SmartherGatewayException {
177 final ContentResponse response = requestModule(GET, plantId, moduleId, null);
178 ModuleStatus moduleStatus = ModelUtil.gsonInstance().fromJson(response.getContentAsString(),
180 return Objects.requireNonNull(moduleStatus);
181 } catch (JsonSyntaxException e) {
182 throw new SmartherGatewayException(e.getMessage());
187 * Sends new settings to be applied to a given chronothermostat module.
190 * the module settings to be applied
192 * @return {@code true} if the settings have been successfully applied, {@code false} otherwise
194 * @throws SmartherGatewayException in case of communication issues with the API gateway
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()) {
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);
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");
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());
223 // {"function":"heating","mode":"boost","activationTime":"X"}
224 rootMap.put(ATTR_ACTIVATION_TIME, settings.getActivationTime());
227 // {"function":"heating","mode":"off"}
230 // {"function":"heating","mode":"protection"}
233 final String jsonPayload = ModelUtil.gsonInstance().toJson(rootMap);
235 // Send request to server
236 final ContentResponse response = requestModule(POST, settings.getPlantId(), settings.getModuleId(),
238 return (response.getStatus() == HttpStatus.OK_200);
242 * Returns the automatic mode programs registered for the given chronothermostat module.
245 * the identifier of the plant
247 * the identifier of the chronothermostat module inside the plant
249 * @return the list of registered programs, or an empty {@link List} in case of no programs found
251 * @throws SmartherGatewayException in case of communication issues with the API gateway
253 public List<Program> getModulePrograms(String plantId, String moduleId) throws SmartherGatewayException {
255 final ContentResponse response = requestModule(GET, plantId, moduleId, PATH_PROGRAMS, null);
256 final ModuleStatus moduleStatus = ModelUtil.gsonInstance().fromJson(response.getContentAsString(),
259 final Chronothermostat chronothermostat = moduleStatus.toChronothermostat();
260 return (chronothermostat != null) ? chronothermostat.getPrograms() : Collections.emptyList();
261 } catch (JsonSyntaxException e) {
262 throw new SmartherGatewayException(e.getMessage());
267 * Returns the subscriptions registered to the C2C Webhook, where modules status notifications are currently sent
268 * for all the plants.
270 * @return the list of registered subscriptions, or an empty {@link List} in case of no subscriptions found
272 * @throws SmartherGatewayException in case of communication issues with the API gateway
274 public List<Subscription> getSubscriptions() throws SmartherGatewayException {
276 final ContentResponse response = requestBasic(GET, PATH_SUBSCRIPTIONS);
277 if (response.getStatus() == HttpStatus.NO_CONTENT_204) {
278 return new ArrayList<>();
280 List<Subscription> subscriptions = ModelUtil.gsonInstance().fromJson(response.getContentAsString(),
281 new TypeToken<List<Subscription>>() {
283 if (subscriptions == null) {
284 throw new SmartherGatewayException("fromJson returned null");
286 return subscriptions;
288 } catch (JsonSyntaxException e) {
289 throw new SmartherGatewayException(e.getMessage());
294 * Subscribes a plant to the C2C Webhook to start receiving modules status notifications.
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
301 * @return the identifier this subscription has been registered under
303 * @throws SmartherGatewayException in case of communication issues with the API gateway
305 public String subscribePlant(String plantId, String notificationUrl) throws SmartherGatewayException {
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(),
316 return subscription.getSubscriptionId();
317 } catch (JsonSyntaxException e) {
318 throw new SmartherGatewayException(e.getMessage());
323 * Unsubscribes a plant from the C2C Webhook to stop receiving modules status notifications.
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
330 * @return {@code true} if the plant is successfully unsubscribed, {@code false} otherwise
332 * @throws SmartherGatewayException in case of communication issues with the API gateway
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);
339 // ===========================================================================
341 // Internal API call handling methods
343 // ===========================================================================
346 * Calls the API gateway with the given http method, request url and actual data.
349 * the http method to make the call with
351 * the API operation url to call
353 * the actual data to send in the request body, may be {@code null}
355 * @return the response received from the API gateway
357 * @throws {@link SmartherGatewayException}
358 * in case of communication issues with the API gateway
360 private ContentResponse requestBasic(HttpMethod method, String url, @Nullable String requestData)
361 throws SmartherGatewayException {
362 return request(method, SMARTHER_API_URL + url, requestData);
366 * Calls the API gateway with the given http method and request url.
369 * the http method to make the call with
371 * the API operation url to call
373 * @return the response received from the API gateway
375 * @throws {@link SmartherGatewayException}
376 * in case of communication issues with the API gateway
378 private ContentResponse requestBasic(HttpMethod method, String url) throws SmartherGatewayException {
379 return requestBasic(method, url, null);
383 * Calls the API gateway with the given http method, plant id, module id, request path and actual data.
386 * the http method to make the call with
388 * the identifier of the plant to use
390 * the identifier of the module to use
392 * the API operation relative path to call, may be {@code null}
394 * the actual data to send in the request body, may be {@code null}
396 * @return the response received from the API gateway
398 * @throws {@link SmartherGatewayException}
399 * in case of communication issues with the API gateway
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);
408 * Calls the API gateway with the given http method, plant id, module id and actual data.
411 * the http method to make the call with
413 * the identifier of the plant to use
415 * the identifier of the module to use
417 * the actual data to send in the request body, may be {@code null}
419 * @return the response received from the API gateway
421 * @throws {@link SmartherGatewayException}
422 * in case of communication issues with the API gateway
424 private ContentResponse requestModule(HttpMethod method, String plantId, String moduleId,
425 @Nullable String requestData) throws SmartherGatewayException {
426 return requestModule(method, plantId, moduleId, null, requestData);
430 * Calls the API gateway with the given http method, request url and actual data.
433 * the http method to make the call with
435 * the API operation url to call
437 * the actual data to send in the request body, may be {@code null}
439 * @return the response received from the API gateway
441 * @throws {@link SmartherGatewayException}
442 * in case of communication issues with the API gateway
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);
452 final AccessTokenResponse accessTokenResponse = oAuthClientService.getAccessTokenResponse();
453 final String accessToken = (accessTokenResponse == null) ? null : accessTokenResponse.getAccessToken();
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));
459 return requestWithRetry(call, accessToken);
461 } catch (SmartherGatewayException e) {
463 } catch (OAuthException | OAuthResponseException e) {
464 throw new SmartherAuthorizationException(e.getMessage(), e);
465 } catch (IOException e) {
466 throw new SmartherGatewayException(e.getMessage(), e);
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).
475 * the http call to make
477 * the authorization access token to use
479 * @return the response received from the API gateway
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
488 private ContentResponse requestWithRetry(final Function<HttpClient, Request> call, final String accessToken)
489 throws OAuthException, OAuthResponseException, IOException {
491 return this.connector.request(call, this.oAuthSubscriptionKey, BEARER + accessToken);
492 } catch (SmartherTokenExpiredException e) {
493 // Retry with new access token
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()));