2 * Copyright (c) 2010-2024 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;
33 import com.google.gson.JsonSyntaxException;
36 * KVVBridgeHandler encapsulates the communication with the KVV API.
38 * @author Maximilian Hess - Initial contribution
41 public class KVVBridgeHandler extends BaseBridgeHandler {
43 private final Logger logger = LoggerFactory.getLogger(KVVBridgeHandler.class);
45 private final Cache cache;
47 private KVVBridgeConfig config;
49 private boolean wasOffline;
51 public KVVBridgeHandler(final Bridge bridge) {
53 this.config = new KVVBridgeConfig();
54 this.cache = new Cache();
55 this.wasOffline = false;
58 public KVVBridgeConfig getBridgeConfig() {
63 public void initialize() {
64 this.config = getConfigAs(KVVBridgeConfig.class);
65 updateStatus(ThingStatus.ONLINE);
69 public void handleCommand(ChannelUID channelUID, Command command) {
70 // There is nothing to handle in the bridge handler
74 * Returns the latest {@link DepartureResult}. Returns {@code null} if the result could not be retrieved.
76 * @return the latest {@link DepartureResult}.
78 public synchronized @Nullable DepartureResult queryKVV(final KVVStopConfig stopConfig) {
79 // is there an up-to-date value in the cache?
80 final DepartureResult cr = this.cache.get(stopConfig.stopId);
85 final String url = String.format(KVVBindingConstants.API_FORMAT, stopConfig.stopId, config.maxTrains);
89 data = HttpUtil.executeUrl("GET", url, KVVBindingConstants.TIMEOUT_IN_SECONDS * 1000);
90 } catch (IOException e) {
91 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Failed to connect to KVV API");
92 logger.debug("Failed to get departures from '{}'", url, e);
93 this.wasOffline = true;
97 DepartureResult result;
99 result = new Gson().fromJson(data, DepartureResult.class);
100 } catch (JsonSyntaxException e) {
101 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Failed to connect to KVV API");
102 logger.debug("Failed to parse departure data", e);
103 logger.debug("Server returned '{}'", data);
104 this.wasOffline = true;
108 if (result == null) {
112 if (this.wasOffline) {
113 updateStatus(ThingStatus.ONLINE);
116 this.cache.update(stopConfig.stopId, result);
121 public static class Cache {
123 private int updateInterval;
125 private final Map<String, CacheLine> cache;
128 * Creates a new @{link Cache}.
132 this.updateInterval = KVVBindingConstants.CACHE_DEFAULT_UPDATEINTERVAL;
133 this.cache = new HashMap<String, CacheLine>();
137 * Updates the @{code updateInterval}.
139 * @param updateInterval the new @{code updateInterval}
141 public void setUpdateInterval(final int updateInterval) {
142 this.updateInterval = updateInterval;
146 * Returns the result of the latest API call for a given stop. Returns @{code null} if the latest result is
147 * out dated or the @{link CacheLine} does not exist. Not distinguishing between those two cases is sufficient,
148 * because it leads to the same handling of @{link KVVBridgeHandler}.
151 * @return the result of the latest API call for a given stop.
154 public DepartureResult get(final String stopId) {
155 if (!this.cache.containsKey(stopId)) {
159 final CacheLine cl = this.cache.get(stopId);
160 if (cl.getEvictAfter().before(new Date())) {
164 return cl.getPayload();
167 public void update(final String stopId, final DepartureResult payload) {
168 if (!this.cache.containsKey(stopId)) {
169 this.cache.put(stopId, new CacheLine(payload, new Date()));
172 final CacheLine cl = this.cache.get(stopId);
174 // the eviction time is calculated by adding an offset of 60 percent of the regular update interval of
175 // the bridge handler
176 cl.update(payload, new Date(System.currentTimeMillis() + (long) (0.6 * this.updateInterval * 1000)));
181 public static class CacheLine {
183 private Date evictAfter;
185 private DepartureResult payload;
187 public CacheLine(final DepartureResult payload, final Date evictAfter) {
188 this.payload = payload;
189 this.evictAfter = evictAfter;
192 public Date getEvictAfter() {
193 return this.evictAfter;
196 public DepartureResult getPayload() {
200 public void update(final DepartureResult payload, final Date evictAfter) {
201 this.payload = payload;
202 this.evictAfter = evictAfter;