Search in sources :

Example 16 with HistoricItem

use of org.eclipse.smarthome.core.persistence.HistoricItem in project smarthome by eclipse.

the class PersistenceExtensions method deltaSince.

/**
 * Gets the difference value of the state of a given <code>item</code> since a certain point in time.
 * The {@link PersistenceService} identified by the <code>serviceId</code> is used.
 *
 * @param item the item to get the average state value for
 * @param timestamp the point in time from which to compute the delta
 * @param serviceId the name of the {@link PersistenceService} to use
 * @return the difference between now and then, or <code>null</code> if the given serviceId does not refer to an
 *         available {@link QueryablePersistenceService}, or if there is no persisted state for the given
 *         <code>item</code> at the given <code>timestamp</code> using the persistence service named
 *         <code>serviceId</code>
 */
public static DecimalType deltaSince(Item item, AbstractInstant timestamp, String serviceId) {
    HistoricItem itemThen = historicState(item, timestamp, serviceId);
    if (itemThen != null) {
        DecimalType valueThen = (DecimalType) itemThen.getState();
        DecimalType valueNow = (DecimalType) item.getStateAs(DecimalType.class);
        if ((valueThen != null) && (valueNow != null)) {
            return new DecimalType(valueNow.toBigDecimal().subtract(valueThen.toBigDecimal()));
        }
    }
    return null;
}
Also used : DecimalType(org.eclipse.smarthome.core.library.types.DecimalType) HistoricItem(org.eclipse.smarthome.core.persistence.HistoricItem)

Example 17 with HistoricItem

use of org.eclipse.smarthome.core.persistence.HistoricItem in project smarthome by eclipse.

the class PersistenceExtensions method sumSince.

/**
 * Gets the sum of the state of a given <code>item</code> since a certain point in time.
 * The {@link PersistenceService} identified by the <code>serviceId</code> is used.
 *
 * @param item the item for which we will sum its persisted state values since <code>timestamp</code>
 * @param timestamp the point in time from which to start the summation
 * @param serviceId the name of the {@link PersistenceService} to use
 * @return the sum of the state values since the given point in time, or {@link DecimalType.ZERO} if no historic
 *         states could be found for the <code>item</code> or if <code>serviceId</code> does no refer to a
 *         {@link QueryablePersistenceService}
 */
public static DecimalType sumSince(Item item, AbstractInstant timestamp, String serviceId) {
    Iterable<HistoricItem> result = getAllStatesSince(item, timestamp, serviceId);
    Iterator<HistoricItem> it = result.iterator();
    BigDecimal sum = BigDecimal.ZERO;
    while (it.hasNext()) {
        State state = it.next().getState();
        if (state instanceof DecimalType) {
            sum = sum.add(((DecimalType) state).toBigDecimal());
        }
    }
    return new DecimalType(sum);
}
Also used : State(org.eclipse.smarthome.core.types.State) DecimalType(org.eclipse.smarthome.core.library.types.DecimalType) HistoricItem(org.eclipse.smarthome.core.persistence.HistoricItem) BigDecimal(java.math.BigDecimal)

Example 18 with HistoricItem

use of org.eclipse.smarthome.core.persistence.HistoricItem in project smarthome by eclipse.

the class PersistenceExtensions method maximumSince.

/**
 * Gets the historic item with the maximum value of the state of a given <code>item</code> since
 * a certain point in time. The {@link PersistenceService} identified by the <code>serviceId</code> is used.
 *
 * @param item the item to get the maximum state value for
 * @param timestamp the point in time to start the check
 * @param serviceId the name of the {@link PersistenceService} to use
 * @return a {@link HistoricItem} with the maximum state value since the given point in time, or a
 *         {@link HistoricItem} constructed from the <code>item</code>'s state if <code>item</code>'s state is the
 *         maximum value or if the given <code>serviceId</code> does not refer to an available
 *         {@link QueryablePersistenceService}
 */
public static HistoricItem maximumSince(final Item item, AbstractInstant timestamp, String serviceId) {
    Iterable<HistoricItem> result = getAllStatesSince(item, timestamp, serviceId);
    Iterator<HistoricItem> it = result.iterator();
    HistoricItem maximumHistoricItem = null;
    DecimalType maximum = (DecimalType) item.getStateAs(DecimalType.class);
    while (it.hasNext()) {
        HistoricItem historicItem = it.next();
        State state = historicItem.getState();
        if (state instanceof DecimalType) {
            DecimalType value = (DecimalType) state;
            if (maximum == null || value.compareTo(maximum) > 0) {
                maximum = value;
                maximumHistoricItem = historicItem;
            }
        }
    }
    if (maximumHistoricItem == null && maximum != null) {
        // the maximum state is the current one, so construct a historic item on the fly
        final DecimalType state = maximum;
        return new HistoricItem() {

            @Override
            public Date getTimestamp() {
                return Calendar.getInstance().getTime();
            }

            @Override
            public State getState() {
                return state;
            }

            @Override
            public String getName() {
                return item.getName();
            }
        };
    } else {
        return maximumHistoricItem;
    }
}
Also used : State(org.eclipse.smarthome.core.types.State) DecimalType(org.eclipse.smarthome.core.library.types.DecimalType) HistoricItem(org.eclipse.smarthome.core.persistence.HistoricItem)

Example 19 with HistoricItem

use of org.eclipse.smarthome.core.persistence.HistoricItem in project smarthome by eclipse.

the class PersistenceExtensions method averageSince.

/**
 * Gets the average value of the state of a given <code>item</code> since a certain point in time.
 * The {@link PersistenceService} identified by the <code>serviceId</code> is used.
 *
 * @param item the item to get the average state value for
 * @param timestamp the point in time from which to search for the average state value
 * @param serviceId the name of the {@link PersistenceService} to use
 * @return the average state values since <code>timestamp</code>, or the state of the given <code>item</code> if no
 *         previous states could be found or if the persistence service given by <code>serviceId</code> does not
 *         refer to an available {@link QueryablePersistenceService}
 */
public static DecimalType averageSince(Item item, AbstractInstant timestamp, String serviceId) {
    Iterable<HistoricItem> result = getAllStatesSince(item, timestamp, serviceId);
    Iterator<HistoricItem> it = result.iterator();
    BigDecimal total = BigDecimal.ZERO;
    BigDecimal avgValue, timeSpan;
    DecimalType lastState = null, thisState = null;
    BigDecimal lastTimestamp = null, thisTimestamp = null;
    BigDecimal firstTimestamp = null;
    while (it.hasNext()) {
        HistoricItem thisItem = it.next();
        State state = thisItem.getState();
        if (state instanceof DecimalType) {
            thisState = (DecimalType) state;
            thisTimestamp = BigDecimal.valueOf(thisItem.getTimestamp().getTime());
            if (firstTimestamp == null) {
                firstTimestamp = thisTimestamp;
            } else {
                avgValue = (thisState.toBigDecimal().add(lastState.toBigDecimal())).divide(BigDecimal.valueOf(2), MathContext.DECIMAL64);
                timeSpan = thisTimestamp.subtract(lastTimestamp);
                total = total.add(avgValue.multiply(timeSpan, MathContext.DECIMAL64));
            }
            lastTimestamp = thisTimestamp;
            lastState = thisState;
        }
    }
    if (lastState != null) {
        thisState = (DecimalType) item.getStateAs(DecimalType.class);
        thisTimestamp = BigDecimal.valueOf((new DateTime()).getMillis());
        avgValue = (thisState.toBigDecimal().add(lastState.toBigDecimal())).divide(BigDecimal.valueOf(2), MathContext.DECIMAL64);
        timeSpan = thisTimestamp.subtract(lastTimestamp);
        total = total.add(avgValue.multiply(timeSpan, MathContext.DECIMAL64));
    }
    if (thisTimestamp != null) {
        timeSpan = thisTimestamp.subtract(firstTimestamp, MathContext.DECIMAL64);
        BigDecimal average = total.divide(timeSpan, MathContext.DECIMAL64);
        return new DecimalType(average);
    } else {
        return null;
    }
}
Also used : State(org.eclipse.smarthome.core.types.State) DecimalType(org.eclipse.smarthome.core.library.types.DecimalType) HistoricItem(org.eclipse.smarthome.core.persistence.HistoricItem) BigDecimal(java.math.BigDecimal) ZonedDateTime(java.time.ZonedDateTime) DateTime(org.joda.time.DateTime)

Example 20 with HistoricItem

use of org.eclipse.smarthome.core.persistence.HistoricItem in project smarthome by eclipse.

the class PersistenceResource method getItemHistoryDTO.

private Response getItemHistoryDTO(String serviceId, String itemName, String timeBegin, String timeEnd, int pageNumber, int pageLength, boolean boundary) {
    // Benchmarking timer...
    long timerStart = System.currentTimeMillis();
    // If serviceId is null, then use the default service
    PersistenceService service = null;
    String effectiveServiceId = serviceId != null ? serviceId : persistenceServiceRegistry.getDefaultId();
    service = persistenceServiceRegistry.get(effectiveServiceId);
    if (service == null) {
        logger.debug("Persistence service not found '{}'.", effectiveServiceId);
        return JSONResponse.createErrorResponse(Status.BAD_REQUEST, "Persistence service not found: " + effectiveServiceId);
    }
    if (!(service instanceof QueryablePersistenceService)) {
        logger.debug("Persistence service not queryable '{}'.", effectiveServiceId);
        return JSONResponse.createErrorResponse(Status.BAD_REQUEST, "Persistence service not queryable: " + effectiveServiceId);
    }
    QueryablePersistenceService qService = (QueryablePersistenceService) service;
    ZonedDateTime dateTimeBegin = ZonedDateTime.now();
    ZonedDateTime dateTimeEnd = dateTimeBegin;
    if (timeBegin != null) {
        dateTimeBegin = convertTime(timeBegin);
    }
    if (timeEnd != null) {
        dateTimeEnd = convertTime(timeEnd);
    }
    // End now...
    if (dateTimeEnd.toEpochSecond() == 0) {
        dateTimeEnd = ZonedDateTime.of(LocalDateTime.now(), timeZoneProvider.getTimeZone());
    }
    if (dateTimeBegin.toEpochSecond() == 0) {
        // Default to 1 days data if the times are the same or the start time is newer
        // than the end time
        dateTimeBegin = ZonedDateTime.of(dateTimeEnd.toLocalDateTime().plusDays(-1), timeZoneProvider.getTimeZone());
    }
    // than the end time
    if (dateTimeBegin.isAfter(dateTimeEnd) || dateTimeBegin.isEqual(dateTimeEnd)) {
        dateTimeBegin = ZonedDateTime.of(dateTimeEnd.toLocalDateTime().plusDays(-1), timeZoneProvider.getTimeZone());
    }
    FilterCriteria filter;
    Iterable<HistoricItem> result;
    State state = null;
    Long quantity = 0l;
    ItemHistoryDTO dto = new ItemHistoryDTO();
    dto.name = itemName;
    filter = new FilterCriteria();
    filter.setItemName(itemName);
    // (or not at all if there's no change during the graph period)
    if (boundary) {
        // Get the value before the start time.
        filter.setEndDate(dateTimeBegin);
        filter.setPageSize(1);
        filter.setOrdering(Ordering.DESCENDING);
        result = qService.query(filter);
        if (result != null && result.iterator().hasNext()) {
            dto.addData(dateTimeBegin.toInstant().toEpochMilli(), result.iterator().next().getState());
            quantity++;
        }
    }
    if (pageLength == 0) {
        filter.setPageNumber(0);
        filter.setPageSize(Integer.MAX_VALUE);
    } else {
        filter.setPageNumber(pageNumber);
        filter.setPageSize(pageLength);
    }
    filter.setBeginDate(dateTimeBegin);
    filter.setEndDate(dateTimeEnd);
    filter.setOrdering(Ordering.ASCENDING);
    result = qService.query(filter);
    if (result != null) {
        Iterator<HistoricItem> it = result.iterator();
        // Iterate through the data
        while (it.hasNext()) {
            HistoricItem historicItem = it.next();
            state = historicItem.getState();
            // to avoid diagonal lines
            if (state instanceof OnOffType || state instanceof OpenClosedType) {
                dto.addData(historicItem.getTimestamp().getTime(), state);
            }
            dto.addData(historicItem.getTimestamp().getTime(), state);
            quantity++;
        }
    }
    if (boundary) {
        // Get the value after the end time.
        filter.setBeginDate(dateTimeEnd);
        filter.setPageSize(1);
        filter.setOrdering(Ordering.ASCENDING);
        result = qService.query(filter);
        if (result != null && result.iterator().hasNext()) {
            dto.addData(dateTimeEnd.toInstant().toEpochMilli(), result.iterator().next().getState());
            quantity++;
        }
    }
    dto.datapoints = Long.toString(quantity);
    logger.debug("Persistence returned {} rows in {}ms", dto.datapoints, System.currentTimeMillis() - timerStart);
    return JSONResponse.createResponse(Status.OK, dto, "");
}
Also used : FilterCriteria(org.eclipse.smarthome.core.persistence.FilterCriteria) PersistenceService(org.eclipse.smarthome.core.persistence.PersistenceService) QueryablePersistenceService(org.eclipse.smarthome.core.persistence.QueryablePersistenceService) ModifiablePersistenceService(org.eclipse.smarthome.core.persistence.ModifiablePersistenceService) QueryablePersistenceService(org.eclipse.smarthome.core.persistence.QueryablePersistenceService) ItemHistoryDTO(org.eclipse.smarthome.core.persistence.dto.ItemHistoryDTO) ZonedDateTime(java.time.ZonedDateTime) OnOffType(org.eclipse.smarthome.core.library.types.OnOffType) State(org.eclipse.smarthome.core.types.State) OpenClosedType(org.eclipse.smarthome.core.library.types.OpenClosedType) HistoricItem(org.eclipse.smarthome.core.persistence.HistoricItem)

Aggregations

HistoricItem (org.eclipse.smarthome.core.persistence.HistoricItem)20 DecimalType (org.eclipse.smarthome.core.library.types.DecimalType)11 State (org.eclipse.smarthome.core.types.State)9 FilterCriteria (org.eclipse.smarthome.core.persistence.FilterCriteria)6 PersistenceService (org.eclipse.smarthome.core.persistence.PersistenceService)5 QueryablePersistenceService (org.eclipse.smarthome.core.persistence.QueryablePersistenceService)5 Test (org.junit.Test)5 ZonedDateTime (java.time.ZonedDateTime)3 Date (java.util.Date)3 DateMidnight (org.joda.time.DateMidnight)3 BigDecimal (java.math.BigDecimal)2 ArrayList (java.util.ArrayList)2 OnOffType (org.eclipse.smarthome.core.library.types.OnOffType)2 OpenClosedType (org.eclipse.smarthome.core.library.types.OpenClosedType)2 DateTime (org.joda.time.DateTime)2 BasicStroke (java.awt.BasicStroke)1 Color (java.awt.Color)1 DateFormat (java.text.DateFormat)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Calendar (java.util.Calendar)1