]> git.basschouten.com Git - openhab-addons.git/blob
72e192c434a1a6d96818a90ba1b408010e17e2e4
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.deutschebahn.internal;
14
15 import java.io.IOException;
16 import java.net.URISyntaxException;
17 import java.util.ArrayList;
18 import java.util.Collections;
19 import java.util.Date;
20 import java.util.HashMap;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.concurrent.ScheduledExecutorService;
24 import java.util.concurrent.ScheduledFuture;
25 import java.util.concurrent.TimeUnit;
26 import java.util.concurrent.locks.Lock;
27 import java.util.concurrent.locks.ReentrantLock;
28 import java.util.function.Supplier;
29
30 import javax.xml.bind.JAXBException;
31
32 import org.eclipse.jdt.annotation.NonNullByDefault;
33 import org.eclipse.jdt.annotation.Nullable;
34 import org.openhab.binding.deutschebahn.internal.filter.AndPredicate;
35 import org.openhab.binding.deutschebahn.internal.filter.FilterParserException;
36 import org.openhab.binding.deutschebahn.internal.filter.FilterScannerException;
37 import org.openhab.binding.deutschebahn.internal.filter.TimetableStopPredicate;
38 import org.openhab.binding.deutschebahn.internal.timetable.TimetableLoader;
39 import org.openhab.binding.deutschebahn.internal.timetable.TimetablesV1Api;
40 import org.openhab.binding.deutschebahn.internal.timetable.TimetablesV1ApiFactory;
41 import org.openhab.binding.deutschebahn.internal.timetable.dto.TimetableStop;
42 import org.openhab.core.io.net.http.HttpUtil;
43 import org.openhab.core.thing.Bridge;
44 import org.openhab.core.thing.Channel;
45 import org.openhab.core.thing.ChannelUID;
46 import org.openhab.core.thing.Thing;
47 import org.openhab.core.thing.ThingStatus;
48 import org.openhab.core.thing.ThingStatusDetail;
49 import org.openhab.core.thing.ThingTypeUID;
50 import org.openhab.core.thing.binding.BaseBridgeHandler;
51 import org.openhab.core.thing.binding.ThingHandler;
52 import org.openhab.core.types.Command;
53 import org.openhab.core.types.UnDefType;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.xml.sax.SAXException;
57
58 /**
59  * The {@link DeutscheBahnTimetableHandler} is responsible for handling commands, which are
60  * sent to one of the channels.
61  *
62  * @author Sönke Küper - Initial contribution
63  */
64 @NonNullByDefault
65 public class DeutscheBahnTimetableHandler extends BaseBridgeHandler {
66
67     /**
68      * Wrapper containing things grouped by their position and calculates the max. required position.
69      */
70     private static final class GroupedThings {
71
72         private int maxPosition = 0;
73         private final Map<Integer, List<Thing>> thingsPerPosition = new HashMap<>();
74
75         public void addThing(Thing thing) {
76             if (isTrain(thing)) {
77                 int position = thing.getConfiguration().as(DeutscheBahnTrainConfiguration.class).position;
78                 this.maxPosition = Math.max(this.maxPosition, position);
79                 List<Thing> thingsAtPosition = this.thingsPerPosition.get(position);
80                 if (thingsAtPosition == null) {
81                     thingsAtPosition = new ArrayList<>();
82                     this.thingsPerPosition.put(position, thingsAtPosition);
83                 }
84                 thingsAtPosition.add(thing);
85             }
86         }
87
88         /**
89          * Returns the things at the given position.
90          */
91         @Nullable
92         public List<Thing> getThingsAtPosition(int position) {
93             return this.thingsPerPosition.get(position);
94         }
95
96         /**
97          * Returns the max. configured position.
98          */
99         public int getMaxPosition() {
100             return this.maxPosition;
101         }
102     }
103
104     private static final long UPDATE_INTERVAL_SECONDS = 30;
105
106     private final Lock monitor = new ReentrantLock();
107     private @Nullable ScheduledFuture<?> updateJob;
108
109     private final Logger logger = LoggerFactory.getLogger(DeutscheBahnTimetableHandler.class);
110     private @Nullable TimetableLoader loader;
111
112     private final TimetablesV1ApiFactory timetablesV1ApiFactory;
113
114     private final Supplier<Date> currentTimeProvider;
115
116     private final ScheduledExecutorService executorService;
117
118     /**
119      * Creates an new {@link DeutscheBahnTimetableHandler}.
120      */
121     public DeutscheBahnTimetableHandler( //
122             final Bridge bridge, //
123             final TimetablesV1ApiFactory timetablesV1ApiFactory, //
124             final Supplier<Date> currentTimeProvider, //
125             @Nullable final ScheduledExecutorService executorService) {
126         super(bridge);
127         this.timetablesV1ApiFactory = timetablesV1ApiFactory;
128         this.currentTimeProvider = currentTimeProvider;
129         this.executorService = executorService == null ? this.scheduler : executorService;
130     }
131
132     private List<TimetableStop> loadTimetable(TimetableLoader currentLoader) {
133         try {
134             final List<TimetableStop> stops = currentLoader.getTimetableStops();
135             this.updateStatus(ThingStatus.ONLINE);
136             return stops;
137         } catch (final IOException e) {
138             this.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
139             return Collections.emptyList();
140         }
141     }
142
143     /**
144      * The Bridge-Handler does not handle any commands.
145      */
146     @Override
147     public void handleCommand(final ChannelUID channelUID, final Command command) {
148     }
149
150     @Override
151     public void initialize() {
152         final DeutscheBahnTimetableConfiguration config = this.getConfigAs(DeutscheBahnTimetableConfiguration.class);
153
154         try {
155             final TimetablesV1Api api = this.timetablesV1ApiFactory.create(config.accessToken, HttpUtil::executeUrl);
156
157             final TimetableStopFilter stopFilter = config.getTrainFilterFilter();
158             final TimetableStopPredicate additionalFilter = config.getAdditionalFilter();
159
160             final TimetableStopPredicate combinedFilter;
161             if (additionalFilter == null) {
162                 combinedFilter = stopFilter;
163             } else {
164                 combinedFilter = new AndPredicate(stopFilter, additionalFilter);
165             }
166
167             final EventType eventSelection = stopFilter == TimetableStopFilter.ARRIVALS ? EventType.ARRIVAL
168                     : EventType.DEPARTURE;
169
170             this.loader = new TimetableLoader( //
171                     api, //
172                     combinedFilter, //
173                     eventSelection, //
174                     currentTimeProvider, //
175                     config.evaNo, //
176                     1); // will be updated on first call
177
178             this.updateStatus(ThingStatus.UNKNOWN);
179
180             this.executorService.execute(() -> {
181                 this.updateChannels();
182                 this.restartJob();
183             });
184         } catch (FilterScannerException | FilterParserException e) {
185             this.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
186         } catch (JAXBException | SAXException | URISyntaxException e) {
187             this.logger.error("Error initializing api", e);
188             this.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
189         }
190     }
191
192     @Override
193     public void dispose() {
194         this.stopUpdateJob();
195     }
196
197     /**
198      * Schedules an job that updates the timetable every 30 seconds.
199      */
200     private void restartJob() {
201         this.logger.debug("Restarting jobs for bridge {}", this.getThing().getUID());
202         this.monitor.lock();
203         try {
204             this.stopUpdateJob();
205             if (this.getThing().getStatus() == ThingStatus.ONLINE) {
206                 this.updateJob = this.executorService.scheduleWithFixedDelay(//
207                         this::updateChannels, //
208                         0L, //
209                         UPDATE_INTERVAL_SECONDS, //
210                         TimeUnit.SECONDS //
211                 );
212
213                 this.logger.debug("Scheduled {} update of deutsche bahn timetable", this.updateJob);
214             }
215         } finally {
216             this.monitor.unlock();
217         }
218     }
219
220     /**
221      * Stops the update job.
222      */
223     private void stopUpdateJob() {
224         this.monitor.lock();
225         try {
226             final ScheduledFuture<?> job = this.updateJob;
227             if (job != null) {
228                 job.cancel(true);
229             }
230             this.updateJob = null;
231         } finally {
232             this.monitor.unlock();
233         }
234     }
235
236     private void updateChannels() {
237         final TimetableLoader currentLoader = this.loader;
238         if (currentLoader == null) {
239             this.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.HANDLER_INITIALIZING_ERROR);
240             return;
241         }
242         final GroupedThings groupedThings = this.groupThingsPerPosition();
243         currentLoader.setStopCount(groupedThings.getMaxPosition());
244         final List<TimetableStop> timetableStops = this.loadTimetable(currentLoader);
245         if (timetableStops.isEmpty()) {
246             updateThingsToUndefined(groupedThings);
247             return;
248         }
249
250         this.logger.debug("Retrieved {} timetable stops.", timetableStops.size());
251         this.updateThings(groupedThings, timetableStops);
252     }
253
254     /**
255      * No data was retrieved, so update all channel values to undefined.
256      */
257     private void updateThingsToUndefined(GroupedThings groupedThings) {
258         for (List<Thing> things : groupedThings.thingsPerPosition.values()) {
259             for (Thing thing : things) {
260                 updateChannelsToUndefined(thing);
261             }
262         }
263     }
264
265     private void updateChannelsToUndefined(Thing thing) {
266         for (Channel channel : thing.getChannels()) {
267             this.updateState(channel.getUID(), UnDefType.UNDEF);
268         }
269     }
270
271     private void updateThings(GroupedThings groupedThings, final List<TimetableStop> timetableStops) {
272         int position = 1;
273         for (final TimetableStop stop : timetableStops) {
274             final List<Thing> thingsAtPosition = groupedThings.getThingsAtPosition(position);
275
276             if (thingsAtPosition != null) {
277                 for (Thing thing : thingsAtPosition) {
278                     final ThingHandler thingHandler = thing.getHandler();
279                     if (thingHandler != null) {
280                         assert thingHandler instanceof DeutscheBahnTrainHandler;
281                         ((DeutscheBahnTrainHandler) thingHandler).updateChannels(stop);
282                     }
283                 }
284             }
285             position++;
286         }
287
288         // Update all things to undefined, for which no data was received.
289         while (position <= groupedThings.getMaxPosition()) {
290             final List<Thing> thingsAtPosition = groupedThings.getThingsAtPosition(position);
291             if (thingsAtPosition != null) {
292                 for (Thing thing : thingsAtPosition) {
293                     updateChannelsToUndefined(thing);
294                 }
295             }
296             position++;
297         }
298     }
299
300     /**
301      * Returns an map containing the things grouped by timetable stop position.
302      */
303     private GroupedThings groupThingsPerPosition() {
304         final GroupedThings groupedThings = new GroupedThings();
305         for (Thing child : this.getThing().getThings()) {
306             groupedThings.addThing(child);
307         }
308         return groupedThings;
309     }
310
311     private static boolean isTrain(Thing thing) {
312         final ThingTypeUID thingTypeUid = thing.getThingTypeUID();
313         return thingTypeUid.equals(DeutscheBahnBindingConstants.TRAIN_TYPE);
314     }
315 }