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.icalendar.internal.handler;
15 import static org.openhab.binding.icalendar.internal.ICalendarBindingConstants.*;
18 import java.io.FileInputStream;
19 import java.io.IOException;
20 import java.math.BigDecimal;
22 import java.net.URISyntaxException;
23 import java.time.Instant;
24 import java.util.List;
25 import java.util.concurrent.ScheduledFuture;
26 import java.util.concurrent.TimeUnit;
28 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.eclipse.jetty.client.HttpClient;
31 import org.openhab.binding.icalendar.internal.config.ICalendarConfiguration;
32 import org.openhab.binding.icalendar.internal.handler.PullJob.CalendarUpdateListener;
33 import org.openhab.binding.icalendar.internal.logic.AbstractPresentableCalendar;
34 import org.openhab.binding.icalendar.internal.logic.CalendarException;
35 import org.openhab.binding.icalendar.internal.logic.CommandTag;
36 import org.openhab.binding.icalendar.internal.logic.CommandTagType;
37 import org.openhab.binding.icalendar.internal.logic.Event;
38 import org.openhab.core.OpenHAB;
39 import org.openhab.core.events.EventPublisher;
40 import org.openhab.core.i18n.TimeZoneProvider;
41 import org.openhab.core.items.events.ItemEventFactory;
42 import org.openhab.core.library.types.DateTimeType;
43 import org.openhab.core.library.types.OnOffType;
44 import org.openhab.core.library.types.StringType;
45 import org.openhab.core.thing.Bridge;
46 import org.openhab.core.thing.ChannelUID;
47 import org.openhab.core.thing.Thing;
48 import org.openhab.core.thing.ThingStatus;
49 import org.openhab.core.thing.ThingStatusDetail;
50 import org.openhab.core.thing.binding.BaseBridgeHandler;
51 import org.openhab.core.thing.binding.ThingHandler;
52 import org.openhab.core.thing.binding.ThingHandlerCallback;
53 import org.openhab.core.thing.binding.builder.ChannelBuilder;
54 import org.openhab.core.thing.binding.builder.ThingBuilder;
55 import org.openhab.core.types.Command;
56 import org.openhab.core.types.RefreshType;
57 import org.openhab.core.types.UnDefType;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
62 * The {@link ICalendarHandler} is responsible for handling commands, which are
63 * sent to one of the channels.
65 * @author Michael Wodniok - Initial contribution
66 * @author Andrew Fiddian-Green - Support for Command Tags embedded in the Event description
67 * @author Michael Wodniok - Added last_update-channel and additional needed handling of it
70 public class ICalendarHandler extends BaseBridgeHandler implements CalendarUpdateListener {
72 private final File calendarFile;
73 private @Nullable ICalendarConfiguration configuration;
74 private final EventPublisher eventPublisherCallback;
75 private final HttpClient httpClient;
76 private final Logger logger = LoggerFactory.getLogger(ICalendarHandler.class);
77 private final TimeZoneProvider tzProvider;
78 private @Nullable ScheduledFuture<?> pullJobFuture;
79 private @Nullable AbstractPresentableCalendar runtimeCalendar;
80 private @Nullable ScheduledFuture<?> updateJobFuture;
81 private Instant updateStatesLastCalledTime;
82 private @Nullable Instant calendarDownloadedTime;
84 public ICalendarHandler(Bridge bridge, HttpClient httpClient, EventPublisher eventPublisher,
85 TimeZoneProvider tzProvider) {
87 this.httpClient = httpClient;
88 calendarFile = new File(OpenHAB.getUserDataFolder() + File.separator
89 + getThing().getUID().getAsString().replaceAll("[<>:\"/\\\\|?*]", "_") + ".ical");
90 eventPublisherCallback = eventPublisher;
91 updateStatesLastCalledTime = Instant.now();
92 this.tzProvider = tzProvider;
96 public void dispose() {
97 final ScheduledFuture<?> currentUpdateJobFuture = updateJobFuture;
98 if (currentUpdateJobFuture != null) {
99 currentUpdateJobFuture.cancel(true);
101 final ScheduledFuture<?> currentPullJobFuture = pullJobFuture;
102 if (currentPullJobFuture != null) {
103 currentPullJobFuture.cancel(true);
108 public void handleCommand(ChannelUID channelUID, Command command) {
109 switch (channelUID.getId()) {
110 case CHANNEL_CURRENT_EVENT_PRESENT:
111 case CHANNEL_CURRENT_EVENT_TITLE:
112 case CHANNEL_CURRENT_EVENT_START:
113 case CHANNEL_CURRENT_EVENT_END:
114 case CHANNEL_NEXT_EVENT_TITLE:
115 case CHANNEL_NEXT_EVENT_START:
116 case CHANNEL_NEXT_EVENT_END:
117 case CHANNEL_LAST_UPDATE:
118 if (command instanceof RefreshType) {
123 logger.warn("Framework sent command to unknown channel with id '{}'", channelUID.getId());
128 public void initialize() {
129 migrateLastUpdateChannel();
131 final ICalendarConfiguration currentConfiguration = getConfigAs(ICalendarConfiguration.class);
132 configuration = currentConfiguration;
135 if ((currentConfiguration.username == null && currentConfiguration.password != null)
136 || (currentConfiguration.username != null && currentConfiguration.password == null)) {
137 throw new ConfigBrokenException("Only one of username and password was set. This is invalid.");
141 final BigDecimal maxSizeBD = currentConfiguration.maxSize;
142 if (maxSizeBD == null || maxSizeBD.intValue() < 1) {
143 throw new ConfigBrokenException(
144 "maxSize is either not set or less than 1 (mebibyte), which is not allowed.");
146 final int maxSize = maxSizeBD.intValue();
148 regularPull = new PullJob(httpClient, new URI(currentConfiguration.url), currentConfiguration.username,
149 currentConfiguration.password, calendarFile, maxSize * 1048576, this);
150 } catch (URISyntaxException e) {
151 throw new ConfigBrokenException(String.format(
152 "The URI '%s' for downloading the calendar contains syntax errors.", currentConfiguration.url));
156 final BigDecimal refreshTimeBD = currentConfiguration.refreshTime;
157 if (refreshTimeBD == null || refreshTimeBD.longValue() < 1) {
158 throw new ConfigBrokenException(
159 "refreshTime is either not set or less than 1 (minute), which is not allowed.");
161 final long refreshTime = refreshTimeBD.longValue();
162 if (calendarFile.isFile()) {
163 updateStatus(ThingStatus.ONLINE);
165 scheduler.submit(() -> {
166 // reload calendar file asynchronously
167 if (reloadCalendar()) {
171 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
172 "The calendar seems to be configured correctly, but the local copy of calendar could not be loaded.");
175 pullJobFuture = scheduler.scheduleWithFixedDelay(regularPull, refreshTime, refreshTime,
178 updateStatus(ThingStatus.OFFLINE);
180 "The calendar is currently offline as no local copy exists. It will go online as soon as a valid valid calendar is retrieved.");
181 pullJobFuture = scheduler.scheduleWithFixedDelay(regularPull, 0, refreshTime, TimeUnit.MINUTES);
183 } catch (ConfigBrokenException e) {
184 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
189 public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
190 final AbstractPresentableCalendar calendar = runtimeCalendar;
191 if (calendar != null) {
192 updateChild(childHandler);
197 public void onCalendarUpdated() {
198 if (reloadCalendar()) {
202 logger.trace("Calendar was updated, but loading failed.");
207 * @return the calendar that is used for all operations
210 public AbstractPresentableCalendar getRuntimeCalendar() {
211 return runtimeCalendar;
214 private void executeEventCommands(List<Event> events, CommandTagType execTime) {
215 // no begun or ended events => exit quietly as there is nothing to do
216 if (events.isEmpty()) {
220 final ICalendarConfiguration syncConfiguration = configuration;
221 if (syncConfiguration == null) {
222 logger.debug("Configuration not instantiated!");
225 // loop through all events in the list
226 for (Event event : events) {
228 // loop through all command tags in the event
229 for (CommandTag cmdTag : event.commandTags) {
231 // only process the BEGIN resp. END tags
232 if (cmdTag.getTagType() != execTime) {
235 if (!cmdTag.isAuthorized(syncConfiguration.authorizationCode)) {
236 logger.warn("Event: {}, Command Tag: {} => Command not authorized!", event.title,
237 cmdTag.getFullTag());
241 final Command cmdState = cmdTag.getCommand();
242 if (cmdState == null) {
243 logger.warn("Event: {}, Command Tag: {} => Error creating Command State!", event.title,
244 cmdTag.getFullTag());
248 // (try to) execute the command
250 eventPublisherCallback.post(ItemEventFactory.createCommandEvent(cmdTag.getItemName(), cmdState));
251 if (logger.isDebugEnabled()) {
252 String cmdType = cmdState.getClass().toString();
253 int index = cmdType.lastIndexOf(".") + 1;
254 if ((index > 0) && (index < cmdType.length())) {
255 cmdType = cmdType.substring(index);
257 logger.debug("Event: {}, Command Tag: {} => {}.postUpdate({}: {})", event.title,
258 cmdTag.getFullTag(), cmdTag.getItemName(), cmdType, cmdState);
260 } catch (IllegalArgumentException | IllegalStateException e) {
261 logger.warn("Event: {}, Command Tag: {} => Unable to push command to target item!", event.title,
262 cmdTag.getFullTag());
263 logger.debug("Exception occured while pushing to item!", e);
270 * Migration for last_update-channel as this change is compatible to previous instances.
272 private void migrateLastUpdateChannel() {
273 final Thing thing = getThing();
274 if (thing.getChannel(CHANNEL_LAST_UPDATE) == null) {
275 logger.trace("last_update channel is missing in this Thing. Adding it.");
276 final ThingHandlerCallback callback = getCallback();
277 if (callback == null) {
278 logger.debug("ThingHandlerCallback is null. Skipping migration of last_update channel.");
281 final ChannelBuilder channelBuilder = callback
282 .createChannelBuilder(new ChannelUID(thing.getUID(), CHANNEL_LAST_UPDATE), LAST_UPDATE_TYPE_UID);
283 final ThingBuilder thingBuilder = editThing();
284 thingBuilder.withChannel(channelBuilder.build());
285 updateThing(thingBuilder.build());
290 * Reloads the calendar from local ical-file. Replaces the class internal calendar - if loading succeeds. Else
291 * logging details at warn-level logger.
293 * @return Whether the calendar was loaded successfully.
295 private boolean reloadCalendar() {
296 logger.trace("reloading calendar of {}", getThing().getUID());
297 if (!calendarFile.isFile()) {
298 logger.info("Local file for reloading calendar is missing.");
301 final ICalendarConfiguration config = configuration;
302 if (config == null) {
303 logger.warn("Can't reload calendar when configuration is missing.");
306 try (final FileInputStream fileStream = new FileInputStream(calendarFile)) {
307 final AbstractPresentableCalendar calendar = AbstractPresentableCalendar.create(fileStream);
308 runtimeCalendar = calendar;
309 rescheduleCalendarStateUpdate();
310 calendarDownloadedTime = Instant.ofEpochMilli(calendarFile.lastModified());
311 } catch (IOException | CalendarException e) {
312 logger.warn("Loading calendar failed: {}", e.getMessage());
319 * Reschedules the next update of the states.
321 private void rescheduleCalendarStateUpdate() {
322 final ScheduledFuture<?> currentUpdateJobFuture = updateJobFuture;
323 if (currentUpdateJobFuture != null) {
324 if (!(currentUpdateJobFuture.isCancelled() || currentUpdateJobFuture.isDone())) {
325 currentUpdateJobFuture.cancel(true);
327 updateJobFuture = null;
329 final AbstractPresentableCalendar currentCalendar = runtimeCalendar;
330 if (currentCalendar == null) {
333 final Instant now = Instant.now();
334 if (currentCalendar.isEventPresent(now)) {
335 final Event currentEvent = currentCalendar.getCurrentEvent(now);
336 if (currentEvent == null) {
338 "Could not schedule next update of states, due to unexpected behaviour of calendar implementation.");
341 updateJobFuture = scheduler.schedule(() -> {
342 ICalendarHandler.this.updateStates();
343 ICalendarHandler.this.rescheduleCalendarStateUpdate();
344 }, currentEvent.end.getEpochSecond() - now.getEpochSecond(), TimeUnit.SECONDS);
345 logger.debug("Scheduled update in {} seconds", currentEvent.end.getEpochSecond() - now.getEpochSecond());
347 final Event nextEvent = currentCalendar.getNextEvent(now);
348 final ICalendarConfiguration currentConfig = this.configuration;
349 if (currentConfig == null) {
350 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
351 "Something is broken, the configuration is not available.");
354 if (nextEvent == null) {
355 updateJobFuture = scheduler.schedule(() -> {
356 ICalendarHandler.this.rescheduleCalendarStateUpdate();
357 }, 1L, TimeUnit.DAYS);
358 logger.debug("Scheduled reschedule in 1 day");
360 updateJobFuture = scheduler.schedule(() -> {
361 ICalendarHandler.this.updateStates();
362 ICalendarHandler.this.rescheduleCalendarStateUpdate();
363 }, nextEvent.start.getEpochSecond() - now.getEpochSecond(), TimeUnit.SECONDS);
364 logger.debug("Scheduled update in {} seconds", nextEvent.start.getEpochSecond() - now.getEpochSecond());
371 * Updates the states of the Thing and its channels.
373 private void updateStates() {
374 logger.trace("updating states of {}", getThing().getUID());
375 final AbstractPresentableCalendar calendar = runtimeCalendar;
376 if (calendar == null) {
377 updateStatus(ThingStatus.OFFLINE);
379 updateStatus(ThingStatus.ONLINE);
381 final Instant now = Instant.now();
382 if (calendar.isEventPresent(now)) {
383 updateState(CHANNEL_CURRENT_EVENT_PRESENT, OnOffType.ON);
384 final Event currentEvent = calendar.getCurrentEvent(now);
385 if (currentEvent == null) {
386 logger.warn("Unexpected inconsistency of internal API. Not Updating event details.");
388 updateState(CHANNEL_CURRENT_EVENT_TITLE, new StringType(currentEvent.title));
389 updateState(CHANNEL_CURRENT_EVENT_START,
390 new DateTimeType(currentEvent.start.atZone(tzProvider.getTimeZone())));
391 updateState(CHANNEL_CURRENT_EVENT_END,
392 new DateTimeType(currentEvent.end.atZone(tzProvider.getTimeZone())));
395 updateState(CHANNEL_CURRENT_EVENT_PRESENT, OnOffType.OFF);
396 updateState(CHANNEL_CURRENT_EVENT_TITLE, UnDefType.UNDEF);
397 updateState(CHANNEL_CURRENT_EVENT_START, UnDefType.UNDEF);
398 updateState(CHANNEL_CURRENT_EVENT_END, UnDefType.UNDEF);
401 final Event nextEvent = calendar.getNextEvent(now);
402 if (nextEvent != null) {
403 updateState(CHANNEL_NEXT_EVENT_TITLE, new StringType(nextEvent.title));
404 updateState(CHANNEL_NEXT_EVENT_START,
405 new DateTimeType(nextEvent.start.atZone(tzProvider.getTimeZone())));
406 updateState(CHANNEL_NEXT_EVENT_END, new DateTimeType(nextEvent.end.atZone(tzProvider.getTimeZone())));
408 updateState(CHANNEL_NEXT_EVENT_TITLE, UnDefType.UNDEF);
409 updateState(CHANNEL_NEXT_EVENT_START, UnDefType.UNDEF);
410 updateState(CHANNEL_NEXT_EVENT_END, UnDefType.UNDEF);
413 final Instant lastUpdate = calendarDownloadedTime;
414 updateState(CHANNEL_LAST_UPDATE,
415 (lastUpdate != null ? new DateTimeType(lastUpdate.atZone(tzProvider.getTimeZone()))
418 // process all Command Tags in all Calendar Events which ENDED since updateStates was last called
419 // the END Event tags must be processed before the BEGIN ones
420 executeEventCommands(calendar.getJustEndedEvents(updateStatesLastCalledTime, now), CommandTagType.END);
422 // process all Command Tags in all Calendar Events which BEGAN since updateStates was last called
423 // the END Event tags must be processed before the BEGIN ones
424 executeEventCommands(calendar.getJustBegunEvents(updateStatesLastCalledTime, now), CommandTagType.BEGIN);
426 // save time when updateStates was previously called
427 // the purpose is to prevent repeat command execution of events that have already been executed
428 updateStatesLastCalledTime = now;
433 * Updates all children of this handler.
435 private void updateChildren() {
436 getThing().getThings().forEach(childThing -> updateChild(childThing.getHandler()));
440 * Updates a specific child handler.
442 * @param childHandler the handler to be updated
444 private void updateChild(@Nullable ThingHandler childHandler) {
445 if (childHandler instanceof CalendarUpdateListener) {
446 logger.trace("Notifying {} about fresh calendar.", childHandler.getThing().getUID());
448 ((CalendarUpdateListener) childHandler).onCalendarUpdated();
449 } catch (Exception e) {
450 logger.trace("The update of a child handler failed. Ignoring.", e);