]> git.basschouten.com Git - openhab-addons.git/blob
06c5c60d3f7ac42d3733df80f0a2aee8f58861cb
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.types.Command;
53 import org.openhab.core.types.RefreshType;
54 import org.openhab.core.types.UnDefType;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 /**
59  * The {@link ICalendarHandler} is responsible for handling commands, which are
60  * sent to one of the channels.
61  *
62  * @author Michael Wodniok - Initial contribution
63  * @author Andrew Fiddian-Green - Support for Command Tags embedded in the Event description
64  */
65 @NonNullByDefault
66 public class ICalendarHandler extends BaseBridgeHandler implements CalendarUpdateListener {
67
68     private final File calendarFile;
69     private @Nullable ICalendarConfiguration configuration;
70     private final EventPublisher eventPublisherCallback;
71     private final HttpClient httpClient;
72     private final Logger logger = LoggerFactory.getLogger(ICalendarHandler.class);
73     private final TimeZoneProvider tzProvider;
74     private @Nullable ScheduledFuture<?> pullJobFuture;
75     private @Nullable AbstractPresentableCalendar runtimeCalendar;
76     private @Nullable ScheduledFuture<?> updateJobFuture;
77     private Instant updateStatesLastCalledTime;
78     private @Nullable Instant calendarDownloadedTime;
79
80     public ICalendarHandler(Bridge bridge, HttpClient httpClient, EventPublisher eventPublisher,
81             TimeZoneProvider tzProvider) {
82         super(bridge);
83         this.httpClient = httpClient;
84         calendarFile = new File(OpenHAB.getUserDataFolder() + File.separator
85                 + getThing().getUID().getAsString().replaceAll("[<>:\"/\\\\|?*]", "_") + ".ical");
86         eventPublisherCallback = eventPublisher;
87         updateStatesLastCalledTime = Instant.now();
88         this.tzProvider = tzProvider;
89     }
90
91     @Override
92     public void dispose() {
93         final ScheduledFuture<?> currentUpdateJobFuture = updateJobFuture;
94         if (currentUpdateJobFuture != null) {
95             currentUpdateJobFuture.cancel(true);
96         }
97         final ScheduledFuture<?> currentPullJobFuture = pullJobFuture;
98         if (currentPullJobFuture != null) {
99             currentPullJobFuture.cancel(true);
100         }
101     }
102
103     @Override
104     public void handleCommand(ChannelUID channelUID, Command command) {
105         switch (channelUID.getId()) {
106             case CHANNEL_CURRENT_EVENT_PRESENT:
107             case CHANNEL_CURRENT_EVENT_TITLE:
108             case CHANNEL_CURRENT_EVENT_START:
109             case CHANNEL_CURRENT_EVENT_END:
110             case CHANNEL_NEXT_EVENT_TITLE:
111             case CHANNEL_NEXT_EVENT_START:
112             case CHANNEL_NEXT_EVENT_END:
113                 if (command instanceof RefreshType) {
114                     updateStates();
115                 }
116                 break;
117             default:
118                 logger.warn("Framework sent command to unknown channel with id '{}'", channelUID.getId());
119         }
120     }
121
122     @Override
123     public void initialize() {
124         final ICalendarConfiguration currentConfiguration = getConfigAs(ICalendarConfiguration.class);
125         configuration = currentConfiguration;
126
127         try {
128             if ((currentConfiguration.username == null && currentConfiguration.password != null)
129                     || (currentConfiguration.username != null && currentConfiguration.password == null)) {
130                 throw new ConfigBrokenException("Only one of username and password was set. This is invalid.");
131             }
132
133             PullJob regularPull;
134             final BigDecimal maxSizeBD = currentConfiguration.maxSize;
135             if (maxSizeBD == null || maxSizeBD.intValue() < 1) {
136                 throw new ConfigBrokenException(
137                         "maxSize is either not set or less than 1 (mebibyte), which is not allowed.");
138             }
139             final int maxSize = maxSizeBD.intValue();
140             try {
141                 regularPull = new PullJob(httpClient, new URI(currentConfiguration.url), currentConfiguration.username,
142                         currentConfiguration.password, calendarFile, maxSize * 1048576, this);
143             } catch (URISyntaxException e) {
144                 throw new ConfigBrokenException(String.format(
145                         "The URI '%s' for downloading the calendar contains syntax errors.", currentConfiguration.url));
146
147             }
148
149             final BigDecimal refreshTimeBD = currentConfiguration.refreshTime;
150             if (refreshTimeBD == null || refreshTimeBD.longValue() < 1) {
151                 throw new ConfigBrokenException(
152                         "refreshTime is either not set or less than 1 (minute), which is not allowed.");
153             }
154             final long refreshTime = refreshTimeBD.longValue();
155             if (calendarFile.isFile()) {
156                 updateStatus(ThingStatus.ONLINE);
157
158                 scheduler.submit(() -> {
159                     // reload calendar file asynchronously
160                     if (reloadCalendar()) {
161                         updateStates();
162                         updateChildren();
163                     } else {
164                         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
165                                 "The calendar seems to be configured correctly, but the local copy of calendar could not be loaded.");
166                     }
167                 });
168                 pullJobFuture = scheduler.scheduleWithFixedDelay(regularPull, refreshTime, refreshTime,
169                         TimeUnit.MINUTES);
170             } else {
171                 updateStatus(ThingStatus.OFFLINE);
172                 logger.debug(
173                         "The calendar is currently offline as no local copy exists. It will go online as soon as a valid valid calendar is retrieved.");
174                 pullJobFuture = scheduler.scheduleWithFixedDelay(regularPull, 0, refreshTime, TimeUnit.MINUTES);
175             }
176         } catch (ConfigBrokenException e) {
177             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
178         }
179     }
180
181     @Override
182     public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
183         final AbstractPresentableCalendar calendar = runtimeCalendar;
184         if (calendar != null) {
185             updateChild(childHandler);
186         }
187     }
188
189     @Override
190     public void onCalendarUpdated() {
191         if (reloadCalendar()) {
192             updateStates();
193             updateChildren();
194         } else {
195             logger.trace("Calendar was updated, but loading failed.");
196         }
197     }
198
199     /**
200      * @return the calendar that is used for all operations
201      */
202     @Nullable
203     public AbstractPresentableCalendar getRuntimeCalendar() {
204         return runtimeCalendar;
205     }
206
207     private void executeEventCommands(List<Event> events, CommandTagType execTime) {
208         // no begun or ended events => exit quietly as there is nothing to do
209         if (events.isEmpty()) {
210             return;
211         }
212
213         final ICalendarConfiguration syncConfiguration = configuration;
214         if (syncConfiguration == null) {
215             logger.debug("Configuration not instantiated!");
216             return;
217         }
218         // loop through all events in the list
219         for (Event event : events) {
220
221             // loop through all command tags in the event
222             for (CommandTag cmdTag : event.commandTags) {
223
224                 // only process the BEGIN resp. END tags
225                 if (cmdTag.getTagType() != execTime) {
226                     continue;
227                 }
228                 if (!cmdTag.isAuthorized(syncConfiguration.authorizationCode)) {
229                     logger.warn("Event: {}, Command Tag: {} => Command not authorized!", event.title,
230                             cmdTag.getFullTag());
231                     continue;
232                 }
233
234                 final Command cmdState = cmdTag.getCommand();
235                 if (cmdState == null) {
236                     logger.warn("Event: {}, Command Tag: {} => Error creating Command State!", event.title,
237                             cmdTag.getFullTag());
238                     continue;
239                 }
240
241                 // (try to) execute the command
242                 try {
243                     eventPublisherCallback.post(ItemEventFactory.createCommandEvent(cmdTag.getItemName(), cmdState));
244                     if (logger.isDebugEnabled()) {
245                         String cmdType = cmdState.getClass().toString();
246                         int index = cmdType.lastIndexOf(".") + 1;
247                         if ((index > 0) && (index < cmdType.length())) {
248                             cmdType = cmdType.substring(index);
249                         }
250                         logger.debug("Event: {}, Command Tag: {} => {}.postUpdate({}: {})", event.title,
251                                 cmdTag.getFullTag(), cmdTag.getItemName(), cmdType, cmdState);
252                     }
253                 } catch (IllegalArgumentException | IllegalStateException e) {
254                     logger.warn("Event: {}, Command Tag: {} => Unable to push command to target item!", event.title,
255                             cmdTag.getFullTag());
256                     logger.debug("Exception occured while pushing to item!", e);
257                 }
258             }
259         }
260     }
261
262     /**
263      * Reloads the calendar from local ical-file. Replaces the class internal calendar - if loading succeeds. Else
264      * logging details at warn-level logger.
265      *
266      * @return Whether the calendar was loaded successfully.
267      */
268     private boolean reloadCalendar() {
269         if (!calendarFile.isFile()) {
270             logger.info("Local file for reloading calendar is missing.");
271             return false;
272         }
273         final ICalendarConfiguration config = configuration;
274         if (config == null) {
275             logger.warn("Can't reload calendar when configuration is missing.");
276             return false;
277         }
278         try (final FileInputStream fileStream = new FileInputStream(calendarFile)) {
279             final AbstractPresentableCalendar calendar = AbstractPresentableCalendar.create(fileStream);
280             runtimeCalendar = calendar;
281             rescheduleCalendarStateUpdate();
282             calendarDownloadedTime = Instant.ofEpochMilli(calendarFile.lastModified());
283         } catch (IOException | CalendarException e) {
284             logger.warn("Loading calendar failed: {}", e.getMessage());
285             return false;
286         }
287         return true;
288     }
289
290     /**
291      * Reschedules the next update of the states.
292      */
293     private void rescheduleCalendarStateUpdate() {
294         final ScheduledFuture<?> currentUpdateJobFuture = updateJobFuture;
295         if (currentUpdateJobFuture != null) {
296             if (!(currentUpdateJobFuture.isCancelled() || currentUpdateJobFuture.isDone())) {
297                 currentUpdateJobFuture.cancel(true);
298             }
299             updateJobFuture = null;
300         }
301         final AbstractPresentableCalendar currentCalendar = runtimeCalendar;
302         if (currentCalendar == null) {
303             return;
304         }
305         final Instant now = Instant.now();
306         if (currentCalendar.isEventPresent(now)) {
307             final Event currentEvent = currentCalendar.getCurrentEvent(now);
308             if (currentEvent == null) {
309                 logger.debug(
310                         "Could not schedule next update of states, due to unexpected behaviour of calendar implementation.");
311                 return;
312             }
313             updateJobFuture = scheduler.schedule(() -> {
314                 ICalendarHandler.this.updateStates();
315                 ICalendarHandler.this.rescheduleCalendarStateUpdate();
316             }, currentEvent.end.getEpochSecond() - now.getEpochSecond(), TimeUnit.SECONDS);
317         } else {
318             final Event nextEvent = currentCalendar.getNextEvent(now);
319             final ICalendarConfiguration currentConfig = this.configuration;
320             if (currentConfig == null) {
321                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
322                         "Something is broken, the configuration is not available.");
323                 return;
324             }
325             if (nextEvent == null) {
326                 updateJobFuture = scheduler.schedule(() -> {
327                     ICalendarHandler.this.rescheduleCalendarStateUpdate();
328                 }, 1L, TimeUnit.DAYS);
329             } else {
330                 updateJobFuture = scheduler.schedule(() -> {
331                     ICalendarHandler.this.updateStates();
332                     ICalendarHandler.this.rescheduleCalendarStateUpdate();
333                 }, nextEvent.start.getEpochSecond() - now.getEpochSecond(), TimeUnit.SECONDS);
334             }
335         }
336     }
337
338     /**
339      * Updates the states of the Thing and its channels.
340      */
341     private void updateStates() {
342         final AbstractPresentableCalendar calendar = runtimeCalendar;
343         if (calendar == null) {
344             updateStatus(ThingStatus.OFFLINE);
345         } else {
346             updateStatus(ThingStatus.ONLINE);
347
348             final Instant now = Instant.now();
349             if (calendar.isEventPresent(now)) {
350                 updateState(CHANNEL_CURRENT_EVENT_PRESENT, OnOffType.ON);
351                 final Event currentEvent = calendar.getCurrentEvent(now);
352                 if (currentEvent == null) {
353                     logger.warn("Unexpected inconsistency of internal API. Not Updating event details.");
354                 } else {
355                     updateState(CHANNEL_CURRENT_EVENT_TITLE, new StringType(currentEvent.title));
356                     updateState(CHANNEL_CURRENT_EVENT_START,
357                             new DateTimeType(currentEvent.start.atZone(tzProvider.getTimeZone())));
358                     updateState(CHANNEL_CURRENT_EVENT_END,
359                             new DateTimeType(currentEvent.end.atZone(tzProvider.getTimeZone())));
360                 }
361             } else {
362                 updateState(CHANNEL_CURRENT_EVENT_PRESENT, OnOffType.OFF);
363                 updateState(CHANNEL_CURRENT_EVENT_TITLE, UnDefType.UNDEF);
364                 updateState(CHANNEL_CURRENT_EVENT_START, UnDefType.UNDEF);
365                 updateState(CHANNEL_CURRENT_EVENT_END, UnDefType.UNDEF);
366             }
367
368             final Event nextEvent = calendar.getNextEvent(now);
369             if (nextEvent != null) {
370                 updateState(CHANNEL_NEXT_EVENT_TITLE, new StringType(nextEvent.title));
371                 updateState(CHANNEL_NEXT_EVENT_START,
372                         new DateTimeType(nextEvent.start.atZone(tzProvider.getTimeZone())));
373                 updateState(CHANNEL_NEXT_EVENT_END, new DateTimeType(nextEvent.end.atZone(tzProvider.getTimeZone())));
374             } else {
375                 updateState(CHANNEL_NEXT_EVENT_TITLE, UnDefType.UNDEF);
376                 updateState(CHANNEL_NEXT_EVENT_START, UnDefType.UNDEF);
377                 updateState(CHANNEL_NEXT_EVENT_END, UnDefType.UNDEF);
378             }
379
380             final Instant lastUpdate = calendarDownloadedTime;
381             updateState(CHANNEL_LAST_UPDATE,
382                     (lastUpdate != null ? new DateTimeType(lastUpdate.atZone(tzProvider.getTimeZone()))
383                             : UnDefType.UNDEF));
384
385             // process all Command Tags in all Calendar Events which ENDED since updateStates was last called
386             // the END Event tags must be processed before the BEGIN ones
387             executeEventCommands(calendar.getJustEndedEvents(updateStatesLastCalledTime, now), CommandTagType.END);
388
389             // process all Command Tags in all Calendar Events which BEGAN since updateStates was last called
390             // the END Event tags must be processed before the BEGIN ones
391             executeEventCommands(calendar.getJustBegunEvents(updateStatesLastCalledTime, now), CommandTagType.BEGIN);
392
393             // save time when updateStates was previously called
394             // the purpose is to prevent repeat command execution of events that have already been executed
395             updateStatesLastCalledTime = now;
396         }
397     }
398
399     /**
400      * Updates all children of this handler.
401      */
402     private void updateChildren() {
403         getThing().getThings().forEach(childThing -> updateChild(childThing.getHandler()));
404     }
405
406     /**
407      * Updates a specific child handler.
408      *
409      * @param childHandler the handler to be updated
410      */
411     private void updateChild(@Nullable ThingHandler childHandler) {
412         if (childHandler instanceof CalendarUpdateListener) {
413             logger.trace("Notifying {} about fresh calendar.", childHandler.getThing().getUID());
414             try {
415                 ((CalendarUpdateListener) childHandler).onCalendarUpdated();
416             } catch (Exception e) {
417                 logger.trace("The update of a child handler failed. Ignoring.", e);
418             }
419         }
420     }
421 }