2 * Copyright (c) 2010-2023 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.ArrayList;
16 import java.util.Collection;
17 import java.util.HashMap;
18 import java.util.Iterator;
19 import java.util.List;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.concurrent.ExecutionException;
24 import java.util.concurrent.ScheduledExecutorService;
25 import java.util.concurrent.ScheduledFuture;
26 import java.util.concurrent.TimeUnit;
27 import java.util.concurrent.TimeoutException;
29 import org.eclipse.jdt.annotation.NonNullByDefault;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.eclipse.jetty.client.HttpClient;
32 import org.eclipse.jetty.client.api.ContentResponse;
33 import org.eclipse.jetty.client.api.Request;
34 import org.eclipse.jetty.client.util.AbstractTypedContentProvider;
35 import org.eclipse.jetty.client.util.FormContentProvider;
36 import org.eclipse.jetty.client.util.StringContentProvider;
37 import org.eclipse.jetty.http.HttpHeader;
38 import org.eclipse.jetty.http.HttpMethod;
39 import org.eclipse.jetty.util.Fields;
40 import org.eclipse.jetty.websocket.client.WebSocketClient;
41 import org.openhab.binding.gardena.internal.config.GardenaConfig;
42 import org.openhab.binding.gardena.internal.exception.GardenaDeviceNotFoundException;
43 import org.openhab.binding.gardena.internal.exception.GardenaException;
44 import org.openhab.binding.gardena.internal.model.DataItemDeserializer;
45 import org.openhab.binding.gardena.internal.model.dto.Device;
46 import org.openhab.binding.gardena.internal.model.dto.api.CreateWebSocketRequest;
47 import org.openhab.binding.gardena.internal.model.dto.api.DataItem;
48 import org.openhab.binding.gardena.internal.model.dto.api.Location;
49 import org.openhab.binding.gardena.internal.model.dto.api.LocationDataItem;
50 import org.openhab.binding.gardena.internal.model.dto.api.LocationResponse;
51 import org.openhab.binding.gardena.internal.model.dto.api.LocationsResponse;
52 import org.openhab.binding.gardena.internal.model.dto.api.PostOAuth2Response;
53 import org.openhab.binding.gardena.internal.model.dto.api.WebSocket;
54 import org.openhab.binding.gardena.internal.model.dto.api.WebSocketCreatedResponse;
55 import org.openhab.binding.gardena.internal.model.dto.command.GardenaCommand;
56 import org.openhab.binding.gardena.internal.model.dto.command.GardenaCommandRequest;
57 import org.openhab.core.io.net.http.HttpClientFactory;
58 import org.openhab.core.io.net.http.WebSocketFactory;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
62 import com.google.gson.Gson;
63 import com.google.gson.GsonBuilder;
64 import com.google.gson.JsonSyntaxException;
67 * {@link GardenaSmart} implementation to access Gardena smart system.
69 * @author Gerhard Riegler - Initial contribution
72 public class GardenaSmartImpl implements GardenaSmart, GardenaSmartWebSocketListener {
73 private final Logger logger = LoggerFactory.getLogger(GardenaSmartImpl.class);
75 private Gson gson = new GsonBuilder().registerTypeAdapter(DataItem.class, new DataItemDeserializer()).create();
77 private static final String URL_API_HUSQUARNA = "https://api.authentication.husqvarnagroup.dev/v1";
78 private static final String URL_API_GARDENA = "https://api.smart.gardena.dev/v1";
79 private static final String URL_API_TOKEN = URL_API_HUSQUARNA + "/oauth2/token";
80 private static final String URL_API_WEBSOCKET = URL_API_GARDENA + "/websocket";
81 private static final String URL_API_LOCATIONS = URL_API_GARDENA + "/locations";
82 private static final String URL_API_COMMAND = URL_API_GARDENA + "/command";
84 private final String id;
85 private final GardenaConfig config;
86 private final ScheduledExecutorService scheduler;
88 private final Map<String, Device> allDevicesById = new HashMap<>();
89 private @Nullable LocationsResponse locationsResponse = null;
90 private final GardenaSmartEventListener eventListener;
92 private final HttpClient httpClient;
93 private final Map<String, GardenaSmartWebSocket> webSockets = new HashMap<>();
94 private @Nullable PostOAuth2Response token;
95 private boolean initialized = false;
96 private final WebSocketClient webSocketClient;
98 private final Set<Device> devicesToNotify = ConcurrentHashMap.newKeySet();
99 private final Object deviceUpdateTaskLock = new Object();
100 private @Nullable ScheduledFuture<?> deviceUpdateTask;
101 private final Object newDeviceTasksLock = new Object();
102 private final List<ScheduledFuture<?>> newDeviceTasks = new ArrayList<>();
104 public GardenaSmartImpl(String id, GardenaConfig config, GardenaSmartEventListener eventListener,
105 ScheduledExecutorService scheduler, HttpClientFactory httpClientFactory, WebSocketFactory webSocketFactory)
106 throws GardenaException {
108 this.config = config;
109 this.eventListener = eventListener;
110 this.scheduler = scheduler;
112 logger.debug("Starting GardenaSmart");
114 httpClient = httpClientFactory.createHttpClient(id);
115 httpClient.setConnectTimeout(config.getConnectionTimeout() * 1000L);
116 httpClient.setIdleTimeout(httpClient.getConnectTimeout());
119 String webSocketId = String.valueOf(hashCode());
120 webSocketClient = webSocketFactory.createWebSocketClient(webSocketId);
121 webSocketClient.setConnectTimeout(config.getConnectionTimeout() * 1000L);
122 webSocketClient.setStopTimeout(3000);
123 webSocketClient.setMaxIdleTimeout(150000);
124 webSocketClient.start();
126 // initially load access token
128 LocationsResponse locationsResponse = loadLocations();
129 this.locationsResponse = locationsResponse;
132 if (locationsResponse.data != null) {
133 for (LocationDataItem location : locationsResponse.data) {
134 LocationResponse locationResponse = loadLocation(location.id);
135 if (locationResponse.included != null) {
136 for (DataItem<?> dataItem : locationResponse.included) {
137 handleDataItem(dataItem);
143 for (Device device : allDevicesById.values()) {
144 device.evaluateDeviceType();
149 } catch (GardenaException ex) {
151 // pass GardenaException to calling function
153 } catch (Exception ex) {
155 throw new GardenaException(ex.getMessage(), ex);
160 * Starts the websockets for each location.
162 private void startWebsockets() throws Exception {
163 LocationsResponse locationsResponse = this.locationsResponse;
164 if (locationsResponse != null) {
165 for (LocationDataItem location : locationsResponse.data) {
166 WebSocketCreatedResponse webSocketCreatedResponse = getWebsocketInfo(location.id);
167 Location locationAttributes = location.attributes;
168 WebSocket webSocketAttributes = webSocketCreatedResponse.data.attributes;
169 if (locationAttributes == null || webSocketAttributes == null) {
172 String socketId = id + "-" + locationAttributes.name;
173 webSockets.put(location.id, new GardenaSmartWebSocket(this, webSocketClient, scheduler,
174 webSocketAttributes.url, token, socketId, location.id));
180 * Stops all websockets.
182 private void stopWebsockets() {
183 for (GardenaSmartWebSocket webSocket : webSockets.values()) {
190 * Communicates with Gardena smart home system and parses the result.
192 private <T> T executeRequest(HttpMethod method, String url, @Nullable Object content, @Nullable Class<T> result)
193 throws GardenaException {
195 AbstractTypedContentProvider contentProvider = null;
196 String contentType = "application/vnd.api+json";
197 if (content != null) {
198 if (content instanceof Fields) {
199 contentProvider = new FormContentProvider((Fields) content);
200 contentType = "application/x-www-form-urlencoded";
202 contentProvider = new StringContentProvider(gson.toJson(content));
206 if (logger.isTraceEnabled()) {
207 logger.trace(">>> {} {}, data: {}", method, url, content == null ? null : gson.toJson(content));
210 Request request = httpClient.newRequest(url).method(method).header(HttpHeader.CONTENT_TYPE, contentType)
211 .header(HttpHeader.ACCEPT, "application/vnd.api+json").header(HttpHeader.ACCEPT_ENCODING, "gzip");
213 if (!URL_API_TOKEN.equals(url)) {
215 final PostOAuth2Response token = this.token;
217 request.header("Authorization", token.tokenType + " " + token.accessToken);
219 request.header("X-Api-Key", config.getApiKey());
222 request.content(contentProvider);
223 ContentResponse contentResponse = request.send();
224 int status = contentResponse.getStatus();
225 if (logger.isTraceEnabled()) {
226 logger.trace("<<< status:{}, {}", status, contentResponse.getContentAsString());
229 if (status != 200 && status != 204 && status != 201 && status != 202) {
230 throw new GardenaException(String.format("Error %s %s, %s", status, contentResponse.getReason(),
231 contentResponse.getContentAsString()), status);
234 if (result == null) {
237 return (T) gson.fromJson(contentResponse.getContentAsString(), result);
238 } catch (InterruptedException | TimeoutException | ExecutionException ex) {
239 throw new GardenaException(ex.getMessage(), ex);
244 * Creates or refreshes the access token for the Gardena smart system.
246 private synchronized void verifyToken() throws GardenaException {
247 Fields fields = new Fields();
248 fields.add("client_id", config.getApiKey());
250 PostOAuth2Response token = this.token;
251 if (token == null || token.isRefreshTokenExpired()) {
253 logger.debug("Gardena API login using apiSecret, reason: {}",
254 token == null ? "no token available" : "refresh token expired");
255 fields.add("grant_type", "client_credentials");
256 fields.add("client_secret", config.getApiSecret());
257 token = executeRequest(HttpMethod.POST, URL_API_TOKEN, fields, PostOAuth2Response.class);
260 } else if (token.isAccessTokenExpired()) {
262 logger.debug("Gardena API login using refreshToken, reason: access token expired");
263 fields.add("grant_type", "refresh_token");
264 fields.add("refresh_token", token.refreshToken);
266 PostOAuth2Response tempToken = executeRequest(HttpMethod.POST, URL_API_TOKEN, fields,
267 PostOAuth2Response.class);
268 token.accessToken = tempToken.accessToken;
269 token.expiresIn = tempToken.expiresIn;
272 } catch (GardenaException ex) {
273 // refresh token issue
278 logger.debug("Gardena API token valid");
280 logger.debug("{}", token.toString());
284 * Loads all locations.
286 private LocationsResponse loadLocations() throws GardenaException {
287 return executeRequest(HttpMethod.GET, URL_API_LOCATIONS, null, LocationsResponse.class);
291 * Loads all devices for a given location.
293 private LocationResponse loadLocation(String locationId) throws GardenaException {
294 return executeRequest(HttpMethod.GET, URL_API_LOCATIONS + "/" + locationId, null, LocationResponse.class);
298 * Returns the websocket url for a given location.
300 private WebSocketCreatedResponse getWebsocketInfo(String locationId) throws GardenaException {
301 return executeRequest(HttpMethod.POST, URL_API_WEBSOCKET, new CreateWebSocketRequest(locationId),
302 WebSocketCreatedResponse.class);
309 public void dispose() {
310 logger.debug("Disposing GardenaSmart");
312 synchronized (newDeviceTasksLock) {
313 for (ScheduledFuture<?> task : newDeviceTasks) {
314 if (!task.isDone()) {
318 newDeviceTasks.clear();
320 synchronized (deviceUpdateTaskLock) {
321 devicesToNotify.clear();
322 ScheduledFuture<?> task = deviceUpdateTask;
326 deviceUpdateTask = null;
331 webSocketClient.stop();
332 } catch (Exception e) {
335 httpClient.destroy();
336 webSocketClient.destroy();
337 allDevicesById.clear();
338 locationsResponse = null;
342 * Restarts all websockets.
345 public synchronized void restartWebsockets() {
346 logger.debug("Restarting GardenaSmart Webservices");
350 } catch (Exception ex) {
352 if (logger.isDebugEnabled()) {
353 logger.warn("Restarting GardenaSmart Webservices failed! Restarting binding", ex);
355 logger.warn("Restarting GardenaSmart Webservices failed: {}! Restarting binding", ex.getMessage());
357 eventListener.onError();
362 * Sets the dataItem from the websocket event into the correct device.
364 private void handleDataItem(final DataItem<?> dataItem) throws GardenaException {
365 final String deviceId = dataItem.getDeviceId();
366 Device device = allDevicesById.get(deviceId);
367 if (device == null && !(dataItem instanceof LocationDataItem)) {
368 device = new Device(deviceId);
369 allDevicesById.put(device.id, device);
371 synchronized (newDeviceTasksLock) {
372 // remove prior completed tasks from the list
373 newDeviceTasks.removeIf(task -> task.isDone());
374 // add a new scheduled task to the list
375 newDeviceTasks.add(scheduler.schedule(() -> {
377 Device newDevice = allDevicesById.get(deviceId);
378 if (newDevice != null) {
379 newDevice.evaluateDeviceType();
380 if (newDevice.deviceType != null) {
381 eventListener.onNewDevice(newDevice);
385 }, 3, TimeUnit.SECONDS));
389 if (device != null) {
390 device.setDataItem(dataItem);
395 public void onWebSocketClose(String id) {
396 restartWebsocket(webSockets.get(id));
400 public void onWebSocketError(String id) {
401 restartWebsocket(webSockets.get(id));
404 private void restartWebsocket(@Nullable GardenaSmartWebSocket socket) {
405 synchronized (this) {
406 if (socket != null && !socket.isClosing()) {
407 // close socket, if still open
408 logger.info("Restarting GardenaSmart Webservice ({})", socket.getSocketID());
411 // if socket is already closing, exit function and do not restart socket
418 WebSocketCreatedResponse webSocketCreatedResponse = getWebsocketInfo(socket.getLocationID());
419 // only restart single socket, do not restart binding
420 WebSocket webSocketAttributes = webSocketCreatedResponse.data.attributes;
421 if (webSocketAttributes != null) {
422 socket.restart(webSocketAttributes.url);
424 } catch (Exception ex) {
425 // restart binding on error
426 logger.warn("Restarting GardenaSmart Webservice failed ({}): {}, restarting binding", socket.getSocketID(),
428 eventListener.onError();
433 public void onWebSocketMessage(String msg) {
435 DataItem<?> dataItem = gson.fromJson(msg, DataItem.class);
436 if (dataItem != null) {
437 handleDataItem(dataItem);
438 Device device = allDevicesById.get(dataItem.getDeviceId());
439 if (device != null && device.active) {
440 synchronized (deviceUpdateTaskLock) {
441 devicesToNotify.add(device);
443 // delay the deviceUpdated event to filter multiple events for the same device dataItem property
444 ScheduledFuture<?> task = this.deviceUpdateTask;
445 if (task == null || task.isDone()) {
446 deviceUpdateTask = scheduler.schedule(() -> notifyDevicesUpdated(), 1, TimeUnit.SECONDS);
451 } catch (GardenaException | JsonSyntaxException ex) {
452 logger.warn("Ignoring message: {}", ex.getMessage());
457 * Helper scheduler task to update devices
459 private void notifyDevicesUpdated() {
460 synchronized (deviceUpdateTaskLock) {
462 Iterator<Device> notifyIterator = devicesToNotify.iterator();
463 while (notifyIterator.hasNext()) {
464 eventListener.onDeviceUpdated(notifyIterator.next());
465 notifyIterator.remove();
472 public Device getDevice(String deviceId) throws GardenaDeviceNotFoundException {
473 Device device = allDevicesById.get(deviceId);
474 if (device == null) {
475 throw new GardenaDeviceNotFoundException("Device with id " + deviceId + " not found");
481 public void sendCommand(DataItem<?> dataItem, GardenaCommand gardenaCommand) throws GardenaException {
482 executeRequest(HttpMethod.PUT, URL_API_COMMAND + "/" + dataItem.id, new GardenaCommandRequest(gardenaCommand),
487 public String getId() {
492 public Collection<Device> getAllDevices() {
493 return allDevicesById.values();