]> git.basschouten.com Git - openhab-addons.git/blob
916017b0e30ff08b8ce463ec509d25768ef5615d
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.icalendar.internal.handler;
14
15 import static org.openhab.binding.icalendar.internal.ICalendarBindingConstants.*;
16
17 import java.io.File;
18 import java.io.FileInputStream;
19 import java.io.IOException;
20 import java.math.BigDecimal;
21 import java.net.URI;
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;
27
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;
60
61 /**
62  * The {@link ICalendarHandler} is responsible for handling commands, which are
63  * sent to one of the channels.
64  *
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  */
69 @NonNullByDefault
70 public class ICalendarHandler extends BaseBridgeHandler implements CalendarUpdateListener {
71
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;
83
84     public ICalendarHandler(Bridge bridge, HttpClient httpClient, EventPublisher eventPublisher,
85             TimeZoneProvider tzProvider) {
86         super(bridge);
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;
93     }
94
95     @Override
96     public void dispose() {
97         final ScheduledFuture<?> currentUpdateJobFuture = updateJobFuture;
98         if (currentUpdateJobFuture != null) {
99             currentUpdateJobFuture.cancel(true);
100         }
101         final ScheduledFuture<?> currentPullJobFuture = pullJobFuture;
102         if (currentPullJobFuture != null) {
103             currentPullJobFuture.cancel(true);
104         }
105     }
106
107     @Override
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) {
119                     updateStates();
120                 }
121                 break;
122             default:
123                 logger.warn("Framework sent command to unknown channel with id '{}'", channelUID.getId());
124         }
125     }
126
127     @Override
128     public void initialize() {
129         migrateLastUpdateChannel();
130
131         final ICalendarConfiguration currentConfiguration = getConfigAs(ICalendarConfiguration.class);
132         configuration = currentConfiguration;
133
134         try {
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.");
138             }
139
140             PullJob regularPull;
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.");
145             }
146             final int maxSize = maxSizeBD.intValue();
147             try {
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));
153
154             }
155
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.");
160             }
161             final long refreshTime = refreshTimeBD.longValue();
162             if (calendarFile.isFile()) {
163                 updateStatus(ThingStatus.ONLINE);
164
165                 scheduler.submit(() -> {
166                     // reload calendar file asynchronously
167                     if (reloadCalendar()) {
168                         updateStates();
169                         updateChildren();
170                     } else {
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.");
173                     }
174                 });
175                 pullJobFuture = scheduler.scheduleWithFixedDelay(regularPull, refreshTime, refreshTime,
176                         TimeUnit.MINUTES);
177             } else {
178                 updateStatus(ThingStatus.OFFLINE);
179                 logger.debug(
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);
182             }
183         } catch (ConfigBrokenException e) {
184             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
185         }
186     }
187
188     @Override
189     public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
190         final AbstractPresentableCalendar calendar = runtimeCalendar;
191         if (calendar != null) {
192             updateChild(childHandler);
193         }
194     }
195
196     @Override
197     public void onCalendarUpdated() {
198         if (reloadCalendar()) {
199             updateStates();
200             updateChildren();
201         } else {
202             logger.trace("Calendar was updated, but loading failed.");
203         }
204     }
205
206     /**
207      * @return the calendar that is used for all operations
208      */
209     @Nullable
210     public AbstractPresentableCalendar getRuntimeCalendar() {
211         return runtimeCalendar;
212     }
213
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()) {
217             return;
218         }
219
220         final ICalendarConfiguration syncConfiguration = configuration;
221         if (syncConfiguration == null) {
222             logger.debug("Configuration not instantiated!");
223             return;
224         }
225         // loop through all events in the list
226         for (Event event : events) {
227
228             // loop through all command tags in the event
229             for (CommandTag cmdTag : event.commandTags) {
230
231                 // only process the BEGIN resp. END tags
232                 if (cmdTag.getTagType() != execTime) {
233                     continue;
234                 }
235                 if (!cmdTag.isAuthorized(syncConfiguration.authorizationCode)) {
236                     logger.warn("Event: {}, Command Tag: {} => Command not authorized!", event.title,
237                             cmdTag.getFullTag());
238                     continue;
239                 }
240
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());
245                     continue;
246                 }
247
248                 // (try to) execute the command
249                 try {
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);
256                         }
257                         logger.debug("Event: {}, Command Tag: {} => {}.postUpdate({}: {})", event.title,
258                                 cmdTag.getFullTag(), cmdTag.getItemName(), cmdType, cmdState);
259                     }
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);
264                 }
265             }
266         }
267     }
268
269     /**
270      * Migration for last_update-channel as this change is compatible to previous instances.
271      */
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.");
279                 return;
280             }
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());
286         }
287     }
288
289     /**
290      * Reloads the calendar from local ical-file. Replaces the class internal calendar - if loading succeeds. Else
291      * logging details at warn-level logger.
292      *
293      * @return Whether the calendar was loaded successfully.
294      */
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.");
299             return false;
300         }
301         final ICalendarConfiguration config = configuration;
302         if (config == null) {
303             logger.warn("Can't reload calendar when configuration is missing.");
304             return false;
305         }
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());
313             return false;
314         }
315         return true;
316     }
317
318     /**
319      * Reschedules the next update of the states.
320      */
321     private void rescheduleCalendarStateUpdate() {
322         final ScheduledFuture<?> currentUpdateJobFuture = updateJobFuture;
323         if (currentUpdateJobFuture != null) {
324             if (!(currentUpdateJobFuture.isCancelled() || currentUpdateJobFuture.isDone())) {
325                 currentUpdateJobFuture.cancel(true);
326             }
327             updateJobFuture = null;
328         }
329         final AbstractPresentableCalendar currentCalendar = runtimeCalendar;
330         if (currentCalendar == null) {
331             return;
332         }
333         final Instant now = Instant.now();
334         if (currentCalendar.isEventPresent(now)) {
335             final Event currentEvent = currentCalendar.getCurrentEvent(now);
336             if (currentEvent == null) {
337                 logger.debug(
338                         "Could not schedule next update of states, due to unexpected behaviour of calendar implementation.");
339                 return;
340             }
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());
346         } else {
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.");
352                 return;
353             }
354             if (nextEvent == null) {
355                 updateJobFuture = scheduler.schedule(() -> {
356                     ICalendarHandler.this.rescheduleCalendarStateUpdate();
357                 }, 1L, TimeUnit.DAYS);
358                 logger.debug("Scheduled reschedule in 1 day");
359             } else {
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());
365
366             }
367         }
368     }
369
370     /**
371      * Updates the states of the Thing and its channels.
372      */
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);
378         } else {
379             updateStatus(ThingStatus.ONLINE);
380
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.");
387                 } else {
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())));
393                 }
394             } else {
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);
399             }
400
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())));
407             } else {
408                 updateState(CHANNEL_NEXT_EVENT_TITLE, UnDefType.UNDEF);
409                 updateState(CHANNEL_NEXT_EVENT_START, UnDefType.UNDEF);
410                 updateState(CHANNEL_NEXT_EVENT_END, UnDefType.UNDEF);
411             }
412
413             final Instant lastUpdate = calendarDownloadedTime;
414             updateState(CHANNEL_LAST_UPDATE,
415                     (lastUpdate != null ? new DateTimeType(lastUpdate.atZone(tzProvider.getTimeZone()))
416                             : UnDefType.UNDEF));
417
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);
421
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);
425
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;
429         }
430     }
431
432     /**
433      * Updates all children of this handler.
434      */
435     private void updateChildren() {
436         getThing().getThings().forEach(childThing -> updateChild(childThing.getHandler()));
437     }
438
439     /**
440      * Updates a specific child handler.
441      *
442      * @param childHandler the handler to be updated
443      */
444     private void updateChild(@Nullable ThingHandler childHandler) {
445         if (childHandler instanceof CalendarUpdateListener) {
446             logger.trace("Notifying {} about fresh calendar.", childHandler.getThing().getUID());
447             try {
448                 ((CalendarUpdateListener) childHandler).onCalendarUpdated();
449             } catch (Exception e) {
450                 logger.trace("The update of a child handler failed. Ignoring.", e);
451             }
452         }
453     }
454 }