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