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.mcd.internal.handler;
15 import java.util.HashSet;
16 import java.util.concurrent.ScheduledFuture;
17 import java.util.concurrent.TimeUnit;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.eclipse.jetty.client.HttpClient;
22 import org.eclipse.jetty.client.api.Request;
23 import org.eclipse.jetty.client.api.Result;
24 import org.eclipse.jetty.client.util.BufferingResponseListener;
25 import org.eclipse.jetty.client.util.StringContentProvider;
26 import org.eclipse.jetty.http.HttpHeader;
27 import org.eclipse.jetty.http.HttpMethod;
28 import org.openhab.binding.mcd.internal.util.Listener;
29 import org.openhab.core.thing.Bridge;
30 import org.openhab.core.thing.ChannelUID;
31 import org.openhab.core.thing.ThingStatus;
32 import org.openhab.core.thing.ThingStatusDetail;
33 import org.openhab.core.thing.binding.BaseBridgeHandler;
34 import org.openhab.core.types.Command;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
38 import com.google.gson.Gson;
39 import com.google.gson.JsonObject;
42 * The {@link McdBridgeHandler} is responsible for handling commands, which are
43 * sent to one of the channels.
45 * @author Simon Dengler - Initial contribution
48 public class McdBridgeHandler extends BaseBridgeHandler {
50 private static final int REQUEST_TIMEOUT_MS = 10_000;
51 private final Logger logger = LoggerFactory.getLogger(McdBridgeHandler.class);
53 private @Nullable McdBridgeConfiguration config;
55 private final HttpClient httpClient;
56 private final Gson gson;
58 private String accessToken = "";
59 private int expiresIn;
60 private @Nullable ScheduledFuture<?> future = null;
62 private HashSet<Listener> listeners = new HashSet<>();
64 public McdBridgeHandler(Bridge bridge, HttpClient httpClient) {
66 this.httpClient = httpClient;
71 public void initialize() {
72 config = getConfigAs(McdBridgeConfiguration.class);
73 updateStatus(ThingStatus.UNKNOWN);
74 scheduler.execute(this::logMeIn);
78 public void handleCommand(ChannelUID channelUID, Command command) {
82 public void dispose() {
83 ScheduledFuture<?> localFuture = future;
84 if (localFuture != null) {
85 localFuture.cancel(true);
89 public void register(Listener listener) {
90 listeners.add(listener);
93 private void triggerEvent() {
94 logger.debug("Event triggered");
95 for (Listener l : listeners) {
101 * Uses the given credentials to log the user in.
103 protected void logMeIn() {
104 logger.debug("Logging in...");
105 McdBridgeConfiguration localConfig = config;
106 if (localConfig != null) {
108 Request request = httpClient.newRequest("https://cunds-syncapi.azurewebsites.net/token")
109 .method(HttpMethod.POST).header(HttpHeader.CONTENT_TYPE, "application/x-www-form-urlencoded")
110 .header(HttpHeader.HOST, "cunds-syncapi.azurewebsites.net")
111 .header(HttpHeader.ACCEPT, "application/json")
112 .timeout(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
114 String content = "grant_type=password&username=" + localConfig.getUserEmail() + "&password="
115 + localConfig.getUserPassword();
116 request.content(new StringContentProvider(content), "application/x-www-form-urlencoded");
117 request.send(new BufferingResponseListener() {
118 @NonNullByDefault({})
120 public void onComplete(Result result) {
121 String contentString = getContentAsString();
122 JsonObject content = gson.fromJson(contentString, JsonObject.class);
123 int responseCode = result.getResponse().getStatus();
124 switch (responseCode) {
126 if (content != null && content.has("access_token")) {
127 updateStatus(ThingStatus.ONLINE);
128 accessToken = content.get("access_token").getAsString();
129 expiresIn = content.get("expires_in").getAsInt();
130 long delay = ((long) expiresIn) * 1000L - 60000L;
131 Runnable task = () -> {
134 future = scheduler.schedule(task, delay, TimeUnit.MILLISECONDS);
137 } // else go to default
139 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
140 "wrong credentials");
143 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
144 "please check your internet connection");
147 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
148 "Login was not successful");
153 } catch (Exception e) {
154 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
160 * Should be used by C&S binding's things to obtain the bridge's access token
162 * @return returns the access token as String
164 protected String getAccessToken() {