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 final Logger logger = LoggerFactory.getLogger(McdBridgeHandler.class);
52 private @Nullable McdBridgeConfiguration config;
54 private final HttpClient httpClient;
55 private final Gson gson;
57 private String accessToken = "";
58 private int expiresIn;
59 private @Nullable ScheduledFuture<?> future = null;
61 private HashSet<Listener> listeners = new HashSet<>();
63 public McdBridgeHandler(Bridge bridge, HttpClient httpClient) {
65 this.httpClient = httpClient;
70 public void initialize() {
71 config = getConfigAs(McdBridgeConfiguration.class);
72 updateStatus(ThingStatus.UNKNOWN);
73 scheduler.execute(this::logMeIn);
77 public void handleCommand(ChannelUID channelUID, Command command) {
81 public void dispose() {
82 ScheduledFuture<?> localFuture = future;
83 if (localFuture != null) {
84 localFuture.cancel(true);
88 public void register(Listener listener) {
89 listeners.add(listener);
92 private void triggerEvent() {
93 logger.debug("Event triggered");
94 for (Listener l : listeners) {
100 * Uses the given credentials to log the user in.
102 protected void logMeIn() {
103 logger.debug("Logging in...");
104 McdBridgeConfiguration localConfig = config;
105 if (localConfig != null) {
107 Request request = httpClient.newRequest("https://cunds-syncapi.azurewebsites.net/token")
108 .method(HttpMethod.POST).header(HttpHeader.CONTENT_TYPE, "application/x-www-form-urlencoded")
109 .header(HttpHeader.HOST, "cunds-syncapi.azurewebsites.net")
110 .header(HttpHeader.ACCEPT, "application/json");
111 String content = "grant_type=password&username=" + localConfig.getUserEmail() + "&password="
112 + localConfig.getUserPassword();
113 request.content(new StringContentProvider(content), "application/x-www-form-urlencoded");
114 request.send(new BufferingResponseListener() {
115 @NonNullByDefault({})
117 public void onComplete(Result result) {
118 String contentString = getContentAsString();
119 JsonObject content = gson.fromJson(contentString, JsonObject.class);
120 int responseCode = result.getResponse().getStatus();
121 switch (responseCode) {
123 if (content != null && content.has("access_token")) {
124 updateStatus(ThingStatus.ONLINE);
125 accessToken = content.get("access_token").getAsString();
126 expiresIn = content.get("expires_in").getAsInt();
127 long delay = ((long) expiresIn) * 1000L - 60000L;
128 Runnable task = () -> {
131 future = scheduler.schedule(task, delay, TimeUnit.MILLISECONDS);
134 } // else go to default
136 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
137 "wrong credentials");
140 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
141 "please check your internet connection");
144 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
145 "Login was not successful");
150 } catch (Exception e) {
151 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
157 * Should be used by C&S binding's things to obtain the bridge's access token
159 * @return returns the access token as String
161 protected String getAccessToken() {