Search in sources :

Example 71 with Item

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

the class ItemUIRegistryImpl method resolveDefault.

private Widget resolveDefault(Widget widget) {
    if (!(widget instanceof Default)) {
        return widget;
    } else {
        String itemName = widget.getItem();
        if (itemName != null) {
            Item item = itemRegistry.get(itemName);
            if (item != null) {
                Widget defaultWidget = getDefaultWidget(item.getClass(), item.getName());
                if (defaultWidget != null) {
                    copyProperties(widget, defaultWidget);
                    defaultWidgets.put(defaultWidget, widget);
                    return defaultWidget;
                }
            }
        }
        return null;
    }
}
Also used : NumberItem(org.eclipse.smarthome.core.library.items.NumberItem) CallItem(org.eclipse.smarthome.core.library.items.CallItem) SwitchItem(org.eclipse.smarthome.core.library.items.SwitchItem) DateTimeItem(org.eclipse.smarthome.core.library.items.DateTimeItem) RollershutterItem(org.eclipse.smarthome.core.library.items.RollershutterItem) GroupItem(org.eclipse.smarthome.core.items.GroupItem) ColorItem(org.eclipse.smarthome.core.library.items.ColorItem) LocationItem(org.eclipse.smarthome.core.library.items.LocationItem) ContactItem(org.eclipse.smarthome.core.library.items.ContactItem) GenericItem(org.eclipse.smarthome.core.items.GenericItem) Item(org.eclipse.smarthome.core.items.Item) StringItem(org.eclipse.smarthome.core.library.items.StringItem) PlayerItem(org.eclipse.smarthome.core.library.items.PlayerItem) ImageItem(org.eclipse.smarthome.core.library.items.ImageItem) DimmerItem(org.eclipse.smarthome.core.library.items.DimmerItem) Widget(org.eclipse.smarthome.model.sitemap.Widget) LinkableWidget(org.eclipse.smarthome.model.sitemap.LinkableWidget) Default(org.eclipse.smarthome.model.sitemap.Default)

Example 72 with Item

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

the class ItemUIRegistryImpl method getLabel.

@Override
public String getLabel(Widget w) {
    String label = getLabelFromWidget(w);
    String itemName = w.getItem();
    if (StringUtils.isBlank(itemName)) {
        return transform(label, null);
    }
    String labelMappedOption = null;
    State state = null;
    StateDescription stateDescription = null;
    String formatPattern = getFormatPattern(label);
    // (i.e. it contains at least a %)
    try {
        final Item item = getItem(itemName);
        // There is a known issue in the implementation of the method getStateDescription() of class Item
        // in the following case:
        // - the item provider returns as expected a state description without pattern but with for
        // example a min value because a min value is set in the item definition but no label with
        // pattern is set.
        // - the channel state description provider returns as expected a state description with a pattern
        // In this case, the result is no display of value by UIs because no pattern is set in the
        // returned StateDescription. What is expected is the display of a value using the pattern
        // provided by the channel state description provider.
        stateDescription = item.getStateDescription();
        if (formatPattern == null && stateDescription != null && stateDescription.getPattern() != null) {
            label = label + " [" + stateDescription.getPattern() + "]";
        }
        String updatedPattern = getFormatPattern(label);
        if (updatedPattern != null) {
            formatPattern = updatedPattern;
            // a number is requested, PercentType must not be converted to DecimalType:
            if (formatPattern.contains("%d") && !(item.getState() instanceof PercentType)) {
                state = item.getStateAs(DecimalType.class);
            } else {
                state = item.getState();
            }
        }
    } catch (ItemNotFoundException e) {
        logger.error("Cannot retrieve item for widget {}", w.eClass().getInstanceTypeName());
    }
    if (formatPattern != null) {
        if (formatPattern.isEmpty()) {
            label = label.substring(0, label.indexOf("[")).trim();
        } else {
            if (state == null || state instanceof UnDefType) {
                formatPattern = formatUndefined(formatPattern);
            } else if (state instanceof Type) {
                // if the channel contains options, we build a label with the mapped option value
                if (stateDescription != null && stateDescription.getOptions() != null) {
                    for (StateOption option : stateDescription.getOptions()) {
                        if (option.getValue().equals(state.toString()) && option.getLabel() != null) {
                            State stateOption = new StringType(option.getLabel());
                            try {
                                String formatPatternOption = stateOption.format(formatPattern);
                                labelMappedOption = label.trim();
                                labelMappedOption = labelMappedOption.substring(0, labelMappedOption.indexOf("[") + 1) + formatPatternOption + "]";
                            } catch (IllegalArgumentException e) {
                                logger.debug("Mapping option value '{}' for item {} using format '{}' failed ({}); mapping is ignored", stateOption, itemName, formatPattern, e.getMessage());
                                labelMappedOption = null;
                            }
                            break;
                        }
                    }
                }
                if (state instanceof QuantityType) {
                    QuantityType<?> quantityState = (QuantityType<?>) state;
                    // sanity convert current state to the item state description unit in case it was updated in the
                    // meantime. The item state is still in the "original" unit while the state description will
                    // display the new unit:
                    Unit<?> patternUnit = UnitUtils.parseUnit(formatPattern);
                    if (patternUnit != null && !quantityState.getUnit().equals(patternUnit)) {
                        quantityState = quantityState.toUnit(patternUnit);
                    }
                    // The widget may define its own unit in the widget label. Convert to this unit:
                    quantityState = convertStateToWidgetUnit(quantityState, w);
                    state = quantityState;
                }
                // This also handles IllegalFormatConversionException, which is a subclass of IllegalArgument.
                try {
                    formatPattern = fillFormatPattern(formatPattern, state);
                } catch (IllegalArgumentException e) {
                    logger.warn("Exception while formatting value '{}' of item {} with format '{}': {}", state, itemName, formatPattern, e.getMessage());
                    formatPattern = new String("Err");
                }
            }
            label = label.trim();
            label = label.substring(0, label.indexOf("[") + 1) + formatPattern + "]";
        }
    }
    return transform(label, labelMappedOption);
}
Also used : StringType(org.eclipse.smarthome.core.library.types.StringType) UnDefType(org.eclipse.smarthome.core.types.UnDefType) PercentType(org.eclipse.smarthome.core.library.types.PercentType) Unit(javax.measure.Unit) ChronoUnit(java.time.temporal.ChronoUnit) StateOption(org.eclipse.smarthome.core.types.StateOption) NumberItem(org.eclipse.smarthome.core.library.items.NumberItem) CallItem(org.eclipse.smarthome.core.library.items.CallItem) SwitchItem(org.eclipse.smarthome.core.library.items.SwitchItem) DateTimeItem(org.eclipse.smarthome.core.library.items.DateTimeItem) RollershutterItem(org.eclipse.smarthome.core.library.items.RollershutterItem) GroupItem(org.eclipse.smarthome.core.items.GroupItem) ColorItem(org.eclipse.smarthome.core.library.items.ColorItem) LocationItem(org.eclipse.smarthome.core.library.items.LocationItem) ContactItem(org.eclipse.smarthome.core.library.items.ContactItem) GenericItem(org.eclipse.smarthome.core.items.GenericItem) Item(org.eclipse.smarthome.core.items.Item) StringItem(org.eclipse.smarthome.core.library.items.StringItem) PlayerItem(org.eclipse.smarthome.core.library.items.PlayerItem) ImageItem(org.eclipse.smarthome.core.library.items.ImageItem) DimmerItem(org.eclipse.smarthome.core.library.items.DimmerItem) OnOffType(org.eclipse.smarthome.core.library.types.OnOffType) UnDefType(org.eclipse.smarthome.core.types.UnDefType) PlayPauseType(org.eclipse.smarthome.core.library.types.PlayPauseType) StringType(org.eclipse.smarthome.core.library.types.StringType) NextPreviousType(org.eclipse.smarthome.core.library.types.NextPreviousType) PercentType(org.eclipse.smarthome.core.library.types.PercentType) Type(org.eclipse.smarthome.core.types.Type) QuantityType(org.eclipse.smarthome.core.library.types.QuantityType) DateTimeType(org.eclipse.smarthome.core.library.types.DateTimeType) DecimalType(org.eclipse.smarthome.core.library.types.DecimalType) QuantityType(org.eclipse.smarthome.core.library.types.QuantityType) State(org.eclipse.smarthome.core.types.State) DecimalType(org.eclipse.smarthome.core.library.types.DecimalType) StateDescription(org.eclipse.smarthome.core.types.StateDescription) ItemNotFoundException(org.eclipse.smarthome.core.items.ItemNotFoundException)

Example 73 with Item

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

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

the class CommunicationManager method handleCallFromHandler.

void handleCallFromHandler(ChannelUID channelUID, @Nullable Thing thing, Consumer<Profile> action) {
    itemChannelLinkRegistry.stream().filter(link -> {
        // all links for the channel
        return link.getLinkedUID().equals(channelUID);
    }).forEach(link -> {
        Item item = getItem(link.getItemName());
        if (item != null) {
            Profile profile = getProfile(link, item, thing);
            action.accept(profile);
        }
    });
}
Also used : Channel(org.eclipse.smarthome.core.thing.Channel) Arrays(java.util.Arrays) ItemFactory(org.eclipse.smarthome.core.items.ItemFactory) ProfileFactory(org.eclipse.smarthome.core.thing.profiles.ProfileFactory) LoggerFactory(org.slf4j.LoggerFactory) Command(org.eclipse.smarthome.core.types.Command) ItemChannelLinkConfigDescriptionProvider(org.eclipse.smarthome.core.thing.internal.link.ItemChannelLinkConfigDescriptionProvider) ChannelUID(org.eclipse.smarthome.core.thing.ChannelUID) Nullable(org.eclipse.jdt.annotation.Nullable) Map(java.util.Map) Thing(org.eclipse.smarthome.core.thing.Thing) UID(org.eclipse.smarthome.core.thing.UID) State(org.eclipse.smarthome.core.types.State) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) EventPublisher(org.eclipse.smarthome.core.events.EventPublisher) ItemStateConverter(org.eclipse.smarthome.core.items.ItemStateConverter) ReferencePolicy(org.osgi.service.component.annotations.ReferencePolicy) CopyOnWriteArraySet(java.util.concurrent.CopyOnWriteArraySet) ThingEventFactory(org.eclipse.smarthome.core.thing.events.ThingEventFactory) List(java.util.List) StateProfile(org.eclipse.smarthome.core.thing.profiles.StateProfile) Entry(java.util.Map.Entry) NonNull(org.eclipse.jdt.annotation.NonNull) SystemProfileFactory(org.eclipse.smarthome.core.thing.internal.profiles.SystemProfileFactory) ThingUID(org.eclipse.smarthome.core.thing.ThingUID) ItemCommandEvent(org.eclipse.smarthome.core.items.events.ItemCommandEvent) EventFilter(org.eclipse.smarthome.core.events.EventFilter) EventSubscriber(org.eclipse.smarthome.core.events.EventSubscriber) Function(java.util.function.Function) RegistryChangeListener(org.eclipse.smarthome.core.common.registry.RegistryChangeListener) HashSet(java.util.HashSet) ProfileCallbackImpl(org.eclipse.smarthome.core.thing.internal.profiles.ProfileCallbackImpl) Component(org.osgi.service.component.annotations.Component) SafeCaller(org.eclipse.smarthome.core.common.SafeCaller) Type(org.eclipse.smarthome.core.types.Type) ProfileCallback(org.eclipse.smarthome.core.thing.profiles.ProfileCallback) TriggerProfile(org.eclipse.smarthome.core.thing.profiles.TriggerProfile) Logger(org.slf4j.Logger) Profile(org.eclipse.smarthome.core.thing.profiles.Profile) Item(org.eclipse.smarthome.core.items.Item) ItemStateEvent(org.eclipse.smarthome.core.items.events.ItemStateEvent) ItemChannelLink(org.eclipse.smarthome.core.thing.link.ItemChannelLink) ItemRegistry(org.eclipse.smarthome.core.items.ItemRegistry) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ThingRegistry(org.eclipse.smarthome.core.thing.ThingRegistry) ReferenceCardinality(org.osgi.service.component.annotations.ReferenceCardinality) ProfileAdvisor(org.eclipse.smarthome.core.thing.profiles.ProfileAdvisor) ChannelTriggeredEvent(org.eclipse.smarthome.core.thing.events.ChannelTriggeredEvent) ItemChannelLinkRegistry(org.eclipse.smarthome.core.thing.link.ItemChannelLinkRegistry) Event(org.eclipse.smarthome.core.events.Event) ProfileTypeUID(org.eclipse.smarthome.core.thing.profiles.ProfileTypeUID) Reference(org.osgi.service.component.annotations.Reference) Collections(java.util.Collections) Item(org.eclipse.smarthome.core.items.Item) StateProfile(org.eclipse.smarthome.core.thing.profiles.StateProfile) TriggerProfile(org.eclipse.smarthome.core.thing.profiles.TriggerProfile) Profile(org.eclipse.smarthome.core.thing.profiles.Profile)

Example 75 with Item

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

the class CommunicationManager method calculateAcceptedTypes.

private synchronized void calculateAcceptedTypes() {
    acceptedCommandTypeMap.clear();
    acceptedStateTypeMap.clear();
    for (ItemFactory itemFactory : itemFactories) {
        for (String itemTypeName : itemFactory.getSupportedItemTypes()) {
            Item item = itemFactory.createItem(itemTypeName, "tmp");
            if (item != null) {
                acceptedCommandTypeMap.put(itemTypeName, item.getAcceptedCommandTypes());
                acceptedStateTypeMap.put(itemTypeName, item.getAcceptedDataTypes());
            } else {
                logger.error("Item factory {} suggested it can create items of type {} but returned null", itemFactory, itemTypeName);
            }
        }
    }
}
Also used : Item(org.eclipse.smarthome.core.items.Item) ItemFactory(org.eclipse.smarthome.core.items.ItemFactory)

Aggregations

Item (org.eclipse.smarthome.core.items.Item)111 GroupItem (org.eclipse.smarthome.core.items.GroupItem)42 GenericItem (org.eclipse.smarthome.core.items.GenericItem)39 ItemNotFoundException (org.eclipse.smarthome.core.items.ItemNotFoundException)37 SwitchItem (org.eclipse.smarthome.core.library.items.SwitchItem)35 NumberItem (org.eclipse.smarthome.core.library.items.NumberItem)31 State (org.eclipse.smarthome.core.types.State)26 Test (org.junit.Test)26 ItemRegistry (org.eclipse.smarthome.core.items.ItemRegistry)14 RollershutterItem (org.eclipse.smarthome.core.library.items.RollershutterItem)14 StringItem (org.eclipse.smarthome.core.library.items.StringItem)14 JavaOSGiTest (org.eclipse.smarthome.test.java.JavaOSGiTest)13 DimmerItem (org.eclipse.smarthome.core.library.items.DimmerItem)12 ColorItem (org.eclipse.smarthome.core.library.items.ColorItem)10 IntentInterpretation (org.openhab.ui.habot.nlp.IntentInterpretation)10 EventPublisher (org.eclipse.smarthome.core.events.EventPublisher)9 DecimalType (org.eclipse.smarthome.core.library.types.DecimalType)9 Thing (org.eclipse.smarthome.core.thing.Thing)9 Set (java.util.Set)8 Widget (org.eclipse.smarthome.model.sitemap.Widget)8