Search in sources :

Example 6 with QueryablePersistenceService

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

the class DefaultChartProvider method createChart.

@Override
public BufferedImage createChart(String service, String theme, Date startTime, Date endTime, int height, int width, String items, String groups, Integer dpiValue, Boolean legend) throws ItemNotFoundException, IllegalArgumentException {
    logger.debug("Rendering chart: service: '{}', theme: '{}', startTime: '{}', endTime: '{}', width: '{}', height: '{}', items: '{}', groups: '{}', dpi: '{}', legend: '{}'", service, theme, startTime, endTime, width, height, items, groups, dpiValue, legend);
    QueryablePersistenceService persistenceService;
    int seriesCounter = 0;
    // get theme
    ChartTheme chartTheme = getChartTheme(theme);
    // get DPI
    int dpi;
    if (dpiValue != null && dpiValue > 0) {
        dpi = dpiValue;
    } else {
        dpi = DPI_DEFAULT;
    }
    // Create Chart
    Chart chart = new ChartBuilder().width(width).height(height).build();
    // Define the time axis - the defaults are not very nice
    long period = (endTime.getTime() - startTime.getTime()) / 1000;
    String pattern = "HH:mm";
    if (period <= 600) {
        // 10 minutes
        pattern = "mm:ss";
    } else if (period <= 86400) {
        // 1 day
        pattern = "HH:mm";
    } else if (period <= 604800) {
        // 1 week
        pattern = "EEE d";
    } else {
        pattern = "d MMM";
    }
    chart.getStyleManager().setDatePattern(pattern);
    // axis
    chart.getStyleManager().setAxisTickLabelsFont(chartTheme.getAxisTickLabelsFont(dpi));
    chart.getStyleManager().setAxisTickLabelsColor(chartTheme.getAxisTickLabelsColor());
    chart.getStyleManager().setXAxisMin(startTime.getTime());
    chart.getStyleManager().setXAxisMax(endTime.getTime());
    int yAxisSpacing = Math.max(height / 10, chartTheme.getAxisTickLabelsFont(dpi).getSize());
    chart.getStyleManager().setYAxisTickMarkSpacingHint(yAxisSpacing);
    // chart
    chart.getStyleManager().setChartBackgroundColor(chartTheme.getChartBackgroundColor());
    chart.getStyleManager().setChartFontColor(chartTheme.getChartFontColor());
    chart.getStyleManager().setChartPadding(chartTheme.getChartPadding(dpi));
    chart.getStyleManager().setPlotBackgroundColor(chartTheme.getPlotBackgroundColor());
    float plotGridLinesDash = (float) chartTheme.getPlotGridLinesDash(dpi);
    float[] plotGridLinesDashArray = { plotGridLinesDash, plotGridLinesDash };
    chart.getStyleManager().setPlotGridLinesStroke(new BasicStroke((float) chartTheme.getPlotGridLinesWidth(dpi), 0, 2, 10, plotGridLinesDashArray, 0));
    chart.getStyleManager().setPlotGridLinesColor(chartTheme.getPlotGridLinesColor());
    // legend
    chart.getStyleManager().setLegendBackgroundColor(chartTheme.getLegendBackgroundColor());
    chart.getStyleManager().setLegendFont(chartTheme.getLegendFont(dpi));
    chart.getStyleManager().setLegendSeriesLineLength(chartTheme.getLegendSeriesLineLength(dpi));
    // If a persistence service is specified, find the provider
    persistenceService = null;
    if (service != null) {
        persistenceService = getPersistenceServices().get(service);
    } else {
        // Otherwise, just get the first service, if one exists
        Iterator<Entry<String, QueryablePersistenceService>> it = getPersistenceServices().entrySet().iterator();
        if (it.hasNext()) {
            persistenceService = it.next().getValue();
        } else {
            throw new IllegalArgumentException("No Persistence service found.");
        }
    }
    // Did we find a service?
    if (persistenceService == null) {
        throw new IllegalArgumentException("Persistence service not found '" + service + "'.");
    }
    // Loop through all the items
    if (items != null) {
        String[] itemNames = items.split(",");
        for (String itemName : itemNames) {
            Item item = itemUIRegistry.getItem(itemName);
            if (addItem(chart, persistenceService, startTime, endTime, item, seriesCounter, chartTheme, dpi)) {
                seriesCounter++;
            }
        }
    }
    // Loop through all the groups and add each item from each group
    if (groups != null) {
        String[] groupNames = groups.split(",");
        for (String groupName : groupNames) {
            Item item = itemUIRegistry.getItem(groupName);
            if (item instanceof GroupItem) {
                GroupItem groupItem = (GroupItem) item;
                for (Item member : groupItem.getMembers()) {
                    if (addItem(chart, persistenceService, startTime, endTime, member, seriesCounter, chartTheme, dpi)) {
                        seriesCounter++;
                    }
                }
            } else {
                throw new ItemNotFoundException("Item '" + item.getName() + "' defined in groups is not a group.");
            }
        }
    }
    Boolean showLegend = null;
    // If there are no series, render a blank chart
    if (seriesCounter == 0) {
        // always hide the legend
        showLegend = false;
        List<Date> xData = new ArrayList<Date>();
        List<Number> yData = new ArrayList<Number>();
        xData.add(startTime);
        yData.add(0);
        xData.add(endTime);
        yData.add(0);
        Series series = chart.addSeries("NONE", xData, yData);
        series.setMarker(SeriesMarker.NONE);
        series.setLineStyle(new BasicStroke(0f));
    }
    // if the legend is not already hidden, check if legend parameter is supplied, or calculate a sensible value
    if (showLegend == null) {
        if (legend == null) {
            // more than one series, show the legend. otherwise hide it.
            showLegend = seriesCounter > 1;
        } else {
            // take value from supplied legend parameter
            showLegend = legend;
        }
    }
    // This won't be perfect, but it's a good compromise
    if (showLegend) {
        if (legendPosition < 0) {
            chart.getStyleManager().setLegendPosition(LegendPosition.InsideNW);
        } else {
            chart.getStyleManager().setLegendPosition(LegendPosition.InsideSW);
        }
    } else {
        // hide the whole legend
        chart.getStyleManager().setLegendVisible(false);
    }
    // Write the chart as a PNG image
    BufferedImage lBufferedImage = new BufferedImage(chart.getWidth(), chart.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D lGraphics2D = lBufferedImage.createGraphics();
    chart.paint(lGraphics2D);
    return lBufferedImage;
}
Also used : BasicStroke(java.awt.BasicStroke) ChartBuilder(org.knowm.xchart.ChartBuilder) ArrayList(java.util.ArrayList) BufferedImage(java.awt.image.BufferedImage) QueryablePersistenceService(org.eclipse.smarthome.core.persistence.QueryablePersistenceService) GroupItem(org.eclipse.smarthome.core.items.GroupItem) HistoricItem(org.eclipse.smarthome.core.persistence.HistoricItem) Item(org.eclipse.smarthome.core.items.Item) Entry(java.util.Map.Entry) GroupItem(org.eclipse.smarthome.core.items.GroupItem) Chart(org.knowm.xchart.Chart) Date(java.util.Date) Graphics2D(java.awt.Graphics2D) Series(org.knowm.xchart.Series) ItemNotFoundException(org.eclipse.smarthome.core.items.ItemNotFoundException)

Example 7 with QueryablePersistenceService

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

the class PersistenceExtensions method previousState.

/**
 * Returns the previous state of a given <code>item</code>.
 * The {@link PersistenceService} identified by the <code>serviceId</code> is used.
 *
 * @param item the item to get the previous state value for
 * @param skipEqual if <code>true</code>, skips equal state values and searches the first state not equal the
 *            current state
 * @param serviceId the name of the {@link PersistenceService} to use
 * @return the previous state or <code>null</code> if no previous state could be found, or if the given
 *         <code>serviceId</code> is not available or does not refer to a {@link QueryablePersistenceService}
 */
public static HistoricItem previousState(Item item, boolean skipEqual, String serviceId) {
    PersistenceService service = getService(serviceId);
    if (service instanceof QueryablePersistenceService) {
        QueryablePersistenceService qService = (QueryablePersistenceService) service;
        FilterCriteria filter = new FilterCriteria();
        filter.setItemName(item.getName());
        filter.setOrdering(Ordering.DESCENDING);
        filter.setPageSize(skipEqual ? 1000 : 1);
        int startPage = 0;
        filter.setPageNumber(startPage);
        Iterable<HistoricItem> items = qService.query(filter);
        while (items != null) {
            Iterator<HistoricItem> itemIterator = items.iterator();
            int itemCount = 0;
            while (itemIterator.hasNext()) {
                HistoricItem historicItem = itemIterator.next();
                itemCount++;
                if (!skipEqual || (skipEqual && !historicItem.getState().equals(item.getState()))) {
                    return historicItem;
                }
            }
            if (itemCount == filter.getPageSize()) {
                filter.setPageNumber(++startPage);
                items = qService.query(filter);
            } else {
                items = null;
            }
        }
        return null;
    } else {
        LoggerFactory.getLogger(PersistenceExtensions.class).warn("There is no queryable persistence service registered with the id '{}'", serviceId);
        return null;
    }
}
Also used : QueryablePersistenceService(org.eclipse.smarthome.core.persistence.QueryablePersistenceService) PersistenceService(org.eclipse.smarthome.core.persistence.PersistenceService) QueryablePersistenceService(org.eclipse.smarthome.core.persistence.QueryablePersistenceService) FilterCriteria(org.eclipse.smarthome.core.persistence.FilterCriteria) HistoricItem(org.eclipse.smarthome.core.persistence.HistoricItem)

Example 8 with QueryablePersistenceService

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

the class PersistenceExtensions method getAllStatesSince.

private static Iterable<HistoricItem> getAllStatesSince(Item item, AbstractInstant timestamp, String serviceId) {
    PersistenceService service = getService(serviceId);
    if (service instanceof QueryablePersistenceService) {
        QueryablePersistenceService qService = (QueryablePersistenceService) service;
        FilterCriteria filter = new FilterCriteria();
        filter.setBeginDate(ZonedDateTime.ofInstant(timestamp.toDate().toInstant(), timeZoneProvider.getTimeZone()));
        filter.setItemName(item.getName());
        filter.setOrdering(Ordering.ASCENDING);
        return qService.query(filter);
    } else {
        LoggerFactory.getLogger(PersistenceExtensions.class).warn("There is no queryable persistence service registered with the id '{}'", serviceId);
        return Collections.emptySet();
    }
}
Also used : QueryablePersistenceService(org.eclipse.smarthome.core.persistence.QueryablePersistenceService) PersistenceService(org.eclipse.smarthome.core.persistence.PersistenceService) QueryablePersistenceService(org.eclipse.smarthome.core.persistence.QueryablePersistenceService) FilterCriteria(org.eclipse.smarthome.core.persistence.FilterCriteria)

Example 9 with QueryablePersistenceService

use of org.eclipse.smarthome.core.persistence.QueryablePersistenceService 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

QueryablePersistenceService (org.eclipse.smarthome.core.persistence.QueryablePersistenceService)9 PersistenceService (org.eclipse.smarthome.core.persistence.PersistenceService)8 FilterCriteria (org.eclipse.smarthome.core.persistence.FilterCriteria)6 HistoricItem (org.eclipse.smarthome.core.persistence.HistoricItem)6 ModifiablePersistenceService (org.eclipse.smarthome.core.persistence.ModifiablePersistenceService)3 ZonedDateTime (java.time.ZonedDateTime)2 ArrayList (java.util.ArrayList)2 BasicStroke (java.awt.BasicStroke)1 Graphics2D (java.awt.Graphics2D)1 BufferedImage (java.awt.image.BufferedImage)1 Date (java.util.Date)1 Entry (java.util.Map.Entry)1 GenericItem (org.eclipse.smarthome.core.items.GenericItem)1 GroupItem (org.eclipse.smarthome.core.items.GroupItem)1 Item (org.eclipse.smarthome.core.items.Item)1 ItemNotFoundException (org.eclipse.smarthome.core.items.ItemNotFoundException)1 OnOffType (org.eclipse.smarthome.core.library.types.OnOffType)1 OpenClosedType (org.eclipse.smarthome.core.library.types.OpenClosedType)1 PersistenceServiceConfiguration (org.eclipse.smarthome.core.persistence.PersistenceServiceConfiguration)1 SimpleItemConfiguration (org.eclipse.smarthome.core.persistence.SimpleItemConfiguration)1