]> git.basschouten.com Git - openhab-addons.git/blob
882a51be7314416750122c5bbe4bed54c76ff7f3
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.mcd.internal.handler;
14
15 import java.util.HashSet;
16 import java.util.concurrent.ScheduledFuture;
17 import java.util.concurrent.TimeUnit;
18
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;
37
38 import com.google.gson.Gson;
39 import com.google.gson.JsonObject;
40
41 /**
42  * The {@link McdBridgeHandler} is responsible for handling commands, which are
43  * sent to one of the channels.
44  *
45  * @author Simon Dengler - Initial contribution
46  */
47 @NonNullByDefault
48 public class McdBridgeHandler extends BaseBridgeHandler {
49
50     private final Logger logger = LoggerFactory.getLogger(McdBridgeHandler.class);
51
52     private @Nullable McdBridgeConfiguration config;
53
54     private final HttpClient httpClient;
55     private final Gson gson;
56
57     private String accessToken = "";
58     private int expiresIn;
59     private @Nullable ScheduledFuture<?> future = null;
60
61     private HashSet<Listener> listeners = new HashSet<>();
62
63     public McdBridgeHandler(Bridge bridge, HttpClient httpClient) {
64         super(bridge);
65         this.httpClient = httpClient;
66         gson = new Gson();
67     }
68
69     @Override
70     public void initialize() {
71         config = getConfigAs(McdBridgeConfiguration.class);
72         updateStatus(ThingStatus.UNKNOWN);
73         scheduler.execute(this::logMeIn);
74     }
75
76     @Override
77     public void handleCommand(ChannelUID channelUID, Command command) {
78     }
79
80     @Override
81     public void dispose() {
82         ScheduledFuture<?> localFuture = future;
83         if (localFuture != null) {
84             localFuture.cancel(true);
85         }
86     }
87
88     public void register(Listener listener) {
89         listeners.add(listener);
90     }
91
92     private void triggerEvent() {
93         logger.debug("Event triggered");
94         for (Listener l : listeners) {
95             l.onEvent();
96         }
97     }
98
99     /**
100      * Uses the given credentials to log the user in.
101      */
102     protected void logMeIn() {
103         logger.debug("Logging in...");
104         McdBridgeConfiguration localConfig = config;
105         if (localConfig != null) {
106             try {
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({})
116                     @Override
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) {
122                             case 200:
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 = () -> {
129                                         logMeIn();
130                                     };
131                                     future = scheduler.schedule(task, delay, TimeUnit.MILLISECONDS);
132                                     getAccessToken();
133                                     break;
134                                 } // else go to default
135                             case 400:
136                                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
137                                         "wrong credentials");
138                                 break;
139                             case 0:
140                                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
141                                         "please check your internet connection");
142                                 break;
143                             default:
144                                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
145                                         "Login was not successful");
146                         }
147                         triggerEvent();
148                     }
149                 });
150             } catch (Exception e) {
151                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
152             }
153         }
154     }
155
156     /**
157      * Should be used by C&amp;S binding's things to obtain the bridge's access token
158      * 
159      * @return returns the access token as String
160      */
161     protected String getAccessToken() {
162         return accessToken;
163     }
164 }