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