Search in sources :

Example 6 with StateDescriptionFragment

use of org.openhab.core.types.StateDescriptionFragment in project openhab-addons by openhab.

the class LxControlValueSelector method onStateChange.

/**
 * Get dynamic updates to the minimum, maximum and step values. Sets a new state description if these values are
 * available. If no updates to the min/max/step, calls parent class method to update selector value in the
 * framework.
 *
 * @param state state update from the Miniserver
 */
@Override
public void onStateChange(LxState state) {
    String stateName = state.getName();
    Object value = state.getStateValue();
    try {
        if (value instanceof Double) {
            if (STATE_MIN.equals(stateName)) {
                minValue = (Double) value;
            } else if (STATE_MAX.equals(stateName)) {
                maxValue = (Double) value;
            } else if (STATE_STEP.equals(stateName)) {
                stepValue = (Double) value;
                if (stepValue <= 0) {
                    logger.warn("Value selector step value <= 0: {}", stepValue);
                    stepValue = null;
                }
            } else {
                super.onStateChange(state);
                return;
            }
        }
    } catch (NumberFormatException e) {
        logger.debug("Error parsing value for state {}: {}", stateName, e.getMessage());
    }
    if (minValue != null && maxValue != null && stepValue != null && minValue < maxValue) {
        StateDescriptionFragment fragment = StateDescriptionFragmentBuilder.create().withMinimum(new BigDecimal(minValue)).withMaximum(new BigDecimal(maxValue)).withStep(new BigDecimal(stepValue)).withPattern(format).withReadOnly(false).build();
        addChannelStateDescriptionFragment(channelId, fragment);
        addChannelStateDescriptionFragment(numberChannelId, fragment);
    }
}
Also used : StateDescriptionFragment(org.openhab.core.types.StateDescriptionFragment) BigDecimal(java.math.BigDecimal)

Example 7 with StateDescriptionFragment

use of org.openhab.core.types.StateDescriptionFragment in project openhab-addons by openhab.

the class LxControlWebPage method initialize.

@Override
public void initialize(LxControlConfig config) {
    super.initialize(config);
    if (details != null) {
        if (details.url != null) {
            url = new StringType(details.url);
        }
        if (details.urlHd != null) {
            urlHd = new StringType(details.urlHd);
        }
    }
    StateDescriptionFragment fragment = StateDescriptionFragmentBuilder.create().withReadOnly(true).build();
    ChannelUID c1 = addChannel("String", new ChannelTypeUID(BINDING_ID, MINISERVER_CHANNEL_TYPE_RO_TEXT), defaultChannelLabel + " / URL", "Low resolution URL", tags, null, () -> url);
    addChannelStateDescriptionFragment(c1, fragment);
    ChannelUID c2 = addChannel("String", new ChannelTypeUID(BINDING_ID, MINISERVER_CHANNEL_TYPE_RO_TEXT), defaultChannelLabel + " / URL HD", "High resolution URL", tags, null, () -> urlHd);
    addChannelStateDescriptionFragment(c2, fragment);
}
Also used : ChannelTypeUID(org.openhab.core.thing.type.ChannelTypeUID) StringType(org.openhab.core.library.types.StringType) ChannelUID(org.openhab.core.thing.ChannelUID) StateDescriptionFragment(org.openhab.core.types.StateDescriptionFragment)

Example 8 with StateDescriptionFragment

use of org.openhab.core.types.StateDescriptionFragment in project openhab-core by openhab.

the class MetadataStateDescriptionFragmentProvider method getStateDescriptionFragment.

@Override
@Nullable
public StateDescriptionFragment getStateDescriptionFragment(String itemName, @Nullable Locale locale) {
    Metadata metadata = metadataRegistry.get(new MetadataKey(STATEDESCRIPTION_METADATA_NAMESPACE, itemName));
    if (metadata != null) {
        try {
            StateDescriptionFragmentBuilder builder = StateDescriptionFragmentBuilder.create();
            Object pattern = metadata.getConfiguration().get("pattern");
            if (pattern != null) {
                builder.withPattern((String) pattern);
            }
            Object min = metadata.getConfiguration().get("min");
            if (min != null) {
                builder.withMinimum(getBigDecimal(min));
            }
            Object max = metadata.getConfiguration().get("max");
            if (max != null) {
                builder.withMaximum(getBigDecimal(max));
            }
            Object step = metadata.getConfiguration().get("step");
            if (step != null) {
                builder.withStep(getBigDecimal(step));
            }
            Object readOnly = metadata.getConfiguration().get("readOnly");
            if (readOnly != null) {
                builder.withReadOnly(getBoolean(readOnly));
            }
            if (metadata.getConfiguration().containsKey("options")) {
                List<StateOption> stateOptions = Stream.of(metadata.getConfiguration().get("options").toString().split(",")).map(o -> {
                    return (o.contains("=")) ? new StateOption(o.split("=")[0].trim(), o.split("=")[1].trim()) : new StateOption(o.trim(), null);
                }).collect(Collectors.toList());
                builder.withOptions(stateOptions);
            }
            return builder.build();
        } catch (Exception e) {
            logger.warn("Unable to parse the stateDescription from metadata for item {}, ignoring it", itemName);
        }
    }
    return null;
}
Also used : Metadata(org.openhab.core.items.Metadata) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) Logger(org.slf4j.Logger) Constants(org.osgi.framework.Constants) StateDescriptionFragment(org.openhab.core.types.StateDescriptionFragment) StateDescriptionFragmentBuilder(org.openhab.core.types.StateDescriptionFragmentBuilder) LoggerFactory(org.slf4j.LoggerFactory) StateOption(org.openhab.core.types.StateOption) MetadataRegistry(org.openhab.core.items.MetadataRegistry) Collectors(java.util.stream.Collectors) MetadataKey(org.openhab.core.items.MetadataKey) BigDecimal(java.math.BigDecimal) List(java.util.List) Component(org.osgi.service.component.annotations.Component) Stream(java.util.stream.Stream) Nullable(org.eclipse.jdt.annotation.Nullable) Locale(java.util.Locale) Map(java.util.Map) BigInteger(java.math.BigInteger) Activate(org.osgi.service.component.annotations.Activate) Reference(org.osgi.service.component.annotations.Reference) StateDescriptionFragmentProvider(org.openhab.core.types.StateDescriptionFragmentProvider) StateDescriptionFragmentBuilder(org.openhab.core.types.StateDescriptionFragmentBuilder) Metadata(org.openhab.core.items.Metadata) MetadataKey(org.openhab.core.items.MetadataKey) StateOption(org.openhab.core.types.StateOption) Nullable(org.eclipse.jdt.annotation.Nullable)

Example 9 with StateDescriptionFragment

use of org.openhab.core.types.StateDescriptionFragment in project openhab-core by openhab.

the class ChannelCommandDescriptionProviderOSGiTest method beforeEach.

@BeforeEach
public void beforeEach() throws Exception {
    Mockito.when(componentContextMock.getBundleContext()).thenReturn(bundleContext);
    registerVolatileStorageService();
    itemRegistry = getService(ItemRegistry.class);
    assertNotNull(itemRegistry);
    final TestThingHandlerFactory thingHandlerFactory = new TestThingHandlerFactory();
    thingHandlerFactory.activate(componentContextMock);
    registerService(thingHandlerFactory, ThingHandlerFactory.class.getName());
    final StateDescriptionFragment stateDescriptionFragment = StateDescriptionFragmentBuilder.create().withMinimum(BigDecimal.ZERO).withMaximum(BigDecimal.valueOf(100)).withStep(BigDecimal.TEN).withPattern("%d Peek").withReadOnly(true).withOption(new StateOption("SOUND", "My great sound.")).build();
    final CommandDescription command = CommandDescriptionBuilder.create().withCommandOption(new CommandOption("COMMAND", "My command.")).build();
    final ChannelType channelType1 = ChannelTypeBuilder.state(new ChannelTypeUID("hue:state-as-command"), " ", CoreItemFactory.NUMBER).withStateDescriptionFragment(stateDescriptionFragment).build();
    final ChannelType channelType2 = ChannelTypeBuilder.state(new ChannelTypeUID("hue:static"), " ", CoreItemFactory.STRING).withTag("Light").withCommandDescription(command).build();
    final ChannelType channelType3 = ChannelTypeBuilder.state(CHANNEL_TYPE_UID, " ", CoreItemFactory.STRING).withTag("Light").build();
    List<ChannelType> channelTypes = new ArrayList<>();
    channelTypes.add(channelType1);
    channelTypes.add(channelType2);
    channelTypes.add(channelType3);
    registerService(new ChannelTypeProvider() {

        @Override
        public Collection<ChannelType> getChannelTypes(@Nullable Locale locale) {
            return channelTypes;
        }

        @Override
        @Nullable
        public ChannelType getChannelType(ChannelTypeUID channelTypeUID, @Nullable Locale locale) {
            for (final ChannelType channelType : channelTypes) {
                if (channelType.getUID().equals(channelTypeUID)) {
                    return channelType;
                }
            }
            return null;
        }
    });
    testBundle = SyntheticBundleInstaller.install(bundleContext, TEST_BUNDLE_NAME);
    assertThat(testBundle, is(notNullValue()));
    thingStatusInfoI18nLocalizationService = getService(ThingStatusInfoI18nLocalizationService.class);
    assertThat(thingStatusInfoI18nLocalizationService, is(notNullValue()));
    thingStatusInfoI18nLocalizationService.setBundleResolver(new BundleResolverImpl());
    List<ChannelDefinition> channelDefinitions = new ArrayList<>();
    channelDefinitions.add(new ChannelDefinitionBuilder("1", channelType1.getUID()).build());
    channelDefinitions.add(new ChannelDefinitionBuilder("7_1", channelType2.getUID()).build());
    channelDefinitions.add(new ChannelDefinitionBuilder("7_2", channelType3.getUID()).build());
    registerService(new SimpleThingTypeProvider(Set.of(ThingTypeBuilder.instance(new ThingTypeUID("hue:lamp"), "label").withChannelDefinitions(channelDefinitions).build())));
    List<Item> items = new ArrayList<>();
    items.add(new NumberItem("TestItem1"));
    items.add(new NumberItem("TestItem7_1"));
    items.add(new NumberItem("TestItem7_2"));
    registerService(new TestItemProvider(items));
    linkRegistry = getService(ItemChannelLinkRegistry.class);
}
Also used : Locale(java.util.Locale) ChannelDefinitionBuilder(org.openhab.core.thing.type.ChannelDefinitionBuilder) CommandOption(org.openhab.core.types.CommandOption) ArrayList(java.util.ArrayList) ItemRegistry(org.openhab.core.items.ItemRegistry) NumberItem(org.openhab.core.library.items.NumberItem) Item(org.openhab.core.items.Item) ChannelTypeUID(org.openhab.core.thing.type.ChannelTypeUID) ItemChannelLinkRegistry(org.openhab.core.thing.link.ItemChannelLinkRegistry) StateDescriptionFragment(org.openhab.core.types.StateDescriptionFragment) ThingStatusInfoI18nLocalizationService(org.openhab.core.thing.i18n.ThingStatusInfoI18nLocalizationService) CommandDescription(org.openhab.core.types.CommandDescription) ThingHandlerFactory(org.openhab.core.thing.binding.ThingHandlerFactory) BaseThingHandlerFactory(org.openhab.core.thing.binding.BaseThingHandlerFactory) StateOption(org.openhab.core.types.StateOption) NumberItem(org.openhab.core.library.items.NumberItem) ChannelDefinition(org.openhab.core.thing.type.ChannelDefinition) ChannelTypeProvider(org.openhab.core.thing.type.ChannelTypeProvider) Collection(java.util.Collection) ThingTypeUID(org.openhab.core.thing.ThingTypeUID) ChannelType(org.openhab.core.thing.type.ChannelType) Nullable(org.eclipse.jdt.annotation.Nullable) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 10 with StateDescriptionFragment

use of org.openhab.core.types.StateDescriptionFragment in project openhab-core by openhab.

the class ChannelTypeConverter method unmarshalType.

@SuppressWarnings("deprecation")
@Override
protected ChannelTypeXmlResult unmarshalType(HierarchicalStreamReader reader, UnmarshallingContext context, Map<String, String> attributes, NodeIterator nodeIterator) throws ConversionException {
    boolean advanced = readBoolean(attributes, "advanced", false);
    boolean system = readBoolean(attributes, "system", false);
    String uid = system ? XmlHelper.getSystemUID(super.getID(attributes)) : super.getUID(attributes, context);
    ChannelTypeUID channelTypeUID = new ChannelTypeUID(uid);
    String itemType = readItemType(nodeIterator);
    String kind = readKind(nodeIterator);
    String label = super.readLabel(nodeIterator);
    String description = super.readDescription(nodeIterator);
    String category = readCategory(nodeIterator);
    Set<String> tags = readTags(nodeIterator);
    StateDescription stateDescription = readStateDescription(nodeIterator);
    StateDescriptionFragment stateDescriptionFragment = stateDescription != null ? StateDescriptionFragmentBuilder.create(stateDescription).build() : null;
    CommandDescription commandDescription = readCommandDescription(nodeIterator);
    EventDescription eventDescription = readEventDescription(nodeIterator);
    AutoUpdatePolicy autoUpdatePolicy = readAutoUpdatePolicy(nodeIterator);
    Object[] configDescriptionObjects = super.getConfigDescriptionObjects(nodeIterator);
    if (kind == null) {
        // Default for kind is 'state'
        kind = "state";
    }
    ChannelKind cKind = ChannelKind.parse(kind);
    URI configDescriptionURI = (URI) configDescriptionObjects[0];
    final ChannelTypeBuilder<?> builder;
    if (cKind == ChannelKind.STATE) {
        builder = ChannelTypeBuilder.state(channelTypeUID, label, itemType).isAdvanced(advanced).withCategory(category).withConfigDescriptionURI(configDescriptionURI).withStateDescriptionFragment(stateDescriptionFragment).withAutoUpdatePolicy(autoUpdatePolicy).withCommandDescription(commandDescription);
    } else if (cKind == ChannelKind.TRIGGER) {
        builder = ChannelTypeBuilder.trigger(channelTypeUID, label).isAdvanced(advanced).withCategory(category).withConfigDescriptionURI(configDescriptionURI).withEventDescription(eventDescription);
    } else {
        throw new IllegalArgumentException(String.format("Unknown channel kind: '%s'", cKind));
    }
    if (description != null) {
        builder.withDescription(description);
    }
    if (tags != null) {
        builder.withTags(tags);
    }
    ChannelType channelType = builder.build();
    ChannelTypeXmlResult channelTypeXmlResult = new ChannelTypeXmlResult(channelType, (ConfigDescription) configDescriptionObjects[1], system);
    return channelTypeXmlResult;
}
Also used : CommandDescription(org.openhab.core.types.CommandDescription) ChannelKind(org.openhab.core.thing.type.ChannelKind) URI(java.net.URI) AutoUpdatePolicy(org.openhab.core.thing.type.AutoUpdatePolicy) ChannelTypeUID(org.openhab.core.thing.type.ChannelTypeUID) StateDescriptionFragment(org.openhab.core.types.StateDescriptionFragment) EventDescription(org.openhab.core.types.EventDescription) ChannelType(org.openhab.core.thing.type.ChannelType) StateDescription(org.openhab.core.types.StateDescription)

Aggregations

StateDescriptionFragment (org.openhab.core.types.StateDescriptionFragment)31 BigDecimal (java.math.BigDecimal)12 Test (org.junit.jupiter.api.Test)11 StateOption (org.openhab.core.types.StateOption)11 ChannelTypeUID (org.openhab.core.thing.type.ChannelTypeUID)8 StateDescription (org.openhab.core.types.StateDescription)8 ChannelUID (org.openhab.core.thing.ChannelUID)7 ArrayList (java.util.ArrayList)6 Channel (org.openhab.core.thing.Channel)5 Bridge (org.openhab.core.thing.Bridge)4 ItemChannelLinkRegistry (org.openhab.core.thing.link.ItemChannelLinkRegistry)4 Locale (java.util.Locale)3 Nullable (org.eclipse.jdt.annotation.Nullable)3 URI (java.net.URI)2 Collection (java.util.Collection)2 HashMap (java.util.HashMap)2 List (java.util.List)2 BeforeEach (org.junit.jupiter.api.BeforeEach)2 KM200ServiceObject (org.openhab.binding.km200.internal.KM200ServiceObject)2 Item (org.openhab.core.items.Item)2