Search in sources :

Example 26 with ItemNotFoundException

use of org.eclipse.smarthome.core.items.ItemNotFoundException 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 27 with ItemNotFoundException

use of org.eclipse.smarthome.core.items.ItemNotFoundException in project smarthome by eclipse.

the class AutoUpdateBinding method postUpdate.

private void postUpdate(String itemName, State newState) {
    if (itemRegistry != null) {
        try {
            GenericItem item = (GenericItem) itemRegistry.getItem(itemName);
            boolean isAccepted = false;
            if (item.getAcceptedDataTypes().contains(newState.getClass())) {
                isAccepted = true;
            } else {
                // Look for class hierarchy
                for (Class<? extends State> state : item.getAcceptedDataTypes()) {
                    try {
                        if (!state.isEnum() && state.newInstance().getClass().isAssignableFrom(newState.getClass())) {
                            isAccepted = true;
                            break;
                        }
                    } catch (InstantiationException e) {
                        // Should never happen
                        logger.warn("InstantiationException on {}", e.getMessage(), e);
                    } catch (IllegalAccessException e) {
                        // Should never happen
                        logger.warn("IllegalAccessException on {}", e.getMessage(), e);
                    }
                }
            }
            if (isAccepted) {
                eventPublisher.post(ItemEventFactory.createStateEvent(itemName, newState, "org.eclipse.smarthome.core.autoupdate"));
            } else {
                logger.debug("Received update of a not accepted type ({}) for item {}", newState.getClass().getSimpleName(), itemName);
            }
        } catch (ItemNotFoundException e) {
            logger.debug("Received update for non-existing item: {}", e.getMessage());
        }
    }
}
Also used : GenericItem(org.eclipse.smarthome.core.items.GenericItem) ItemNotFoundException(org.eclipse.smarthome.core.items.ItemNotFoundException)

Example 28 with ItemNotFoundException

use of org.eclipse.smarthome.core.items.ItemNotFoundException in project smarthome by eclipse.

the class RuleEngineImpl method receiveCommand.

private void receiveCommand(ItemCommandEvent commandEvent) {
    if (!starting && triggerManager != null && itemRegistry != null) {
        String itemName = commandEvent.getItemName();
        Command command = commandEvent.getItemCommand();
        try {
            Item item = itemRegistry.getItem(itemName);
            Iterable<Rule> rules = triggerManager.getRules(COMMAND, item, command);
            executeRules(rules, item, command);
        } catch (ItemNotFoundException e) {
        // ignore commands for non-existent items
        }
    }
}
Also used : GenericItem(org.eclipse.smarthome.core.items.GenericItem) Item(org.eclipse.smarthome.core.items.Item) Command(org.eclipse.smarthome.core.types.Command) Rule(org.eclipse.smarthome.model.rule.rules.Rule) ItemNotFoundException(org.eclipse.smarthome.core.items.ItemNotFoundException)

Example 29 with ItemNotFoundException

use of org.eclipse.smarthome.core.items.ItemNotFoundException in project smarthome by eclipse.

the class BusEvent method postUpdate.

/**
 * Posts a status update for a specified item to the event bus.
 *
 * @param itemName the name of the item to send the status update for
 * @param stateAsString the new state of the item
 */
public static Object postUpdate(String itemName, String stateString) {
    ItemRegistry registry = ScriptServiceUtil.getItemRegistry();
    EventPublisher publisher = ScriptServiceUtil.getEventPublisher();
    if (publisher != null && registry != null) {
        try {
            Item item = registry.getItem(itemName);
            State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString);
            if (state != null) {
                publisher.post(ItemEventFactory.createStateEvent(itemName, state));
            } else {
                LoggerFactory.getLogger(BusEvent.class).warn("Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item));
            }
        } catch (ItemNotFoundException e) {
            LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName);
        }
    }
    return null;
}
Also used : Item(org.eclipse.smarthome.core.items.Item) GroupItem(org.eclipse.smarthome.core.items.GroupItem) EventPublisher(org.eclipse.smarthome.core.events.EventPublisher) State(org.eclipse.smarthome.core.types.State) ItemRegistry(org.eclipse.smarthome.core.items.ItemRegistry) ItemNotFoundException(org.eclipse.smarthome.core.items.ItemNotFoundException)

Example 30 with ItemNotFoundException

use of org.eclipse.smarthome.core.items.ItemNotFoundException in project smarthome by eclipse.

the class SelectionRenderer method renderWidget.

@Override
public EList<Widget> renderWidget(Widget w, StringBuilder sb) throws RenderException {
    String snippet = getSnippet("selection");
    snippet = StringUtils.replace(snippet, "%category%", getCategory(w));
    snippet = StringUtils.replace(snippet, "%state%", getState(w));
    snippet = StringUtils.replace(snippet, "%format%", getFormat());
    State state = itemUIRegistry.getState(w);
    Selection selection = (Selection) w;
    String mappedValue = "";
    Item item = null;
    try {
        item = itemUIRegistry.getItem(w.getItem());
    } catch (ItemNotFoundException e) {
        logger.debug("Failed to retrieve item during widget rendering: {}", e.getMessage());
    }
    StringBuilder rowSB = new StringBuilder();
    for (Mapping mapping : selection.getMappings()) {
        String rowSnippet = getSnippet("selection_row");
        String command = mapping.getCmd() != null ? mapping.getCmd() : "";
        String label = mapping.getLabel();
        if (item instanceof NumberItem && ((NumberItem) item).getDimension() != null) {
            String unit = getUnitForWidget(w);
            command = StringUtils.replace(command, UnitUtils.UNIT_PLACEHOLDER, unit);
            label = StringUtils.replace(label, UnitUtils.UNIT_PLACEHOLDER, unit);
            // Special treatment for °C since uom library uses a single character: ℃
            // This will ensure the current state matches the cmd and the buttonClass is set accordingly.
            command = StringUtils.replace(command, "°C", "℃");
        }
        rowSnippet = StringUtils.replace(rowSnippet, "%item%", w.getItem() != null ? w.getItem() : "");
        rowSnippet = StringUtils.replace(rowSnippet, "%cmd%", StringEscapeUtils.escapeHtml(command));
        rowSnippet = StringUtils.replace(rowSnippet, "%label%", label != null ? StringEscapeUtils.escapeHtml(label) : "");
        State compareMappingState = state;
        if (state instanceof QuantityType) {
            // convert the item state to the command value for proper
            // comparison and "checked" attribute calculation
            compareMappingState = convertStateToLabelUnit((QuantityType<?>) state, command);
        }
        if (compareMappingState.toString().equals(command)) {
            rowSnippet = StringUtils.replace(rowSnippet, "%checked%", "checked=\"true\"");
            mappedValue = (label != null) ? label : command;
        } else {
            rowSnippet = StringUtils.replace(rowSnippet, "%checked%", "");
        }
        rowSB.append(rowSnippet);
    }
    snippet = StringUtils.replace(snippet, "%label_header%", getLabel(w, mappedValue));
    snippet = StringUtils.replace(snippet, "%rows%", rowSB.toString());
    // Process the color tags
    snippet = processColor(w, snippet);
    sb.append(snippet);
    return null;
}
Also used : NumberItem(org.eclipse.smarthome.core.library.items.NumberItem) NumberItem(org.eclipse.smarthome.core.library.items.NumberItem) Item(org.eclipse.smarthome.core.items.Item) QuantityType(org.eclipse.smarthome.core.library.types.QuantityType) State(org.eclipse.smarthome.core.types.State) Selection(org.eclipse.smarthome.model.sitemap.Selection) Mapping(org.eclipse.smarthome.model.sitemap.Mapping) ItemNotFoundException(org.eclipse.smarthome.core.items.ItemNotFoundException)

Aggregations

ItemNotFoundException (org.eclipse.smarthome.core.items.ItemNotFoundException)41 Item (org.eclipse.smarthome.core.items.Item)36 GroupItem (org.eclipse.smarthome.core.items.GroupItem)22 GenericItem (org.eclipse.smarthome.core.items.GenericItem)17 State (org.eclipse.smarthome.core.types.State)15 NumberItem (org.eclipse.smarthome.core.library.items.NumberItem)8 RollershutterItem (org.eclipse.smarthome.core.library.items.RollershutterItem)8 SwitchItem (org.eclipse.smarthome.core.library.items.SwitchItem)8 Command (org.eclipse.smarthome.core.types.Command)7 ItemNotUniqueException (org.eclipse.smarthome.core.items.ItemNotUniqueException)5 QuantityType (org.eclipse.smarthome.core.library.types.QuantityType)5 Mapping (org.eclipse.smarthome.model.sitemap.Mapping)5 Date (java.util.Date)4 CallItem (org.eclipse.smarthome.core.library.items.CallItem)4 DateTimeItem (org.eclipse.smarthome.core.library.items.DateTimeItem)4 StringItem (org.eclipse.smarthome.core.library.items.StringItem)4 Widget (org.eclipse.smarthome.model.sitemap.Widget)4 ColorItem (org.eclipse.smarthome.core.library.items.ColorItem)3 ContactItem (org.eclipse.smarthome.core.library.items.ContactItem)3 DimmerItem (org.eclipse.smarthome.core.library.items.DimmerItem)3