]> git.basschouten.com Git - openhab-addons.git/blob
0d9d6724a4fb00b72b9d6502bc6dc0fe205c8d8f
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.kvv.internal;
14
15 import java.io.IOException;
16 import java.util.Date;
17 import java.util.HashMap;
18 import java.util.Map;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.openhab.core.io.net.http.HttpUtil;
23 import org.openhab.core.thing.Bridge;
24 import org.openhab.core.thing.ChannelUID;
25 import org.openhab.core.thing.ThingStatus;
26 import org.openhab.core.thing.ThingStatusDetail;
27 import org.openhab.core.thing.binding.BaseBridgeHandler;
28 import org.openhab.core.types.Command;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 import com.google.gson.Gson;
33
34 /**
35  * KVVBridgeHandler encapsulates the communication with the KVV API.
36  *
37  * @author Maximilian Hess - Initial contribution
38  */
39 @NonNullByDefault
40 public class KVVBridgeHandler extends BaseBridgeHandler {
41
42     private final Logger logger = LoggerFactory.getLogger(KVVBridgeHandler.class);
43
44     private final Cache cache;
45
46     private KVVBridgeConfig config;
47
48     private boolean wasOffline;
49
50     public KVVBridgeHandler(final Bridge bridge) {
51         super(bridge);
52         this.config = new KVVBridgeConfig();
53         this.cache = new Cache();
54         this.wasOffline = false;
55     }
56
57     public KVVBridgeConfig getBridgeConfig() {
58         return this.config;
59     }
60
61     @Override
62     public void initialize() {
63         updateStatus(ThingStatus.UNKNOWN);
64
65         this.config = getConfigAs(KVVBridgeConfig.class);
66         if (this.config.apiKey.isEmpty()) {
67             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
68                     "Failed to get bridge configuration");
69             return;
70         }
71
72         updateStatus(ThingStatus.ONLINE);
73     }
74
75     @Override
76     public void handleCommand(ChannelUID channelUID, Command command) {
77         // There is nothing to handle in the bridge handler
78     }
79
80     /**
81      * Returns the latest {@link DepartureResult}. Returns {@code null} if the result could not be retrieved.
82      *
83      * @return the latest {@link DepartureResult}.
84      */
85     public synchronized @Nullable DepartureResult queryKVV(final KVVStopConfig stopConfig) {
86
87         // is there an up-to-date value in the cache?
88         final DepartureResult cr = this.cache.get(stopConfig.stopId);
89         if (cr != null) {
90             return cr;
91         }
92
93         final String url = KVVBindingConstants.API_URL + "/departures/bystop/" + stopConfig.stopId + "?key="
94                 + config.apiKey + "&maxInfos=" + config.maxTrains;
95
96         String data;
97         try {
98             data = HttpUtil.executeUrl("GET", url, KVVBindingConstants.TIMEOUT_IN_SECONDS * 1000);
99         } catch (IOException e) {
100             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Failed to connect to KVV API");
101             logger.debug("Failed to get departures from '{}'", url, e);
102             this.wasOffline = true;
103             return null;
104         }
105
106         DepartureResult result;
107         try {
108             result = new Gson().fromJson(data, DepartureResult.class);
109         } catch (Exception e) {
110             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Failed to connect to KVV API");
111             logger.debug("Failed to parse departure data", e);
112             logger.debug("Server returned '{}'", data);
113             this.wasOffline = true;
114             return null;
115         }
116
117         if (this.wasOffline) {
118             updateStatus(ThingStatus.ONLINE);
119         }
120
121         this.cache.update(stopConfig.stopId, result);
122         return result;
123     }
124
125     @NonNullByDefault
126     public static class Cache {
127
128         private int updateInterval;
129
130         private final Map<String, CacheLine> cache;
131
132         /**
133          * Creates a new @{link Cache}.
134          *
135          * @param updateInterval the @{code updateInterval}
136          */
137         public Cache() {
138             this.updateInterval = KVVBindingConstants.CACHE_DEFAULT_UPDATEINTERVAL;
139             this.cache = new HashMap<String, CacheLine>();
140         }
141
142         /*
143          * Updates the @{code updateInterval}.
144          *
145          * @param updateInterval the new @{code updateInterval}
146          */
147         public void setUpdateInterval(final int updateInterval) {
148             this.updateInterval = updateInterval;
149         }
150
151         /**
152          * Returns the result of the latest API call for a given stop. Returns @{code null} if the latest result is
153          * out dated or the @{link CacheLine} does not exist. Not distinguishing between those two cases is sufficient,
154          * because it leads to the same handling of @{link KVVBridgeHandler}.
155          * 
156          * @param stopId
157          * @return the result of the latest API call for a given stop.
158          */
159         @Nullable
160         public DepartureResult get(final String stopId) {
161             if (!this.cache.containsKey(stopId)) {
162                 return null;
163             }
164
165             final CacheLine cl = this.cache.get(stopId);
166             if (cl.getEvictAfter().before(new Date())) {
167                 return null;
168             }
169
170             return cl.getPayload();
171         }
172
173         public void update(final String stopId, final DepartureResult payload) {
174             if (!this.cache.containsKey(stopId)) {
175                 this.cache.put(stopId, new CacheLine(payload, new Date()));
176             }
177
178             final CacheLine cl = this.cache.get(stopId);
179
180             // the eviction time is calculated by adding an offset of 60 percent of the regular update interval of
181             // the bridge handler
182             cl.update(payload, new Date(System.currentTimeMillis() + (long) (0.6 * this.updateInterval * 1000)));
183         }
184     }
185
186     @NonNullByDefault
187     public static class CacheLine {
188
189         private Date evictAfter;
190
191         private DepartureResult payload;
192
193         public CacheLine(final DepartureResult payload, final Date evictAfter) {
194             this.payload = payload;
195             this.evictAfter = evictAfter;
196         }
197
198         public Date getEvictAfter() {
199             return this.evictAfter;
200         }
201
202         public DepartureResult getPayload() {
203             return this.payload;
204         }
205
206         public void update(final DepartureResult payload, final Date evictAfter) {
207             this.payload = payload;
208             this.evictAfter = evictAfter;
209         }
210     }
211 }