Search in sources :

Example 1 with StateDescription

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

the class HttpThingHandler method createChannel.

/**
 * create all necessary information to handle every channel
 *
 * @param channel a thing channel
 */
private void createChannel(Channel channel) {
    ChannelUID channelUID = channel.getUID();
    HttpChannelConfig channelConfig = channel.getConfiguration().as(HttpChannelConfig.class);
    String stateUrl = concatenateUrlParts(config.baseURL, channelConfig.stateExtension);
    String commandUrl = channelConfig.commandExtension == null ? stateUrl : concatenateUrlParts(config.baseURL, channelConfig.commandExtension);
    String acceptedItemType = channel.getAcceptedItemType();
    if (acceptedItemType == null) {
        logger.warn("Cannot determine item-type for channel '{}'", channelUID);
        return;
    }
    ItemValueConverter itemValueConverter;
    switch(acceptedItemType) {
        case "Color":
            itemValueConverter = createItemConverter(ColorItemConverter::new, commandUrl, channelUID, channelConfig);
            break;
        case "DateTime":
            itemValueConverter = createGenericItemConverter(commandUrl, channelUID, channelConfig, DateTimeType::new);
            break;
        case "Dimmer":
            itemValueConverter = createItemConverter(DimmerItemConverter::new, commandUrl, channelUID, channelConfig);
            break;
        case "Contact":
        case "Switch":
            itemValueConverter = createItemConverter(FixedValueMappingItemConverter::new, commandUrl, channelUID, channelConfig);
            break;
        case "Image":
            itemValueConverter = new ImageItemConverter(state -> updateState(channelUID, state));
            break;
        case "Location":
            itemValueConverter = createGenericItemConverter(commandUrl, channelUID, channelConfig, PointType::new);
            break;
        case "Number":
            itemValueConverter = createItemConverter(NumberItemConverter::new, commandUrl, channelUID, channelConfig);
            break;
        case "Player":
            itemValueConverter = createItemConverter(PlayerItemConverter::new, commandUrl, channelUID, channelConfig);
            break;
        case "Rollershutter":
            itemValueConverter = createItemConverter(RollershutterItemConverter::new, commandUrl, channelUID, channelConfig);
            break;
        case "String":
            itemValueConverter = createGenericItemConverter(commandUrl, channelUID, channelConfig, StringType::new);
            break;
        default:
            logger.warn("Unsupported item-type '{}'", channel.getAcceptedItemType());
            return;
    }
    channels.put(channelUID, itemValueConverter);
    if (channelConfig.mode != HttpChannelMode.WRITEONLY) {
        // we need a key consisting of stateContent and URL, only if both are equal, we can use the same cache
        String key = channelConfig.stateContent + "$" + stateUrl;
        channelUrls.put(channelUID, key);
        urlHandlers.computeIfAbsent(key, k -> new RefreshingUrlCache(scheduler, rateLimitedHttpClient, stateUrl, config, channelConfig.stateContent)).addConsumer(itemValueConverter::process);
    }
    StateDescription stateDescription = StateDescriptionFragmentBuilder.create().withReadOnly(channelConfig.mode == HttpChannelMode.READONLY).build().toStateDescription();
    if (stateDescription != null) {
        // if the state description is not available, we don't need to add it
        httpDynamicStateDescriptionProvider.setDescription(channelUID, stateDescription);
    }
}
Also used : StringType(org.openhab.core.library.types.StringType) Date(java.util.Date) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) ValueTransformationProvider(org.openhab.binding.http.internal.transform.ValueTransformationProvider) StateDescription(org.openhab.core.types.StateDescription) DateTimeType(org.openhab.core.library.types.DateTimeType) Request(org.eclipse.jetty.client.api.Request) GenericItemConverter(org.openhab.binding.http.internal.converter.GenericItemConverter) HttpClient(org.eclipse.jetty.client.HttpClient) Nullable(org.eclipse.jdt.annotation.Nullable) ItemValueConverter(org.openhab.binding.http.internal.converter.ItemValueConverter) ImageItemConverter(org.openhab.binding.http.internal.converter.ImageItemConverter) Map(java.util.Map) URI(java.net.URI) HttpThingConfig(org.openhab.binding.http.internal.config.HttpThingConfig) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) ColorItemConverter(org.openhab.binding.http.internal.converter.ColorItemConverter) HttpResponseListener(org.openhab.binding.http.internal.http.HttpResponseListener) Set(java.util.Set) BaseThingHandler(org.openhab.core.thing.binding.BaseThingHandler) DigestAuthentication(org.eclipse.jetty.client.util.DigestAuthentication) FixedValueMappingItemConverter(org.openhab.binding.http.internal.converter.FixedValueMappingItemConverter) Channel(org.openhab.core.thing.Channel) Base64(java.util.Base64) HttpChannelConfig(org.openhab.binding.http.internal.config.HttpChannelConfig) PointType(org.openhab.core.library.types.PointType) BasicAuthentication(org.eclipse.jetty.client.util.BasicAuthentication) PlayerItemConverter(org.openhab.binding.http.internal.converter.PlayerItemConverter) RateLimitedHttpClient(org.openhab.binding.http.internal.http.RateLimitedHttpClient) AbstractTransformingItemConverter(org.openhab.binding.http.internal.converter.AbstractTransformingItemConverter) RefreshingUrlCache(org.openhab.binding.http.internal.http.RefreshingUrlCache) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Authentication(org.eclipse.jetty.client.api.Authentication) Content(org.openhab.binding.http.internal.http.Content) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) Function(java.util.function.Function) Thing(org.openhab.core.thing.Thing) AuthenticationStore(org.eclipse.jetty.client.api.AuthenticationStore) ChannelUID(org.openhab.core.thing.ChannelUID) NumberItemConverter(org.openhab.binding.http.internal.converter.NumberItemConverter) ThingStatus(org.openhab.core.thing.ThingStatus) Command(org.openhab.core.types.Command) Logger(org.slf4j.Logger) MalformedURLException(java.net.MalformedURLException) HttpChannelMode(org.openhab.binding.http.internal.config.HttpChannelMode) State(org.openhab.core.types.State) RefreshType(org.openhab.core.types.RefreshType) StateDescriptionFragmentBuilder(org.openhab.core.types.StateDescriptionFragmentBuilder) ThingStatusDetail(org.openhab.core.thing.ThingStatusDetail) RollershutterItemConverter(org.openhab.binding.http.internal.converter.RollershutterItemConverter) TimeUnit(java.util.concurrent.TimeUnit) HttpMethod(org.eclipse.jetty.http.HttpMethod) HttpAuthException(org.openhab.binding.http.internal.http.HttpAuthException) DimmerItemConverter(org.openhab.binding.http.internal.converter.DimmerItemConverter) ChannelUID(org.openhab.core.thing.ChannelUID) RefreshingUrlCache(org.openhab.binding.http.internal.http.RefreshingUrlCache) ImageItemConverter(org.openhab.binding.http.internal.converter.ImageItemConverter) HttpChannelConfig(org.openhab.binding.http.internal.config.HttpChannelConfig) ItemValueConverter(org.openhab.binding.http.internal.converter.ItemValueConverter) StateDescription(org.openhab.core.types.StateDescription)

Example 2 with StateDescription

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

the class LxControlTest method testChannel.

void testChannel(LxControl ctrl, String itemType, String namePostFix, BigDecimal min, BigDecimal max, BigDecimal step, String format, Boolean readOnly, List<StateOption> options, Set<String> tags) {
    assertNotNull(ctrl);
    Channel c = getChannel(getExpectedName(ctrl.getLabel(), ctrl.getRoom().getName(), namePostFix), ctrl);
    assertNotNull(c);
    assertNotNull(c.getUID());
    assertNotNull(c.getDescription());
    assertEquals(itemType, c.getAcceptedItemType());
    assertEquals(ChannelKind.STATE, c.getKind());
    StateDescription d = handler.stateDescriptions.get(c.getUID());
    if (readOnly != null || min != null || max != null || step != null || format != null || options != null) {
        assertNotNull(d);
        assertEquals(min, d.getMinimum());
        assertEquals(max, d.getMaximum());
        assertEquals(step, d.getStep());
        assertEquals(format, d.getPattern());
        assertEquals(readOnly, d.isReadOnly());
        List<StateOption> opts = d.getOptions();
        if (options == null) {
            assertTrue(opts.isEmpty());
        } else {
            assertNotNull(opts);
            assertEquals(options.size(), opts.size());
            options.forEach(o -> {
                String label = o.getLabel();
                long num = opts.stream().filter(f -> label != null && label.equals(f.getLabel()) && o.getValue().equals(f.getValue())).collect(Collectors.counting());
                assertEquals(1, num);
            });
        }
    } else {
        assertNull(d);
    }
    if (tags != null) {
        assertThat(c.getDefaultTags(), hasItems(tags.toArray(new String[0])));
    } else {
        assertThat(c.getDefaultTags(), empty());
    }
}
Also used : LxContainer(org.openhab.binding.loxone.internal.types.LxContainer) LxUuid(org.openhab.binding.loxone.internal.types.LxUuid) Command(org.openhab.core.types.Command) Collection(java.util.Collection) State(org.openhab.core.types.State) Matchers(org.hamcrest.Matchers) Set(java.util.Set) StateDescription(org.openhab.core.types.StateDescription) IOException(java.io.IOException) StateOption(org.openhab.core.types.StateOption) Collectors(java.util.stream.Collectors) BigDecimal(java.math.BigDecimal) Channel(org.openhab.core.thing.Channel) List(java.util.List) Type(java.lang.reflect.Type) ChannelKind(org.openhab.core.thing.type.ChannelKind) Map(java.util.Map) LxState(org.openhab.binding.loxone.internal.types.LxState) Assertions(org.junit.jupiter.api.Assertions) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) LxCategory(org.openhab.binding.loxone.internal.types.LxCategory) Channel(org.openhab.core.thing.Channel) StateOption(org.openhab.core.types.StateOption) StateDescription(org.openhab.core.types.StateDescription)

Example 3 with StateDescription

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

the class GenericMQTTThingHandler method initialize.

@Override
public void initialize() {
    initializeAvailabilityTopicsFromConfig();
    List<ChannelUID> configErrors = new ArrayList<>();
    for (Channel channel : thing.getChannels()) {
        final ChannelTypeUID channelTypeUID = channel.getChannelTypeUID();
        if (channelTypeUID == null) {
            logger.warn("Channel {} has no type", channel.getLabel());
            continue;
        }
        final ChannelConfig channelConfig = channel.getConfiguration().as(ChannelConfig.class);
        try {
            Value value = ValueFactory.createValueState(channelConfig, channelTypeUID.getId());
            ChannelState channelState = createChannelState(channelConfig, channel.getUID(), value);
            channelStateByChannelUID.put(channel.getUID(), channelState);
            StateDescription description = value.createStateDescription(channelConfig.commandTopic.isBlank()).build().toStateDescription();
            if (description != null) {
                stateDescProvider.setDescription(channel.getUID(), description);
            }
        } catch (IllegalArgumentException e) {
            logger.warn("Configuration error for channel '{}'", channel.getUID(), e);
            configErrors.add(channel.getUID());
        }
    }
    // in question to the user.
    if (!configErrors.isEmpty()) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Remove and recreate: " + configErrors.stream().map(ChannelUID::getAsString).collect(Collectors.joining(",")));
        return;
    }
    super.initialize();
}
Also used : ChannelState(org.openhab.binding.mqtt.generic.ChannelState) ChannelTypeUID(org.openhab.core.thing.type.ChannelTypeUID) ChannelConfig(org.openhab.binding.mqtt.generic.ChannelConfig) ChannelUID(org.openhab.core.thing.ChannelUID) Channel(org.openhab.core.thing.Channel) ArrayList(java.util.ArrayList) Value(org.openhab.binding.mqtt.generic.values.Value) StateDescription(org.openhab.core.types.StateDescription)

Example 4 with StateDescription

use of org.openhab.core.types.StateDescription in project addons by smarthomej.

the class AbstractDigitalOwDevice method configureChannels.

@Override
public void configureChannels() throws OwException {
    Thing thing = callback.getThing();
    OwDynamicStateDescriptionProvider dynamicStateDescriptionProvider = callback.getDynamicStateDescriptionProvider();
    for (Integer i = 0; i < ioConfig.size(); i++) {
        String channelId = ioConfig.get(i).getChannelId();
        Channel channel = thing.getChannel(channelId);
        if (channel != null) {
            Configuration channelConfig = channel.getConfiguration();
            try {
                if (channelConfig.get(CONFIG_DIGITAL_MODE) != null) {
                    ioConfig.get(i).setIoMode((String) channelConfig.get(CONFIG_DIGITAL_MODE));
                }
                if (channelConfig.get(CONFIG_DIGITAL_LOGIC) != null) {
                    ioConfig.get(i).setIoLogic((String) channelConfig.get(CONFIG_DIGITAL_LOGIC));
                }
            } catch (IllegalArgumentException e) {
                throw new OwException(channelId + " has invalid configuration");
            }
            if (dynamicStateDescriptionProvider != null) {
                StateDescription stateDescription = StateDescriptionFragmentBuilder.create().withReadOnly(ioConfig.get(i).isInput()).build().toStateDescription();
                if (stateDescription != null) {
                    dynamicStateDescriptionProvider.setDescription(ioConfig.get(i).getChannelUID(), stateDescription);
                } else {
                    logger.warn("Failed to create state description in thing {}", thing.getUID());
                }
            } else {
                logger.debug("state description may be inaccurate, state description provider not available in thing {}", thing.getUID());
            }
            logger.debug("configured {} channel {}: {}", thing.getUID(), i, ioConfig.get(i));
        } else {
            throw new OwException(channelId + " not found");
        }
    }
    isConfigured = true;
}
Also used : OwDynamicStateDescriptionProvider(org.smarthomej.binding.onewire.internal.OwDynamicStateDescriptionProvider) Configuration(org.openhab.core.config.core.Configuration) Channel(org.openhab.core.thing.Channel) Thing(org.openhab.core.thing.Thing) OwException(org.smarthomej.binding.onewire.internal.OwException) StateDescription(org.openhab.core.types.StateDescription)

Example 5 with StateDescription

use of org.openhab.core.types.StateDescription in project addons by smarthomej.

the class EchoHandler method createMusicProviderStateDescription.

private void createMusicProviderStateDescription(List<JsonMusicProvider> jsonMusicProviders) {
    List<StateOption> options = new ArrayList<>();
    for (JsonMusicProvider musicProvider : jsonMusicProviders) {
        List<String> properties = musicProvider.supportedProperties;
        String providerId = musicProvider.id;
        String displayName = musicProvider.displayName;
        if (properties != null && properties.contains("Alexa.Music.PlaySearchPhrase") && providerId != null && !providerId.isEmpty() && "AVAILABLE".equals(musicProvider.availability) && displayName != null && !displayName.isEmpty()) {
            options.add(new StateOption(providerId, displayName));
        }
    }
    ChannelUID channelUID = new ChannelUID(thing.getUID(), CHANNEL_MUSIC_PROVIDER_ID);
    StateDescription stateDescription = StateDescriptionFragmentBuilder.create().withOptions(options).build().toStateDescription();
    if (stateDescription != null) {
        dynamicStateDescriptionProvider.setDescription(channelUID, stateDescription);
    }
}
Also used : JsonMusicProvider(org.smarthomej.binding.amazonechocontrol.internal.jsons.JsonMusicProvider) ChannelUID(org.openhab.core.thing.ChannelUID) ArrayList(java.util.ArrayList) StateOption(org.openhab.core.types.StateOption) StateDescription(org.openhab.core.types.StateDescription)

Aggregations

StateDescription (org.openhab.core.types.StateDescription)47 Test (org.junit.jupiter.api.Test)19 StateOption (org.openhab.core.types.StateOption)15 Nullable (org.eclipse.jdt.annotation.Nullable)11 Channel (org.openhab.core.thing.Channel)9 ChannelUID (org.openhab.core.thing.ChannelUID)9 ArrayList (java.util.ArrayList)8 NumberItem (org.openhab.core.library.items.NumberItem)8 StringType (org.openhab.core.library.types.StringType)8 StateDescriptionFragment (org.openhab.core.types.StateDescriptionFragment)8 Item (org.openhab.core.items.Item)7 SwitchItem (org.openhab.core.library.items.SwitchItem)6 JavaOSGiTest (org.openhab.core.test.java.JavaOSGiTest)6 Thing (org.openhab.core.thing.Thing)6 State (org.openhab.core.types.State)6 Map (java.util.Map)5 Configuration (org.openhab.core.config.core.Configuration)5 GroupItem (org.openhab.core.items.GroupItem)5 ColorItem (org.openhab.core.library.items.ColorItem)5 DimmerItem (org.openhab.core.library.items.DimmerItem)5