Search in sources :

Example 1 with ConsolFun

use of org.rrd4j.ConsolFun in project openhab1-addons by openhab.

the class RRD4jService method store.

/**
     * @{inheritDoc}
     */
@Override
public synchronized void store(final Item item, final String alias) {
    final String name = alias == null ? item.getName() : alias;
    RrdDb db = getDB(name);
    if (db != null) {
        ConsolFun function = getConsolidationFunction(db);
        long now = System.currentTimeMillis() / 1000;
        if (function != ConsolFun.AVERAGE) {
            try {
                // happens right at this spot
                if (now - 1 > db.getLastUpdateTime()) {
                    // only do it if there is not already a value
                    double lastValue = db.getLastDatasourceValue(DATASOURCE_STATE);
                    if (!Double.isNaN(lastValue)) {
                        Sample sample = db.createSample();
                        sample.setTime(now - 1);
                        sample.setValue(DATASOURCE_STATE, lastValue);
                        sample.update();
                        logger.debug("Stored '{}' with state '{}' in rrd4j database (again)", name, mapToState(lastValue, item.getName()));
                    }
                }
            } catch (IOException e) {
                logger.debug("Error storing last value (again): {}", e.getMessage());
            }
        }
        try {
            Sample sample = db.createSample();
            sample.setTime(now);
            DecimalType state = (DecimalType) item.getStateAs(DecimalType.class);
            if (state != null) {
                double value = state.toBigDecimal().doubleValue();
                if (db.getDatasource(DATASOURCE_STATE).getType() == DsType.COUNTER) {
                    // counter
                    // values
                    // must
                    // be
                    // adjusted
                    // by
                    // stepsize
                    value = value * db.getRrdDef().getStep();
                }
                sample.setValue(DATASOURCE_STATE, value);
                sample.update();
                logger.debug("Stored '{}' with state '{}' in rrd4j database", name, state);
            }
        } catch (IllegalArgumentException e) {
            if (e.getMessage().contains("at least one second step is required")) {
                // we try to store the value one second later
                Runnable task = new Runnable() {

                    @Override
                    public void run() {
                        store(item, name);
                    }
                };
                ScheduledFuture<?> job = scheduledJobs.get(name);
                if (job != null) {
                    job.cancel(true);
                    scheduledJobs.remove(name);
                }
                job = scheduler.schedule(task, 1, TimeUnit.SECONDS);
                scheduledJobs.put(name, job);
            } else {
                logger.warn("Could not persist '{}' to rrd4j database: {}", name, e.getMessage());
            }
        } catch (Exception e) {
            logger.warn("Could not persist '{}' to rrd4j database: {}", name, e.getMessage());
        }
        try {
            db.close();
        } catch (IOException e) {
            logger.debug("Error closing rrd4j database: {}", e.getMessage());
        }
    }
}
Also used : Sample(org.rrd4j.core.Sample) IOException(java.io.IOException) ScheduledFuture(java.util.concurrent.ScheduledFuture) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) ItemNotFoundException(org.openhab.core.items.ItemNotFoundException) IOException(java.io.IOException) ConsolFun(org.rrd4j.ConsolFun) DecimalType(org.openhab.core.library.types.DecimalType) RrdDb(org.rrd4j.core.RrdDb)

Example 2 with ConsolFun

use of org.rrd4j.ConsolFun in project openhab1-addons by openhab.

the class RRD4jChartServlet method addLine.

/**
     * Adds a line for the item to the graph definition.
     * The color of the line is determined by the counter, it simply picks the according index from LINECOLORS (and
     * rolls over if necessary).
     * 
     * @param graphDef the graph definition to fill
     * @param item the item to add a line for
     * @param counter defines the number of the datasource and is used to determine the line color
     */
protected void addLine(RrdGraphDef graphDef, Item item, int counter) {
    Color color = LINECOLORS[counter % LINECOLORS.length];
    String label = itemUIRegistry.getLabel(item.getName());
    String rrdName = RRD4jService.DB_FOLDER + File.separator + item.getName() + ".rrd";
    ConsolFun consolFun;
    if (label != null && label.contains("[") && label.contains("]")) {
        label = label.substring(0, label.indexOf('['));
    }
    try {
        RrdDb db = new RrdDb(rrdName);
        consolFun = db.getRrdDef().getArcDefs()[0].getConsolFun();
        db.close();
    } catch (IOException e) {
        consolFun = ConsolFun.MAX;
    }
    if (item instanceof NumberItem) {
        // we only draw a line
        // RRD4jService.getConsolidationFunction(item));
        graphDef.datasource(Integer.toString(counter), rrdName, "state", consolFun);
        graphDef.line(Integer.toString(counter), color, label, 2);
    } else {
        // we draw a line and fill the area beneath it with a transparent color
        // RRD4jService.getConsolidationFunction(item));
        graphDef.datasource(Integer.toString(counter), rrdName, "state", consolFun);
        Color areaColor = AREACOLORS[counter % LINECOLORS.length];
        graphDef.area(Integer.toString(counter), areaColor);
        graphDef.line(Integer.toString(counter), color, label, 2);
    }
}
Also used : NumberItem(org.openhab.core.library.items.NumberItem) ConsolFun(org.rrd4j.ConsolFun) Color(java.awt.Color) RrdDb(org.rrd4j.core.RrdDb) IOException(java.io.IOException)

Example 3 with ConsolFun

use of org.rrd4j.ConsolFun in project openhab1-addons by openhab.

the class RRD4jService method query.

@Override
public Iterable<HistoricItem> query(FilterCriteria filter) {
    String itemName = filter.getItemName();
    RrdDb db = getDB(itemName);
    if (db != null) {
        ConsolFun consolidationFunction = getConsolidationFunction(db);
        long start = 0L;
        long end = filter.getEndDate() == null ? System.currentTimeMillis() / 1000 : filter.getEndDate().getTime() / 1000;
        try {
            if (filter.getBeginDate() == null) {
                // want to support
                if (filter.getOrdering() == Ordering.DESCENDING && filter.getPageSize() == 1 && filter.getPageNumber() == 0) {
                    if (filter.getEndDate() == null) {
                        // we are asked only for the most recent value!
                        double lastValue = db.getLastDatasourceValue(DATASOURCE_STATE);
                        if (!Double.isNaN(lastValue)) {
                            HistoricItem rrd4jItem = new RRD4jItem(itemName, mapToState(lastValue, itemName), new Date(db.getLastArchiveUpdateTime() * 1000));
                            return Collections.singletonList(rrd4jItem);
                        } else {
                            return Collections.emptyList();
                        }
                    } else {
                        start = end;
                    }
                } else {
                    throw new UnsupportedOperationException("rrd4j does not allow querys without a begin date, " + "unless order is descending and a single value is requested");
                }
            } else {
                start = filter.getBeginDate().getTime() / 1000;
            }
            FetchRequest request = db.createFetchRequest(consolidationFunction, start, end, 1);
            List<HistoricItem> items = new ArrayList<HistoricItem>();
            FetchData result = request.fetchData();
            long ts = result.getFirstTimestamp();
            long step = result.getRowCount() > 1 ? result.getStep() : 0;
            for (double value : result.getValues(DATASOURCE_STATE)) {
                if (!Double.isNaN(value) && (((ts >= start) && (ts <= end)) || (start == end))) {
                    RRD4jItem rrd4jItem = new RRD4jItem(itemName, mapToState(value, itemName), new Date(ts * 1000));
                    items.add(rrd4jItem);
                }
                ts += step;
            }
            return items;
        } catch (IOException e) {
            logger.warn("Could not query rrd4j database for item '{}': {}", itemName, e.getMessage());
        }
    }
    return Collections.emptyList();
}
Also used : ArrayList(java.util.ArrayList) IOException(java.io.IOException) FetchData(org.rrd4j.core.FetchData) Date(java.util.Date) ConsolFun(org.rrd4j.ConsolFun) FetchRequest(org.rrd4j.core.FetchRequest) RrdDb(org.rrd4j.core.RrdDb) HistoricItem(org.openhab.core.persistence.HistoricItem)

Aggregations

IOException (java.io.IOException)3 ConsolFun (org.rrd4j.ConsolFun)3 RrdDb (org.rrd4j.core.RrdDb)3 Color (java.awt.Color)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)1 ScheduledFuture (java.util.concurrent.ScheduledFuture)1 ItemNotFoundException (org.openhab.core.items.ItemNotFoundException)1 NumberItem (org.openhab.core.library.items.NumberItem)1 DecimalType (org.openhab.core.library.types.DecimalType)1 HistoricItem (org.openhab.core.persistence.HistoricItem)1 FetchData (org.rrd4j.core.FetchData)1 FetchRequest (org.rrd4j.core.FetchRequest)1 Sample (org.rrd4j.core.Sample)1