2 * Copyright (c) 2010-2021 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.deutschebahn.internal;
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;
23 import java.util.concurrent.ScheduledFuture;
24 import java.util.concurrent.TimeUnit;
25 import java.util.concurrent.locks.Lock;
26 import java.util.concurrent.locks.ReentrantLock;
27 import java.util.function.Supplier;
29 import javax.xml.bind.JAXBException;
31 import org.eclipse.jdt.annotation.NonNullByDefault;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.openhab.binding.deutschebahn.internal.filter.AndPredicate;
34 import org.openhab.binding.deutschebahn.internal.filter.FilterParserException;
35 import org.openhab.binding.deutschebahn.internal.filter.FilterScannerException;
36 import org.openhab.binding.deutschebahn.internal.filter.TimetableStopPredicate;
37 import org.openhab.binding.deutschebahn.internal.timetable.TimetableLoader;
38 import org.openhab.binding.deutschebahn.internal.timetable.TimetablesV1Api;
39 import org.openhab.binding.deutschebahn.internal.timetable.TimetablesV1ApiFactory;
40 import org.openhab.binding.deutschebahn.internal.timetable.dto.TimetableStop;
41 import org.openhab.core.io.net.http.HttpUtil;
42 import org.openhab.core.thing.Bridge;
43 import org.openhab.core.thing.Channel;
44 import org.openhab.core.thing.ChannelUID;
45 import org.openhab.core.thing.Thing;
46 import org.openhab.core.thing.ThingStatus;
47 import org.openhab.core.thing.ThingStatusDetail;
48 import org.openhab.core.thing.ThingTypeUID;
49 import org.openhab.core.thing.binding.BaseBridgeHandler;
50 import org.openhab.core.thing.binding.ThingHandler;
51 import org.openhab.core.types.Command;
52 import org.openhab.core.types.UnDefType;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.xml.sax.SAXException;
58 * The {@link DeutscheBahnTimetableHandler} is responsible for handling commands, which are
59 * sent to one of the channels.
61 * @author Sönke Küper - Initial contribution
64 public class DeutscheBahnTimetableHandler extends BaseBridgeHandler {
67 * Wrapper containing things grouped by their position and calculates the max. required position.
69 private static final class GroupedThings {
71 private int maxPosition = 0;
72 private final Map<Integer, List<Thing>> thingsPerPosition = new HashMap<>();
74 public void addThing(Thing thing) {
76 int position = thing.getConfiguration().as(DeutscheBahnTrainConfiguration.class).position;
77 this.maxPosition = Math.max(this.maxPosition, position);
78 List<Thing> thingsAtPosition = this.thingsPerPosition.get(position);
79 if (thingsAtPosition == null) {
80 thingsAtPosition = new ArrayList<>();
81 this.thingsPerPosition.put(position, thingsAtPosition);
83 thingsAtPosition.add(thing);
88 * Returns the things at the given position.
91 public List<Thing> getThingsAtPosition(int position) {
92 return this.thingsPerPosition.get(position);
96 * Returns the max. configured position.
98 public int getMaxPosition() {
99 return this.maxPosition;
103 private static final long UPDATE_INTERVAL_SECONDS = 30;
105 private final Lock monitor = new ReentrantLock();
106 private @Nullable ScheduledFuture<?> updateJob;
108 private final Logger logger = LoggerFactory.getLogger(DeutscheBahnTimetableHandler.class);
109 private @Nullable TimetableLoader loader;
111 private TimetablesV1ApiFactory timetablesV1ApiFactory;
113 private Supplier<Date> currentTimeProvider;
116 * Creates an new {@link DeutscheBahnTimetableHandler}.
118 public DeutscheBahnTimetableHandler( //
119 final Bridge bridge, //
120 final TimetablesV1ApiFactory timetablesV1ApiFactory, //
121 final Supplier<Date> currentTimeProvider) {
123 this.timetablesV1ApiFactory = timetablesV1ApiFactory;
124 this.currentTimeProvider = currentTimeProvider;
127 private List<TimetableStop> loadTimetable() {
128 final TimetableLoader currentLoader = this.loader;
129 if (currentLoader == null) {
130 this.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.HANDLER_INITIALIZING_ERROR);
131 return Collections.emptyList();
135 final List<TimetableStop> stops = currentLoader.getTimetableStops();
136 this.updateStatus(ThingStatus.ONLINE);
138 } catch (final IOException e) {
139 this.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
140 return Collections.emptyList();
145 * The Bridge-Handler does not handle any commands.
148 public void handleCommand(final ChannelUID channelUID, final Command command) {
152 public void initialize() {
153 final DeutscheBahnTimetableConfiguration config = this.getConfigAs(DeutscheBahnTimetableConfiguration.class);
156 final TimetablesV1Api api = this.timetablesV1ApiFactory.create(config.accessToken, HttpUtil::executeUrl);
158 final TimetableStopFilter stopFilter = config.getTrainFilterFilter();
159 final TimetableStopPredicate additionalFilter = config.getAdditionalFilter();
161 final TimetableStopPredicate combinedFilter;
162 if (additionalFilter == null) {
163 combinedFilter = stopFilter;
165 combinedFilter = new AndPredicate(stopFilter, additionalFilter);
168 final EventType eventSelection = stopFilter == TimetableStopFilter.ARRIVALS ? EventType.ARRIVAL
171 this.loader = new TimetableLoader( //
175 currentTimeProvider, //
177 1); // will be updated on first call
179 this.updateStatus(ThingStatus.UNKNOWN);
181 this.scheduler.execute(() -> {
182 this.updateChannels();
185 } catch (FilterScannerException | FilterParserException e) {
186 this.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
187 } catch (JAXBException | SAXException | URISyntaxException e) {
188 this.logger.error("Error initializing api", e);
189 this.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
194 public void dispose() {
195 this.stopUpdateJob();
199 * Schedules an job that updates the timetable every 30 seconds.
201 private void restartJob() {
202 this.logger.debug("Restarting jobs for bridge {}", this.getThing().getUID());
205 this.stopUpdateJob();
206 if (this.getThing().getStatus() == ThingStatus.ONLINE) {
207 this.updateJob = this.scheduler.scheduleWithFixedDelay(//
208 this::updateChannels, //
210 UPDATE_INTERVAL_SECONDS, //
214 this.logger.debug("Scheduled {} update of deutsche bahn timetable", this.updateJob);
217 this.monitor.unlock();
222 * Stops the update job.
224 private void stopUpdateJob() {
227 final ScheduledFuture<?> job = this.updateJob;
231 this.updateJob = null;
233 this.monitor.unlock();
237 private void updateChannels() {
238 final TimetableLoader currentLoader = this.loader;
239 if (currentLoader == null) {
240 this.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.HANDLER_INITIALIZING_ERROR);
243 final GroupedThings groupedThings = this.groupThingsPerPosition();
244 currentLoader.setStopCount(groupedThings.getMaxPosition());
245 final List<TimetableStop> timetableStops = this.loadTimetable();
246 if (timetableStops.isEmpty()) {
247 updateThingsToUndefined(groupedThings);
251 this.logger.debug("Retrieved {} timetable stops.", timetableStops.size());
252 this.updateThings(groupedThings, timetableStops);
256 * No data was retrieved, so update all channel values to undefined.
258 private void updateThingsToUndefined(GroupedThings groupedThings) {
259 for (List<Thing> things : groupedThings.thingsPerPosition.values()) {
260 for (Thing thing : things) {
261 updateChannelsToUndefined(thing);
266 private void updateChannelsToUndefined(Thing thing) {
267 for (Channel channel : thing.getChannels()) {
268 this.updateState(channel.getUID(), UnDefType.UNDEF);
272 private void updateThings(GroupedThings groupedThings, final List<TimetableStop> timetableStops) {
274 for (final TimetableStop stop : timetableStops) {
275 final List<Thing> thingsAtPosition = groupedThings.getThingsAtPosition(position);
277 if (thingsAtPosition != null) {
278 for (Thing thing : thingsAtPosition) {
279 final ThingHandler thingHandler = thing.getHandler();
280 if (thingHandler != null) {
281 assert thingHandler instanceof DeutscheBahnTrainHandler;
282 ((DeutscheBahnTrainHandler) thingHandler).updateChannels(stop);
289 // Update all things to undefined, for which no data was received.
290 while (position <= groupedThings.getMaxPosition()) {
291 final List<Thing> thingsAtPosition = groupedThings.getThingsAtPosition(position);
292 if (thingsAtPosition != null) {
293 for (Thing thing : thingsAtPosition) {
294 updateChannelsToUndefined(thing);
302 * Returns an map containing the things grouped by timetable stop position.
304 private GroupedThings groupThingsPerPosition() {
305 final GroupedThings groupedThings = new GroupedThings();
306 for (Thing child : this.getThing().getThings()) {
307 groupedThings.addThing(child);
309 return groupedThings;
312 private static boolean isTrain(Thing thing) {
313 final ThingTypeUID thingTypeUid = thing.getThingTypeUID();
314 return thingTypeUid.equals(DeutscheBahnBindingConstants.TRAIN_TYPE);