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.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
68 * @author Michael Wodniok - Changed calculation of Future for refresh of channels
71 public class ICalendarHandler extends BaseBridgeHandler implements CalendarUpdateListener {
73 private final File calendarFile;
74 private @Nullable ICalendarConfiguration configuration;
75 private final EventPublisher eventPublisherCallback;
76 private final HttpClient httpClient;
77 private final Logger logger = LoggerFactory.getLogger(ICalendarHandler.class);
78 private final TimeZoneProvider tzProvider;
79 private @Nullable ScheduledFuture<?> pullJobFuture;
80 private @Nullable AbstractPresentableCalendar runtimeCalendar;
81 private @Nullable ScheduledFuture<?> updateJobFuture;
82 private Instant updateStatesLastCalledTime;
83 private @Nullable Instant calendarDownloadedTime;
85 public ICalendarHandler(Bridge bridge, HttpClient httpClient, EventPublisher eventPublisher,
86 TimeZoneProvider tzProvider) {
88 this.httpClient = httpClient;
89 final File cacheFolder = new File(new File(OpenHAB.getUserDataFolder(), "cache"),
90 "org.openhab.binding.icalendar");
91 if (!cacheFolder.exists()) {
92 logger.debug("Creating cache folder '{}'", cacheFolder.getAbsolutePath());
95 calendarFile = new File(cacheFolder,
96 getThing().getUID().getAsString().replaceAll("[<>:\"/\\\\|?*]", "_") + ".ical");
97 eventPublisherCallback = eventPublisher;
98 updateStatesLastCalledTime = Instant.now();
99 this.tzProvider = tzProvider;
103 public void dispose() {
104 final ScheduledFuture<?> currentUpdateJobFuture = updateJobFuture;
105 if (currentUpdateJobFuture != null) {
106 currentUpdateJobFuture.cancel(true);
108 final ScheduledFuture<?> currentPullJobFuture = pullJobFuture;
109 if (currentPullJobFuture != null) {
110 currentPullJobFuture.cancel(true);
115 public void handleCommand(ChannelUID channelUID, Command command) {
116 switch (channelUID.getId()) {
117 case CHANNEL_CURRENT_EVENT_PRESENT:
118 case CHANNEL_CURRENT_EVENT_TITLE:
119 case CHANNEL_CURRENT_EVENT_START:
120 case CHANNEL_CURRENT_EVENT_END:
121 case CHANNEL_NEXT_EVENT_TITLE:
122 case CHANNEL_NEXT_EVENT_START:
123 case CHANNEL_NEXT_EVENT_END:
124 case CHANNEL_LAST_UPDATE:
125 if (command instanceof RefreshType) {
130 logger.warn("Framework sent command to unknown channel with id '{}'", channelUID.getId());
135 public void initialize() {
136 migrateLastUpdateChannel();
138 final ICalendarConfiguration currentConfiguration = getConfigAs(ICalendarConfiguration.class);
139 configuration = currentConfiguration;
142 if ((currentConfiguration.username == null && currentConfiguration.password != null)
143 || (currentConfiguration.username != null && currentConfiguration.password == null)) {
144 throw new ConfigBrokenException("Only one of username and password was set. This is invalid.");
148 final BigDecimal maxSizeBD = currentConfiguration.maxSize;
149 if (maxSizeBD == null || maxSizeBD.intValue() < 1) {
150 throw new ConfigBrokenException(
151 "maxSize is either not set or less than 1 (mebibyte), which is not allowed.");
153 final int maxSize = maxSizeBD.intValue();
155 regularPull = new PullJob(httpClient, new URI(currentConfiguration.url), currentConfiguration.username,
156 currentConfiguration.password, calendarFile, maxSize * 1048576, this);
157 } catch (URISyntaxException e) {
158 throw new ConfigBrokenException(String.format(
159 "The URI '%s' for downloading the calendar contains syntax errors.", currentConfiguration.url));
163 final BigDecimal refreshTimeBD = currentConfiguration.refreshTime;
164 if (refreshTimeBD == null || refreshTimeBD.longValue() < 1) {
165 throw new ConfigBrokenException(
166 "refreshTime is either not set or less than 1 (minute), which is not allowed.");
168 final long refreshTime = refreshTimeBD.longValue();
169 if (calendarFile.isFile()) {
170 updateStatus(ThingStatus.ONLINE);
172 scheduler.submit(() -> {
173 // reload calendar file asynchronously
174 if (reloadCalendar()) {
178 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
179 "The calendar seems to be configured correctly, but the local copy of calendar could not be loaded.");
182 pullJobFuture = scheduler.scheduleWithFixedDelay(regularPull, refreshTime, refreshTime,
185 updateStatus(ThingStatus.OFFLINE);
187 "The calendar is currently offline as no local copy exists. It will go online as soon as a valid valid calendar is retrieved.");
188 pullJobFuture = scheduler.scheduleWithFixedDelay(regularPull, 0, refreshTime, TimeUnit.MINUTES);
190 } catch (ConfigBrokenException e) {
191 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
196 public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
197 final AbstractPresentableCalendar calendar = runtimeCalendar;
198 if (calendar != null) {
199 updateChild(childHandler);
204 public void onCalendarUpdated() {
205 if (reloadCalendar()) {
209 logger.trace("Calendar was updated, but loading failed.");
214 * @return the calendar that is used for all operations
217 public AbstractPresentableCalendar getRuntimeCalendar() {
218 return runtimeCalendar;
221 private void executeEventCommands(List<Event> events, CommandTagType execTime) {
222 // no begun or ended events => exit quietly as there is nothing to do
223 if (events.isEmpty()) {
227 final ICalendarConfiguration syncConfiguration = configuration;
228 if (syncConfiguration == null) {
229 logger.debug("Configuration not instantiated!");
232 // loop through all events in the list
233 for (Event event : events) {
235 // loop through all command tags in the event
236 for (CommandTag cmdTag : event.commandTags) {
238 // only process the BEGIN resp. END tags
239 if (cmdTag.getTagType() != execTime) {
242 if (!cmdTag.isAuthorized(syncConfiguration.authorizationCode)) {
243 logger.warn("Event: {}, Command Tag: {} => Command not authorized!", event.title,
244 cmdTag.getFullTag());
248 final Command cmdState = cmdTag.getCommand();
249 if (cmdState == null) {
250 logger.warn("Event: {}, Command Tag: {} => Error creating Command State!", event.title,
251 cmdTag.getFullTag());
255 // (try to) execute the command
257 eventPublisherCallback.post(ItemEventFactory.createCommandEvent(cmdTag.getItemName(), cmdState));
258 if (logger.isDebugEnabled()) {
259 String cmdType = cmdState.getClass().toString();
260 int index = cmdType.lastIndexOf(".") + 1;
261 if ((index > 0) && (index < cmdType.length())) {
262 cmdType = cmdType.substring(index);
264 logger.debug("Event: {}, Command Tag: {} => {}.postUpdate({}: {})", event.title,
265 cmdTag.getFullTag(), cmdTag.getItemName(), cmdType, cmdState);
267 } catch (IllegalArgumentException | IllegalStateException e) {
268 logger.warn("Event: {}, Command Tag: {} => Unable to push command to target item!", event.title,
269 cmdTag.getFullTag());
270 logger.debug("Exception occured while pushing to item!", e);
277 * Migration for last_update-channel as this change is compatible to previous instances.
279 private void migrateLastUpdateChannel() {
280 final Thing thing = getThing();
281 if (thing.getChannel(CHANNEL_LAST_UPDATE) == null) {
282 logger.trace("last_update channel is missing in this Thing. Adding it.");
283 final ThingHandlerCallback callback = getCallback();
284 if (callback == null) {
285 logger.debug("ThingHandlerCallback is null. Skipping migration of last_update channel.");
288 final ChannelBuilder channelBuilder = callback
289 .createChannelBuilder(new ChannelUID(thing.getUID(), CHANNEL_LAST_UPDATE), LAST_UPDATE_TYPE_UID);
290 final ThingBuilder thingBuilder = editThing();
291 thingBuilder.withChannel(channelBuilder.build());
292 updateThing(thingBuilder.build());
297 * Reloads the calendar from local ical-file. Replaces the class internal calendar - if loading succeeds. Else
298 * logging details at warn-level logger.
300 * @return Whether the calendar was loaded successfully.
302 private boolean reloadCalendar() {
303 logger.trace("reloading calendar of {}", getThing().getUID());
304 if (!calendarFile.isFile()) {
305 logger.info("Local file for reloading calendar is missing.");
308 final ICalendarConfiguration config = configuration;
309 if (config == null) {
310 logger.warn("Can't reload calendar when configuration is missing.");
313 try (final FileInputStream fileStream = new FileInputStream(calendarFile)) {
314 final AbstractPresentableCalendar calendar = AbstractPresentableCalendar.create(fileStream);
315 runtimeCalendar = calendar;
316 rescheduleCalendarStateUpdate();
317 calendarDownloadedTime = Instant.ofEpochMilli(calendarFile.lastModified());
318 } catch (IOException | CalendarException e) {
319 logger.warn("Loading calendar failed: {}", e.getMessage());
326 * Reschedules the next update of the states.
328 private void rescheduleCalendarStateUpdate() {
329 final ScheduledFuture<?> currentUpdateJobFuture = updateJobFuture;
330 if (currentUpdateJobFuture != null) {
331 if (!(currentUpdateJobFuture.isCancelled() || currentUpdateJobFuture.isDone())) {
332 currentUpdateJobFuture.cancel(true);
334 updateJobFuture = null;
336 final AbstractPresentableCalendar currentCalendar = runtimeCalendar;
337 if (currentCalendar == null) {
340 final Instant now = Instant.now();
341 Instant nextRegularUpdate = null;
342 if (currentCalendar.isEventPresent(now)) {
343 final Event currentEvent = currentCalendar.getCurrentEvent(now);
344 if (currentEvent == null) {
346 "Could not schedule next update of states, due to unexpected behaviour of calendar implementation.");
349 nextRegularUpdate = currentEvent.end;
352 final Event nextEvent = currentCalendar.getNextEvent(now);
353 final ICalendarConfiguration currentConfig = this.configuration;
354 if (currentConfig == null) {
355 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
356 "Something is broken, the configuration is not available.");
359 if (nextEvent != null) {
360 if (nextRegularUpdate == null || nextEvent.start.isBefore(nextRegularUpdate)) {
361 nextRegularUpdate = nextEvent.start;
365 if (nextRegularUpdate != null) {
366 updateJobFuture = scheduler.schedule(() -> {
367 ICalendarHandler.this.updateStates();
368 ICalendarHandler.this.rescheduleCalendarStateUpdate();
369 }, nextRegularUpdate.getEpochSecond() - now.getEpochSecond(), TimeUnit.SECONDS);
370 logger.debug("Scheduled update in {} seconds", nextRegularUpdate.getEpochSecond() - now.getEpochSecond());
372 updateJobFuture = scheduler.schedule(() -> {
373 ICalendarHandler.this.rescheduleCalendarStateUpdate();
374 }, 1L, TimeUnit.DAYS);
375 logger.debug("Scheduled reschedule in 1 day");
380 * Updates the states of the Thing and its channels.
382 private void updateStates() {
383 logger.trace("updating states of {}", getThing().getUID());
384 final AbstractPresentableCalendar calendar = runtimeCalendar;
385 if (calendar == null) {
386 updateStatus(ThingStatus.OFFLINE);
388 updateStatus(ThingStatus.ONLINE);
390 final Instant now = Instant.now();
391 if (calendar.isEventPresent(now)) {
392 updateState(CHANNEL_CURRENT_EVENT_PRESENT, OnOffType.ON);
393 final Event currentEvent = calendar.getCurrentEvent(now);
394 if (currentEvent == null) {
395 logger.warn("Unexpected inconsistency of internal API. Not Updating event details.");
397 updateState(CHANNEL_CURRENT_EVENT_TITLE, new StringType(currentEvent.title));
398 updateState(CHANNEL_CURRENT_EVENT_START,
399 new DateTimeType(currentEvent.start.atZone(tzProvider.getTimeZone())));
400 updateState(CHANNEL_CURRENT_EVENT_END,
401 new DateTimeType(currentEvent.end.atZone(tzProvider.getTimeZone())));
404 updateState(CHANNEL_CURRENT_EVENT_PRESENT, OnOffType.OFF);
405 updateState(CHANNEL_CURRENT_EVENT_TITLE, UnDefType.UNDEF);
406 updateState(CHANNEL_CURRENT_EVENT_START, UnDefType.UNDEF);
407 updateState(CHANNEL_CURRENT_EVENT_END, UnDefType.UNDEF);
410 final Event nextEvent = calendar.getNextEvent(now);
411 if (nextEvent != null) {
412 updateState(CHANNEL_NEXT_EVENT_TITLE, new StringType(nextEvent.title));
413 updateState(CHANNEL_NEXT_EVENT_START,
414 new DateTimeType(nextEvent.start.atZone(tzProvider.getTimeZone())));
415 updateState(CHANNEL_NEXT_EVENT_END, new DateTimeType(nextEvent.end.atZone(tzProvider.getTimeZone())));
417 updateState(CHANNEL_NEXT_EVENT_TITLE, UnDefType.UNDEF);
418 updateState(CHANNEL_NEXT_EVENT_START, UnDefType.UNDEF);
419 updateState(CHANNEL_NEXT_EVENT_END, UnDefType.UNDEF);
422 final Instant lastUpdate = calendarDownloadedTime;
423 updateState(CHANNEL_LAST_UPDATE,
424 (lastUpdate != null ? new DateTimeType(lastUpdate.atZone(tzProvider.getTimeZone()))
427 // process all Command Tags in all Calendar Events which ENDED since updateStates was last called
428 // the END Event tags must be processed before the BEGIN ones
429 executeEventCommands(calendar.getJustEndedEvents(updateStatesLastCalledTime, now), CommandTagType.END);
431 // process all Command Tags in all Calendar Events which BEGAN since updateStates was last called
432 // the END Event tags must be processed before the BEGIN ones
433 executeEventCommands(calendar.getJustBegunEvents(updateStatesLastCalledTime, now), CommandTagType.BEGIN);
435 // save time when updateStates was previously called
436 // the purpose is to prevent repeat command execution of events that have already been executed
437 updateStatesLastCalledTime = now;
442 * Updates all children of this handler.
444 private void updateChildren() {
445 getThing().getThings().forEach(childThing -> updateChild(childThing.getHandler()));
449 * Updates a specific child handler.
451 * @param childHandler the handler to be updated
453 private void updateChild(@Nullable ThingHandler childHandler) {
454 if (childHandler instanceof CalendarUpdateListener updateListener) {
455 logger.trace("Notifying {} about fresh calendar.", childHandler.getThing().getUID());
457 updateListener.onCalendarUpdated();
458 } catch (Exception e) {
459 logger.trace("The update of a child handler failed. Ignoring.", e);