]> git.basschouten.com Git - openhab-addons.git/blob
71b68276f22f646391877771b523a4b0bc13e742
[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 static final int REQUEST_TIMEOUT_MS = 10_000;
51     private final Logger logger = LoggerFactory.getLogger(McdBridgeHandler.class);
52
53     private @Nullable McdBridgeConfiguration config;
54
55     private final HttpClient httpClient;
56     private final Gson gson;
57
58     private String accessToken = "";
59     private int expiresIn;
60     private @Nullable ScheduledFuture<?> future = null;
61
62     private HashSet<Listener> listeners = new HashSet<>();
63
64     public McdBridgeHandler(Bridge bridge, HttpClient httpClient) {
65         super(bridge);
66         this.httpClient = httpClient;
67         gson = new Gson();
68     }
69
70     @Override
71     public void initialize() {
72         config = getConfigAs(McdBridgeConfiguration.class);
73         updateStatus(ThingStatus.UNKNOWN);
74         scheduler.execute(this::logMeIn);
75     }
76
77     @Override
78     public void handleCommand(ChannelUID channelUID, Command command) {
79     }
80
81     @Override
82     public void dispose() {
83         ScheduledFuture<?> localFuture = future;
84         if (localFuture != null) {
85             localFuture.cancel(true);
86         }
87     }
88
89     public void register(Listener listener) {
90         listeners.add(listener);
91     }
92
93     private void triggerEvent() {
94         logger.debug("Event triggered");
95         for (Listener l : listeners) {
96             l.onEvent();
97         }
98     }
99
100     /**
101      * Uses the given credentials to log the user in.
102      */
103     protected void logMeIn() {
104         logger.debug("Logging in...");
105         McdBridgeConfiguration localConfig = config;
106         if (localConfig != null) {
107             try {
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);
113
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({})
119                     @Override
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) {
125                             case 200:
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 = () -> {
132                                         logMeIn();
133                                     };
134                                     future = scheduler.schedule(task, delay, TimeUnit.MILLISECONDS);
135                                     getAccessToken();
136                                     break;
137                                 } // else go to default
138                             case 400:
139                                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
140                                         "wrong credentials");
141                                 break;
142                             case 0:
143                                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
144                                         "please check your internet connection");
145                                 break;
146                             default:
147                                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
148                                         "Login was not successful");
149                         }
150                         triggerEvent();
151                     }
152                 });
153             } catch (Exception e) {
154                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
155             }
156         }
157     }
158
159     /**
160      * Should be used by C&amp;S binding's things to obtain the bridge's access token
161      * 
162      * @return returns the access token as String
163      */
164     protected String getAccessToken() {
165         return accessToken;
166     }
167 }