Search in sources :

Example 6 with CalDavEvent

use of org.openhab.io.caldav.CalDavEvent in project openhab1-addons by openhab.

the class CalDavBinding method updateItemState.

private void updateItemState(CalDavNextEventConfig config, List<CalDavEvent> events) {
    String itemName = config.getItemNameToListenTo();
    String itemNamePreview = config.getItemName();
    logger.trace("update item state for item: {}", itemName);
    Command state = null;
    DateTime time = null;
    if (calDavLoader == null) {
        logger.warn("caldav loader is not set");
        return;
    }
    for (CalDavEvent calDavEvent : events) {
        try {
            final Item item = this.itemRegistry.getItem(itemName);
            final List<EventUtils.EventContent> parseContent = EventUtils.parseContent(calDavEvent, item);
            for (EventUtils.EventContent eventContent : parseContent) {
                if (!eventContent.getTime().isBefore(DateTime.now()) && (time == null || time.isAfter(eventContent.getTime()))) {
                    time = eventContent.getTime();
                    state = eventContent.getCommand();
                }
            }
        } catch (ItemNotFoundException e) {
            logger.error("item {} could not be found", itemName);
        }
    }
    if (time == null && config.getType() != CalDavType.DISABLE) {
        // no item found
        eventPublisher.postUpdate(itemNamePreview, org.openhab.core.types.UnDefType.UNDEF);
        return;
    }
    CalDavType type = config.getType();
    logger.trace("handling event of type: {}", type);
    if (type == CalDavType.VALUE) {
        logger.debug("setting value for '{}' to: {}", itemNamePreview, state);
        eventPublisher.sendCommand(itemNamePreview, state);
    } else if (type == CalDavType.DATE) {
        Command c = new DateTimeType(FORMATTER.print(time));
        logger.debug("setting value for '{}' to: {}", itemNamePreview, c);
        eventPublisher.sendCommand(itemNamePreview, c);
    } else if (type == CalDavType.DISABLE) {
        // nothing to do
        return;
    } else {
        logger.warn("unhandled type: {}", type);
    }
}
Also used : Item(org.openhab.core.items.Item) DateTimeType(org.openhab.core.library.types.DateTimeType) Command(org.openhab.core.types.Command) CalDavEvent(org.openhab.io.caldav.CalDavEvent) EventUtils(org.openhab.io.caldav.EventUtils) DateTime(org.joda.time.DateTime) ItemNotFoundException(org.openhab.core.items.ItemNotFoundException)

Example 7 with CalDavEvent

use of org.openhab.io.caldav.CalDavEvent in project openhab1-addons by openhab.

the class CalDavBinding method bindingChanged.

@Override
public void bindingChanged(BindingProvider provider, String itemName) {
    if (provider.getItemNames().contains(itemName)) {
        final CalDavNextEventConfig config = ((CalDavBindingProvider) provider).getConfig(itemName);
        List<CalDavEvent> events = calDavLoader.getEvents(new CalDavQuery(this.readCalendars, DateTime.now()));
        this.updateItemState(config, events);
    }
}
Also used : CalDavEvent(org.openhab.io.caldav.CalDavEvent) CalDavBindingProvider(org.openhab.binding.caldav_command.CalDavBindingProvider) CalDavQuery(org.openhab.io.caldav.CalDavQuery)

Example 8 with CalDavEvent

use of org.openhab.io.caldav.CalDavEvent in project openhab1-addons by openhab.

the class CalDavBinding method updateItem.

private synchronized void updateItem(String itemName, CalDavConfig config, List<CalDavEvent> events) {
    if (config.getType() == Type.PRESENCE) {
        List<CalDavEvent> subList = getActiveEvents(events);
        subList = this.removeWithMatchingPlace(subList);
        if (subList.size() == 0) {
            eventPublisher.sendCommand(itemName, OnOffType.OFF);
        } else {
            eventPublisher.sendCommand(itemName, OnOffType.ON);
        }
    } else {
        List<CalDavEvent> subList = new ArrayList<CalDavEvent>();
        if (config.getType() == Type.EVENT) {
            subList = getAllEvents(events);
        } else if (config.getType() == Type.ACTIVE) {
            subList = getActiveEvents(events);
        } else if (config.getType() == Type.UPCOMING) {
            subList = getUpcomingEvents(events);
        }
        if (config.getEventNr() > subList.size()) {
            logger.debug("no event found for {}, setting to UNDEF", itemName);
            eventPublisher.postUpdate(itemName, org.openhab.core.types.UnDefType.UNDEF);
            return;
        }
        logger.debug("found {} events for config: {}", subList.size(), config);
        CalDavEvent event = subList.get(config.getEventNr() - 1);
        logger.trace("found event {} for config {}", event.getShortName(), config);
        State command = null;
        switch(config.getValue()) {
            case NAME:
                command = new StringType(event.getName());
                break;
            case DESCRIPTION:
                command = new StringType(event.getContent());
                break;
            case PLACE:
                command = new StringType(event.getLocation());
                break;
            case START:
                command = new DateTimeType(FORMATTER.print(event.getStart()));
                break;
            case END:
                command = new DateTimeType(FORMATTER.print(event.getEnd()));
                break;
            case TIME:
                String startEnd = DF.print(event.getStart()) + " - " + DF.print(event.getEnd());
                command = new StringType(startEnd);
                break;
            case NAMEANDTIME:
                String startEnd2 = DF.print(event.getStart()) + " - " + DF.print(event.getEnd());
                String name = event.getName();
                command = new StringType(name + " @ " + startEnd2);
        }
        logger.debug("sending command {} for item {}", command, itemName);
        eventPublisher.postUpdate(itemName, command);
        logger.trace("command {} successfully sent", command);
    }
}
Also used : DateTimeType(org.openhab.core.library.types.DateTimeType) StringType(org.openhab.core.library.types.StringType) CalDavEvent(org.openhab.io.caldav.CalDavEvent) State(org.openhab.core.types.State) ArrayList(java.util.ArrayList)

Example 9 with CalDavEvent

use of org.openhab.io.caldav.CalDavEvent in project openhab1-addons by openhab.

the class CalDavBinding method doActionInitial.

private void doActionInitial() {
    List<CalDavEvent> events = calDavLoader.getEvents(new CalDavQuery(this.readCalendars, DateTime.now(), Sort.ASCENDING));
    Map<String, EventUtils.EventContent> map = new HashMap<String, EventUtils.EventContent>();
    for (CalDavEvent calDavEvent : events) {
        final List<EventUtils.EventContent> parseContent = EventUtils.parseContent(calDavEvent, this.itemRegistry, null);
        for (EventUtils.EventContent eventContent : parseContent) {
            if (disabledItems.contains(eventContent.getItem().getName())) {
                // changing this is item is disabled, do not change it
                continue;
            }
            EventUtils.EventContent currentEventContent = map.get(eventContent.getItem().getName());
            if (eventContent.getTime().isBefore(DateTime.now()) && (currentEventContent == null || eventContent.getTime().isAfter(currentEventContent.getTime()))) {
                map.put(eventContent.getItem().getName(), eventContent);
            }
        }
    }
    for (EventUtils.EventContent currentEventContent : map.values()) {
        eventPublisher.sendCommand(currentEventContent.getItem().getName(), currentEventContent.getCommand());
        logger.debug("setting initial value for {} to {}", currentEventContent.getItem().getName(), currentEventContent.getCommand());
    }
}
Also used : HashMap(java.util.HashMap) CalDavEvent(org.openhab.io.caldav.CalDavEvent) EventUtils(org.openhab.io.caldav.EventUtils) CalDavQuery(org.openhab.io.caldav.CalDavQuery)

Example 10 with CalDavEvent

use of org.openhab.io.caldav.CalDavEvent in project openhab1-addons by openhab.

the class EventReloaderJob method loadEvents.

public void loadEvents(String filename, org.joda.time.DateTime lastResourceChangeFS, final InputStream inputStream, final CalDavConfig config, final List<String> oldEventIds, boolean readFromFile) throws IOException, ParserException {
    CalendarBuilder builder = new CalendarBuilder();
    InputStreamReader is = new InputStreamReader(inputStream, config.getCharset());
    BufferedReader in = new BufferedReader(is, 50);
    final UnfoldingReader uin = new UnfoldingReader(in, 50, true);
    Calendar calendar = builder.build(uin);
    uin.close();
    // log.trace("calendar: {}", calendar);
    EventContainer eventContainer = new EventContainer(config.getKey());
    eventContainer.setFilename(filename);
    eventContainer.setLastChanged(lastResourceChangeFS);
    org.joda.time.DateTime loadFrom = org.joda.time.DateTime.now().minusMinutes(config.getHistoricLoadMinutes());
    org.joda.time.DateTime loadTo = org.joda.time.DateTime.now().plusMinutes(config.getPreloadMinutes());
    final ComponentList<CalendarComponent> vEventComponents = calendar.getComponents(Component.VEVENT);
    if (vEventComponents.size() == 0) {
        log.debug("could not find a VEVENT from calendar build, based on file {}", filename);
        // no events inside
        if (!readFromFile) {
            Util.storeToDisk(config.getKey(), filename, calendar);
        }
        return;
    }
    org.joda.time.DateTime lastModifedVEventOverAll = null;
    for (CalendarComponent comp : vEventComponents) {
        VEvent vEvent = (VEvent) comp;
        log.trace("loading event: " + vEvent.getUid().getValue() + ":" + vEvent.getSummary().getValue());
        // fallback, because 'LastModified' in VEvent is optional
        org.joda.time.DateTime lastModifedVEvent = lastResourceChangeFS;
        if (vEvent.getLastModified() != null) {
            lastModifedVEvent = new org.joda.time.DateTime(vEvent.getLastModified().getDateTime());
            log.trace("overriding lastmodified from file FS ({}) with event's last-modified property ({})", lastResourceChangeFS, lastModifedVEvent);
        }
        if (!config.isLastModifiedFileTimeStampValid()) {
            if (lastModifedVEventOverAll == null || lastModifedVEvent.isAfter(lastModifedVEventOverAll)) {
                lastModifedVEventOverAll = lastModifedVEvent;
            }
            if (eventContainer != null && !lastModifedVEvent.isBefore(eventContainer.getLastChanged())) {
                // to be created
                if (eventContainer.getCalculatedUntil() != null && vEventComponents.size() == 1 && eventContainer.getCalculatedUntil().isAfter(org.joda.time.DateTime.now().plusMinutes(config.getReloadMinutes()))) {
                    // the event is calculated as long as the next reload
                    // interval can handle this
                    log.trace("skipping resource processing {}, not changed", filename);
                    continue;
                }
                if (eventContainer.isHistoricEvent()) {
                    // no more upcoming events, do nothing
                    log.trace("skipping resource processing {}, not changed", filename);
                    continue;
                }
            }
        }
        Period period = new Period(new DateTime(loadFrom.toDate()), new DateTime(loadTo.toDate()));
        PeriodList periods = vEvent.calculateRecurrenceSet(period);
        periods = periods.normalise();
        String eventId = vEvent.getUid().getValue();
        final String eventName = vEvent.getSummary().getValue();
        // no more upcoming events
        if (periods.size() > 0) {
            if (vEvent.getConsumedTime(new net.fortuna.ical4j.model.Date(), new net.fortuna.ical4j.model.Date(org.joda.time.DateTime.now().plusYears(10).getMillis())).size() == 0) {
                log.trace("event will never be occur (historic): {}", eventName);
                eventContainer.setHistoricEvent(true);
            }
        }
        // expecting this is for every vEvent inside a calendar equals
        eventContainer.setEventId(eventId);
        eventContainer.setCalculatedUntil(loadTo);
        for (Period p : periods) {
            org.joda.time.DateTime start = getDateTime("start", p.getStart(), p.getRangeStart());
            org.joda.time.DateTime end = getDateTime("end", p.getEnd(), p.getRangeEnd());
            CalDavEvent event = new CalDavEvent(eventName, vEvent.getUid().getValue(), config.getKey(), start, end);
            event.setLastChanged(lastModifedVEvent);
            if (vEvent.getLocation() != null) {
                event.setLocation(vEvent.getLocation().getValue());
            }
            if (vEvent.getDescription() != null) {
                event.setContent(vEvent.getDescription().getValue());
            }
            event.getCategoryList().addAll(readCategory(vEvent));
            event.setFilename(filename);
            log.trace("adding event: " + event.getShortName());
            eventContainer.getEventList().add(event);
        }
    }
    if (lastModifedVEventOverAll != null && !config.isLastModifiedFileTimeStampValid()) {
        eventContainer.setLastChanged(lastModifedVEventOverAll);
        log.debug("changing eventcontainer last modified to {}", lastModifedVEventOverAll);
    }
    // if (!eventContainer.getEventList().isEmpty()) {
    CalDavLoaderImpl.instance.addEventToMap(eventContainer, true);
    if (!readFromFile) {
        Util.storeToDisk(config.getKey(), filename, calendar);
    }
// }
}
Also used : VEvent(net.fortuna.ical4j.model.component.VEvent) InputStreamReader(java.io.InputStreamReader) CalendarBuilder(net.fortuna.ical4j.data.CalendarBuilder) EventContainer(org.openhab.io.caldav.internal.EventStorage.EventContainer) CalendarComponent(net.fortuna.ical4j.model.component.CalendarComponent) UnfoldingReader(net.fortuna.ical4j.data.UnfoldingReader) Calendar(net.fortuna.ical4j.model.Calendar) Period(net.fortuna.ical4j.model.Period) PeriodList(net.fortuna.ical4j.model.PeriodList) DateTime(net.fortuna.ical4j.model.DateTime) LocalDateTime(org.joda.time.LocalDateTime) CalDavEvent(org.openhab.io.caldav.CalDavEvent) BufferedReader(java.io.BufferedReader) CalendarRuntime(org.openhab.io.caldav.internal.EventStorage.CalendarRuntime)

Aggregations

CalDavEvent (org.openhab.io.caldav.CalDavEvent)14 ArrayList (java.util.ArrayList)6 CalendarRuntime (org.openhab.io.caldav.internal.EventStorage.CalendarRuntime)6 EventContainer (org.openhab.io.caldav.internal.EventStorage.EventContainer)6 CalDavQuery (org.openhab.io.caldav.CalDavQuery)5 EventNotifier (org.openhab.io.caldav.EventNotifier)4 IOException (java.io.IOException)3 State (org.openhab.core.types.State)3 EventUtils (org.openhab.io.caldav.EventUtils)3 JobExecutionException (org.quartz.JobExecutionException)3 SchedulerException (org.quartz.SchedulerException)3 SardineException (com.github.sardine.impl.SardineException)2 HashMap (java.util.HashMap)2 List (java.util.List)2 ParserException (net.fortuna.ical4j.data.ParserException)2 PeriodList (net.fortuna.ical4j.model.PeriodList)2 DateTime (org.joda.time.DateTime)2 CalDavBindingProvider (org.openhab.binding.caldav_command.CalDavBindingProvider)2 Item (org.openhab.core.items.Item)2 ItemNotFoundException (org.openhab.core.items.ItemNotFoundException)2