2 * Copyright (c) 2010-2020 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.kvv.internal;
15 import java.io.IOException;
16 import java.util.Date;
17 import java.util.HashMap;
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;
32 import com.google.gson.Gson;
35 * KVVBridgeHandler encapsulates the communication with the KVV API.
37 * @author Maximilian Hess - Initial contribution
40 public class KVVBridgeHandler extends BaseBridgeHandler {
42 private final Logger logger = LoggerFactory.getLogger(KVVBridgeHandler.class);
44 private final Cache cache;
46 private KVVBridgeConfig config;
48 private boolean wasOffline;
50 public KVVBridgeHandler(final Bridge bridge) {
52 this.config = new KVVBridgeConfig();
53 this.cache = new Cache();
54 this.wasOffline = false;
57 public KVVBridgeConfig getBridgeConfig() {
62 public void initialize() {
63 updateStatus(ThingStatus.UNKNOWN);
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");
72 updateStatus(ThingStatus.ONLINE);
76 public void handleCommand(ChannelUID channelUID, Command command) {
77 // There is nothing to handle in the bridge handler
81 * Returns the latest {@link DepartureResult}. Returns {@code null} if the result could not be retrieved.
83 * @return the latest {@link DepartureResult}.
85 public synchronized @Nullable DepartureResult queryKVV(final KVVStopConfig stopConfig) {
87 // is there an up-to-date value in the cache?
88 final DepartureResult cr = this.cache.get(stopConfig.stopId);
93 final String url = KVVBindingConstants.API_URL + "/departures/bystop/" + stopConfig.stopId + "?key="
94 + config.apiKey + "&maxInfos=" + config.maxTrains;
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;
106 DepartureResult result;
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;
117 if (this.wasOffline) {
118 updateStatus(ThingStatus.ONLINE);
121 this.cache.update(stopConfig.stopId, result);
126 public static class Cache {
128 private int updateInterval;
130 private final Map<String, CacheLine> cache;
133 * Creates a new @{link Cache}.
135 * @param updateInterval the @{code updateInterval}
138 this.updateInterval = KVVBindingConstants.CACHE_DEFAULT_UPDATEINTERVAL;
139 this.cache = new HashMap<String, CacheLine>();
143 * Updates the @{code updateInterval}.
145 * @param updateInterval the new @{code updateInterval}
147 public void setUpdateInterval(final int updateInterval) {
148 this.updateInterval = updateInterval;
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}.
157 * @return the result of the latest API call for a given stop.
160 public DepartureResult get(final String stopId) {
161 if (!this.cache.containsKey(stopId)) {
165 final CacheLine cl = this.cache.get(stopId);
166 if (cl.getEvictAfter().before(new Date())) {
170 return cl.getPayload();
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()));
178 final CacheLine cl = this.cache.get(stopId);
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)));
187 public static class CacheLine {
189 private Date evictAfter;
191 private DepartureResult payload;
193 public CacheLine(final DepartureResult payload, final Date evictAfter) {
194 this.payload = payload;
195 this.evictAfter = evictAfter;
198 public Date getEvictAfter() {
199 return this.evictAfter;
202 public DepartureResult getPayload() {
206 public void update(final DepartureResult payload, final Date evictAfter) {
207 this.payload = payload;
208 this.evictAfter = evictAfter;