2 * Copyright (c) 2010-2022 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.gardena.internal;
15 import java.util.Collection;
16 import java.util.HashMap;
17 import java.util.Iterator;
20 import java.util.concurrent.ConcurrentHashMap;
21 import java.util.concurrent.ExecutionException;
22 import java.util.concurrent.ScheduledExecutorService;
23 import java.util.concurrent.ScheduledFuture;
24 import java.util.concurrent.TimeUnit;
25 import java.util.concurrent.TimeoutException;
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.eclipse.jetty.client.HttpClient;
30 import org.eclipse.jetty.client.api.ContentResponse;
31 import org.eclipse.jetty.client.api.Request;
32 import org.eclipse.jetty.client.util.AbstractTypedContentProvider;
33 import org.eclipse.jetty.client.util.FormContentProvider;
34 import org.eclipse.jetty.client.util.StringContentProvider;
35 import org.eclipse.jetty.http.HttpHeader;
36 import org.eclipse.jetty.http.HttpMethod;
37 import org.eclipse.jetty.util.Fields;
38 import org.eclipse.jetty.websocket.client.WebSocketClient;
39 import org.openhab.binding.gardena.internal.config.GardenaConfig;
40 import org.openhab.binding.gardena.internal.exception.GardenaDeviceNotFoundException;
41 import org.openhab.binding.gardena.internal.exception.GardenaException;
42 import org.openhab.binding.gardena.internal.model.DataItemDeserializer;
43 import org.openhab.binding.gardena.internal.model.dto.Device;
44 import org.openhab.binding.gardena.internal.model.dto.api.CreateWebSocketRequest;
45 import org.openhab.binding.gardena.internal.model.dto.api.DataItem;
46 import org.openhab.binding.gardena.internal.model.dto.api.Location;
47 import org.openhab.binding.gardena.internal.model.dto.api.LocationDataItem;
48 import org.openhab.binding.gardena.internal.model.dto.api.LocationResponse;
49 import org.openhab.binding.gardena.internal.model.dto.api.LocationsResponse;
50 import org.openhab.binding.gardena.internal.model.dto.api.PostOAuth2Response;
51 import org.openhab.binding.gardena.internal.model.dto.api.WebSocket;
52 import org.openhab.binding.gardena.internal.model.dto.api.WebSocketCreatedResponse;
53 import org.openhab.binding.gardena.internal.model.dto.command.GardenaCommand;
54 import org.openhab.binding.gardena.internal.model.dto.command.GardenaCommandRequest;
55 import org.openhab.core.io.net.http.HttpClientFactory;
56 import org.openhab.core.io.net.http.WebSocketFactory;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
60 import com.google.gson.Gson;
61 import com.google.gson.GsonBuilder;
62 import com.google.gson.JsonSyntaxException;
65 * {@link GardenaSmart} implementation to access Gardena smart system.
67 * @author Gerhard Riegler - Initial contribution
70 public class GardenaSmartImpl implements GardenaSmart, GardenaSmartWebSocketListener {
71 private final Logger logger = LoggerFactory.getLogger(GardenaSmartImpl.class);
73 private Gson gson = new GsonBuilder().registerTypeAdapter(DataItem.class, new DataItemDeserializer()).create();
75 private static final String URL_API_HUSQUARNA = "https://api.authentication.husqvarnagroup.dev/v1";
76 private static final String URL_API_GARDENA = "https://api.smart.gardena.dev/v1";
77 private static final String URL_API_TOKEN = URL_API_HUSQUARNA + "/oauth2/token";
78 private static final String URL_API_WEBSOCKET = URL_API_GARDENA + "/websocket";
79 private static final String URL_API_LOCATIONS = URL_API_GARDENA + "/locations";
80 private static final String URL_API_COMMAND = URL_API_GARDENA + "/command";
83 private GardenaConfig config;
84 private ScheduledExecutorService scheduler;
86 private Map<String, Device> allDevicesById = new HashMap<>();
87 private LocationsResponse locationsResponse;
88 private GardenaSmartEventListener eventListener;
90 private HttpClient httpClient;
91 private Map<String, GardenaSmartWebSocket> webSockets = new HashMap<>();
92 private @Nullable PostOAuth2Response token;
93 private boolean initialized = false;
94 private WebSocketClient webSocketClient;
96 private Set<Device> devicesToNotify = ConcurrentHashMap.newKeySet();
97 private @Nullable ScheduledFuture<?> deviceToNotifyFuture;
98 private @Nullable ScheduledFuture<?> newDeviceFuture;
100 public GardenaSmartImpl(String id, GardenaConfig config, GardenaSmartEventListener eventListener,
101 ScheduledExecutorService scheduler, HttpClientFactory httpClientFactory, WebSocketFactory webSocketFactory)
102 throws GardenaException {
104 this.config = config;
105 this.eventListener = eventListener;
106 this.scheduler = scheduler;
108 logger.debug("Starting GardenaSmart");
110 httpClient = httpClientFactory.createHttpClient(id);
111 httpClient.setConnectTimeout(config.getConnectionTimeout() * 1000L);
112 httpClient.setIdleTimeout(httpClient.getConnectTimeout());
115 String webSocketId = String.valueOf(hashCode());
116 webSocketClient = webSocketFactory.createWebSocketClient(webSocketId);
117 webSocketClient.setConnectTimeout(config.getConnectionTimeout() * 1000L);
118 webSocketClient.setStopTimeout(3000);
119 webSocketClient.setMaxIdleTimeout(150000);
120 webSocketClient.start();
122 // initially load access token
124 locationsResponse = loadLocations();
127 for (LocationDataItem location : locationsResponse.data) {
128 LocationResponse locationResponse = loadLocation(location.id);
129 if (locationResponse.included != null) {
130 for (DataItem<?> dataItem : locationResponse.included) {
131 handleDataItem(dataItem);
136 for (Device device : allDevicesById.values()) {
137 device.evaluateDeviceType();
142 } catch (GardenaException ex) {
144 // pass GardenaException to calling function
146 } catch (Exception ex) {
148 throw new GardenaException(ex.getMessage(), ex);
153 * Starts the websockets for each location.
155 private void startWebsockets() throws Exception {
156 for (LocationDataItem location : locationsResponse.data) {
157 WebSocketCreatedResponse webSocketCreatedResponse = getWebsocketInfo(location.id);
158 Location locationAttributes = location.attributes;
159 WebSocket webSocketAttributes = webSocketCreatedResponse.data.attributes;
160 if (locationAttributes == null || webSocketAttributes == null) {
163 String socketId = id + "-" + locationAttributes.name;
164 webSockets.put(location.id, new GardenaSmartWebSocket(this, webSocketClient, scheduler,
165 webSocketAttributes.url, token, socketId, location.id));
170 * Stops all websockets.
172 private void stopWebsockets() {
173 for (GardenaSmartWebSocket webSocket : webSockets.values()) {
180 * Communicates with Gardena smart home system and parses the result.
182 private <T> T executeRequest(HttpMethod method, String url, @Nullable Object content, @Nullable Class<T> result)
183 throws GardenaException {
185 AbstractTypedContentProvider contentProvider = null;
186 String contentType = "application/vnd.api+json";
187 if (content != null) {
188 if (content instanceof Fields) {
189 contentProvider = new FormContentProvider((Fields) content);
190 contentType = "application/x-www-form-urlencoded";
192 contentProvider = new StringContentProvider(gson.toJson(content));
196 if (logger.isTraceEnabled()) {
197 logger.trace(">>> {} {}, data: {}", method, url, content == null ? null : gson.toJson(content));
200 Request request = httpClient.newRequest(url).method(method).header(HttpHeader.CONTENT_TYPE, contentType)
201 .header(HttpHeader.ACCEPT, "application/vnd.api+json").header(HttpHeader.ACCEPT_ENCODING, "gzip");
203 if (!URL_API_TOKEN.equals(url)) {
205 final PostOAuth2Response token = this.token;
207 request.header("Authorization", token.tokenType + " " + token.accessToken);
208 request.header("Authorization-provider", token.provider);
210 request.header("X-Api-Key", config.getApiKey());
213 request.content(contentProvider);
214 ContentResponse contentResponse = request.send();
215 int status = contentResponse.getStatus();
216 if (logger.isTraceEnabled()) {
217 logger.trace("<<< status:{}, {}", status, contentResponse.getContentAsString());
220 if (status != 200 && status != 204 && status != 201 && status != 202) {
221 throw new GardenaException(String.format("Error %s %s, %s", status, contentResponse.getReason(),
222 contentResponse.getContentAsString()), status);
225 if (result == null) {
228 return (T) gson.fromJson(contentResponse.getContentAsString(), result);
229 } catch (InterruptedException | TimeoutException | ExecutionException ex) {
230 throw new GardenaException(ex.getMessage(), ex);
235 * Creates or refreshes the access token for the Gardena smart system.
237 private synchronized void verifyToken() throws GardenaException {
238 Fields fields = new Fields();
239 fields.add("client_id", config.getApiKey());
241 PostOAuth2Response token = this.token;
242 if (token == null || token.isRefreshTokenExpired()) {
244 logger.debug("Gardena API login using apiSecret, reason: {}",
245 token == null ? "no token available" : "refresh token expired");
246 fields.add("grant_type", "client_credentials");
247 fields.add("client_secret", config.getApiSecret());
248 token = executeRequest(HttpMethod.POST, URL_API_TOKEN, fields, PostOAuth2Response.class);
251 } else if (token.isAccessTokenExpired()) {
253 logger.debug("Gardena API login using refreshToken, reason: access token expired");
254 fields.add("grant_type", "refresh_token");
255 fields.add("refresh_token", token.refreshToken);
257 PostOAuth2Response tempToken = executeRequest(HttpMethod.POST, URL_API_TOKEN, fields,
258 PostOAuth2Response.class);
259 token.accessToken = tempToken.accessToken;
260 token.expiresIn = tempToken.expiresIn;
263 } catch (GardenaException ex) {
264 // refresh token issue
269 logger.debug("Gardena API token valid");
271 logger.debug("{}", token.toString());
275 * Loads all locations.
277 private LocationsResponse loadLocations() throws GardenaException {
278 return executeRequest(HttpMethod.GET, URL_API_LOCATIONS, null, LocationsResponse.class);
282 * Loads all devices for a given location.
284 private LocationResponse loadLocation(String locationId) throws GardenaException {
285 return executeRequest(HttpMethod.GET, URL_API_LOCATIONS + "/" + locationId, null, LocationResponse.class);
289 * Returns the websocket url for a given location.
291 private WebSocketCreatedResponse getWebsocketInfo(String locationId) throws GardenaException {
292 return executeRequest(HttpMethod.POST, URL_API_WEBSOCKET, new CreateWebSocketRequest(locationId),
293 WebSocketCreatedResponse.class);
300 public void dispose() {
301 logger.debug("Disposing GardenaSmart");
303 final ScheduledFuture<?> newDeviceFuture = this.newDeviceFuture;
304 if (newDeviceFuture != null) {
305 newDeviceFuture.cancel(true);
308 final ScheduledFuture<?> deviceToNotifyFuture = this.deviceToNotifyFuture;
309 if (deviceToNotifyFuture != null) {
310 deviceToNotifyFuture.cancel(true);
315 webSocketClient.stop();
316 } catch (Exception e) {
319 httpClient.destroy();
320 webSocketClient.destroy();
321 locationsResponse = new LocationsResponse();
322 allDevicesById.clear();
327 * Restarts all websockets.
330 public synchronized void restartWebsockets() {
331 logger.debug("Restarting GardenaSmart Webservices");
335 } catch (Exception ex) {
337 if (logger.isDebugEnabled()) {
338 logger.warn("Restarting GardenaSmart Webservices failed! Restarting binding", ex);
340 logger.warn("Restarting GardenaSmart Webservices failed: {}! Restarting binding", ex.getMessage());
342 eventListener.onError();
347 * Sets the dataItem from the websocket event into the correct device.
349 private void handleDataItem(final DataItem<?> dataItem) throws GardenaException {
350 final String deviceId = dataItem.getDeviceId();
351 Device device = allDevicesById.get(deviceId);
352 if (device == null && !(dataItem instanceof LocationDataItem)) {
353 device = new Device(deviceId);
354 allDevicesById.put(device.id, device);
357 newDeviceFuture = scheduler.schedule(() -> {
358 Device newDevice = allDevicesById.get(deviceId);
359 if (newDevice != null) {
360 newDevice.evaluateDeviceType();
361 if (newDevice.deviceType != null) {
362 eventListener.onNewDevice(newDevice);
365 }, 3, TimeUnit.SECONDS);
369 if (device != null) {
370 device.setDataItem(dataItem);
375 public void onWebSocketClose(String id) {
376 restartWebsocket(webSockets.get(id));
380 public void onWebSocketError(String id) {
381 restartWebsocket(webSockets.get(id));
384 private void restartWebsocket(@Nullable GardenaSmartWebSocket socket) {
385 synchronized (this) {
386 if (socket != null && !socket.isClosing()) {
387 // close socket, if still open
388 logger.info("Restarting GardenaSmart Webservice ({})", socket.getSocketID());
391 // if socket is already closing, exit function and do not restart socket
398 WebSocketCreatedResponse webSocketCreatedResponse = getWebsocketInfo(socket.getLocationID());
399 // only restart single socket, do not restart binding
400 WebSocket webSocketAttributes = webSocketCreatedResponse.data.attributes;
401 if (webSocketAttributes != null) {
402 socket.restart(webSocketAttributes.url);
404 } catch (Exception ex) {
405 // restart binding on error
406 logger.warn("Restarting GardenaSmart Webservice failed ({}): {}, restarting binding", socket.getSocketID(),
408 eventListener.onError();
413 public void onWebSocketMessage(String msg) {
415 DataItem<?> dataItem = gson.fromJson(msg, DataItem.class);
416 if (dataItem != null) {
417 handleDataItem(dataItem);
418 Device device = allDevicesById.get(dataItem.getDeviceId());
419 if (device != null && device.active) {
420 devicesToNotify.add(device);
422 // delay the deviceUpdated event to filter multiple events for the same device dataItem property
423 if (deviceToNotifyFuture == null) {
424 deviceToNotifyFuture = scheduler.schedule(() -> {
425 deviceToNotifyFuture = null;
426 Iterator<Device> notifyIterator = devicesToNotify.iterator();
427 while (notifyIterator.hasNext()) {
428 eventListener.onDeviceUpdated(notifyIterator.next());
429 notifyIterator.remove();
431 }, 1, TimeUnit.SECONDS);
435 } catch (GardenaException | JsonSyntaxException ex) {
436 logger.warn("Ignoring message: {}", ex.getMessage());
441 public Device getDevice(String deviceId) throws GardenaDeviceNotFoundException {
442 Device device = allDevicesById.get(deviceId);
443 if (device == null) {
444 throw new GardenaDeviceNotFoundException("Device with id " + deviceId + " not found");
450 public void sendCommand(DataItem<?> dataItem, GardenaCommand gardenaCommand) throws GardenaException {
451 executeRequest(HttpMethod.PUT, URL_API_COMMAND + "/" + dataItem.id, new GardenaCommandRequest(gardenaCommand),
456 public String getId() {
461 public Collection<Device> getAllDevices() {
462 return allDevicesById.values();