Search in sources :

Example 36 with ThingBuilder

use of org.openhab.core.thing.binding.builder.ThingBuilder in project openhab-addons by openhab.

the class Util method checkAvailableChannels.

/**
 * check and add available channels on a thing
 *
 * @param thing the Thing
 * @param thingBuilder the ThingBuilder (needs to be passed as editThing is only available in the handler)
 * @param scpdUtil the SCPDUtil instance for this thing
 * @param deviceId the device id for this thing
 * @param deviceType the (SCPD) device-type for this thing
 * @param channels a (mutable) channel list for storing all channels
 */
public static void checkAvailableChannels(Thing thing, ThingBuilder thingBuilder, SCPDUtil scpdUtil, String deviceId, String deviceType, Map<ChannelUID, Tr064ChannelConfig> channels) {
    Tr064BaseThingConfiguration thingConfig = Tr064RootHandler.SUPPORTED_THING_TYPES.contains(thing.getThingTypeUID()) ? thing.getConfiguration().as(Tr064RootConfiguration.class) : thing.getConfiguration().as(Tr064SubConfiguration.class);
    channels.clear();
    CHANNEL_TYPES.stream().filter(channel -> deviceType.equals(channel.getService().getDeviceType())).forEach(channelTypeDescription -> {
        String channelId = channelTypeDescription.getName();
        String serviceId = channelTypeDescription.getService().getServiceId();
        String typeId = channelTypeDescription.getTypeId();
        Map<String, String> channelProperties = new HashMap<String, String>();
        if (typeId != null) {
            channelProperties.put("typeId", typeId);
        }
        Set<String> parameters = new HashSet<>();
        try {
            SCPDServiceType deviceService = scpdUtil.getDevice(deviceId).flatMap(device -> device.getServiceList().stream().filter(service -> service.getServiceId().equals(serviceId)).findFirst()).orElseThrow(() -> new ChannelConfigException("Service '" + serviceId + "' not found"));
            SCPDScpdType serviceRoot = scpdUtil.getService(deviceService.getServiceId()).orElseThrow(() -> new ChannelConfigException("Service definition for '" + serviceId + "' not found"));
            Tr064ChannelConfig channelConfig = new Tr064ChannelConfig(channelTypeDescription, deviceService);
            // get
            ActionType getAction = channelTypeDescription.getGetAction();
            if (getAction != null) {
                String actionName = getAction.getName();
                String argumentName = getAction.getArgument();
                SCPDActionType scpdAction = getAction(serviceRoot, actionName, "Get-Action");
                SCPDArgumentType scpdArgument = getArgument(scpdAction, argumentName, SCPDDirection.OUT);
                SCPDStateVariableType relatedStateVariable = getStateVariable(serviceRoot, scpdArgument);
                parameters.addAll(getAndCheckParameters(channelId, getAction, scpdAction, serviceRoot, thingConfig));
                channelConfig.setGetAction(scpdAction);
                channelConfig.setDataType(relatedStateVariable.getDataType());
            }
            // check set action
            ActionType setAction = channelTypeDescription.getSetAction();
            if (setAction != null) {
                String actionName = setAction.getName();
                String argumentName = setAction.getArgument();
                SCPDActionType scpdAction = getAction(serviceRoot, actionName, "Set-Action");
                if (argumentName != null) {
                    SCPDArgumentType scpdArgument = getArgument(scpdAction, argumentName, SCPDDirection.IN);
                    SCPDStateVariableType relatedStateVariable = getStateVariable(serviceRoot, scpdArgument);
                    if (channelConfig.getDataType().isEmpty()) {
                        channelConfig.setDataType(relatedStateVariable.getDataType());
                    } else if (!channelConfig.getDataType().equals(relatedStateVariable.getDataType())) {
                        throw new ChannelConfigException("dataType of set and get action are different");
                    }
                }
            }
            // everything is available, create the channel
            ChannelTypeUID channelTypeUID = new ChannelTypeUID(BINDING_ID, channelTypeDescription.getName());
            if (parameters.isEmpty()) {
                // we have no parameters, so create a single channel
                ChannelUID channelUID = new ChannelUID(thing.getUID(), channelId);
                ChannelBuilder channelBuilder = ChannelBuilder.create(channelUID, channelTypeDescription.getItem().getType()).withType(channelTypeUID).withProperties(channelProperties);
                thingBuilder.withChannel(channelBuilder.build());
                channels.put(channelUID, channelConfig);
            } else {
                // create a channel for each parameter
                parameters.forEach(parameter -> {
                    // remove comment: split parameter at '#', discard everything after that and remove
                    // trailing spaces
                    String rawParameter = parameter.split("#")[0].trim();
                    String normalizedParameter = UIDUtils.encode(rawParameter);
                    ChannelUID channelUID = new ChannelUID(thing.getUID(), channelId + "_" + normalizedParameter);
                    ChannelBuilder channelBuilder = ChannelBuilder.create(channelUID, channelTypeDescription.getItem().getType()).withType(channelTypeUID).withProperties(channelProperties).withLabel(channelTypeDescription.getLabel() + " " + parameter);
                    thingBuilder.withChannel(channelBuilder.build());
                    Tr064ChannelConfig channelConfig1 = new Tr064ChannelConfig(channelConfig);
                    channelConfig1.setParameter(rawParameter);
                    channels.put(channelUID, channelConfig1);
                });
            }
        } catch (ChannelConfigException e) {
            LOGGER.debug("Channel {} not available: {}", channelId, e.getMessage());
        }
    });
}
Also used : ActionType(org.openhab.binding.tr064.internal.dto.config.ActionType) XMLInputFactory(javax.xml.stream.XMLInputFactory) SOAPException(javax.xml.soap.SOAPException) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) Tr064RootHandler(org.openhab.binding.tr064.internal.Tr064RootHandler) HttpClient(org.eclipse.jetty.client.HttpClient) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) XMLStreamReader(javax.xml.stream.XMLStreamReader) Nullable(org.eclipse.jdt.annotation.Nullable) Duration(java.time.Duration) Map(java.util.Map) XMLStreamException(javax.xml.stream.XMLStreamException) ThingBuilder(org.openhab.core.thing.binding.builder.ThingBuilder) Tr064RootConfiguration(org.openhab.binding.tr064.internal.config.Tr064RootConfiguration) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) ChannelBuilder(org.openhab.core.thing.binding.builder.ChannelBuilder) Set(java.util.Set) ChannelTypeDescriptions(org.openhab.binding.tr064.internal.dto.config.ChannelTypeDescriptions) Tr064ChannelConfig(org.openhab.binding.tr064.internal.config.Tr064ChannelConfig) Collectors(java.util.stream.Collectors) JAXBException(javax.xml.bind.JAXBException) Tr064SubConfiguration(org.openhab.binding.tr064.internal.config.Tr064SubConfiguration) List(java.util.List) SCPDActionType(org.openhab.binding.tr064.internal.dto.scpd.service.SCPDActionType) Stream(java.util.stream.Stream) SCPDScpdType(org.openhab.binding.tr064.internal.dto.scpd.service.SCPDScpdType) Optional(java.util.Optional) SCPDStateVariableType(org.openhab.binding.tr064.internal.dto.scpd.service.SCPDStateVariableType) ChannelTypeDescription(org.openhab.binding.tr064.internal.dto.config.ChannelTypeDescription) SCPDArgumentType(org.openhab.binding.tr064.internal.dto.scpd.service.SCPDArgumentType) SCPDServiceType(org.openhab.binding.tr064.internal.dto.scpd.root.SCPDServiceType) StreamSource(javax.xml.transform.stream.StreamSource) HashMap(java.util.HashMap) HashSet(java.util.HashSet) Thing(org.openhab.core.thing.Thing) Tr064BaseThingConfiguration(org.openhab.binding.tr064.internal.config.Tr064BaseThingConfiguration) Tr064BindingConstants(org.openhab.binding.tr064.internal.Tr064BindingConstants) UIDUtils(org.openhab.core.util.UIDUtils) ChannelUID(org.openhab.core.thing.ChannelUID) JAXBContext(javax.xml.bind.JAXBContext) Unmarshaller(javax.xml.bind.Unmarshaller) ParameterType(org.openhab.binding.tr064.internal.dto.config.ParameterType) Logger(org.slf4j.Logger) NodeList(org.w3c.dom.NodeList) JAXBElement(javax.xml.bind.JAXBElement) ExpiringCacheMap(org.openhab.core.cache.ExpiringCacheMap) Field(java.lang.reflect.Field) SCPDDirection(org.openhab.binding.tr064.internal.dto.scpd.service.SCPDDirection) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) HttpMethod(org.eclipse.jetty.http.HttpMethod) ChannelTypeUID(org.openhab.core.thing.type.ChannelTypeUID) SOAPMessage(javax.xml.soap.SOAPMessage) ChannelConfigException(org.openhab.binding.tr064.internal.ChannelConfigException) Collections(java.util.Collections) InputStream(java.io.InputStream) SCPDStateVariableType(org.openhab.binding.tr064.internal.dto.scpd.service.SCPDStateVariableType) Tr064SubConfiguration(org.openhab.binding.tr064.internal.config.Tr064SubConfiguration) SCPDServiceType(org.openhab.binding.tr064.internal.dto.scpd.root.SCPDServiceType) Tr064RootConfiguration(org.openhab.binding.tr064.internal.config.Tr064RootConfiguration) ActionType(org.openhab.binding.tr064.internal.dto.config.ActionType) SCPDActionType(org.openhab.binding.tr064.internal.dto.scpd.service.SCPDActionType) SCPDScpdType(org.openhab.binding.tr064.internal.dto.scpd.service.SCPDScpdType) HashMap(java.util.HashMap) SCPDArgumentType(org.openhab.binding.tr064.internal.dto.scpd.service.SCPDArgumentType) ChannelTypeUID(org.openhab.core.thing.type.ChannelTypeUID) Tr064BaseThingConfiguration(org.openhab.binding.tr064.internal.config.Tr064BaseThingConfiguration) ChannelUID(org.openhab.core.thing.ChannelUID) Tr064ChannelConfig(org.openhab.binding.tr064.internal.config.Tr064ChannelConfig) ChannelConfigException(org.openhab.binding.tr064.internal.ChannelConfigException) ChannelBuilder(org.openhab.core.thing.binding.builder.ChannelBuilder) SCPDActionType(org.openhab.binding.tr064.internal.dto.scpd.service.SCPDActionType) HashSet(java.util.HashSet)

Example 37 with ThingBuilder

use of org.openhab.core.thing.binding.builder.ThingBuilder in project openhab-addons by openhab.

the class VigiCruesHandler method discoverAttributes.

private Map<String, String> discoverAttributes(StationConfiguration config) {
    Map<String, String> properties = new HashMap<>();
    ThingBuilder thingBuilder = editThing();
    List<Channel> channels = new ArrayList<>(getThing().getChannels());
    try {
        HubEauResponse stationDetails = apiHandler.discoverStations(config.id);
        stationDetails.stations.stream().findFirst().ifPresent(station -> {
            PointType stationLocation = new PointType(String.format(Locale.US, "%f,%f", station.latitudeStation, station.longitudeStation));
            properties.put(LOCATION, stationLocation.toString());
            PointType serverLocation = locationProvider.getLocation();
            if (serverLocation != null) {
                DecimalType distance = serverLocation.distanceFrom(stationLocation);
                properties.put(DISTANCE, new QuantityType<>(distance, SIUnits.METRE).toString());
            }
            properties.put(RIVER, station.libelleCoursEau);
        });
    } catch (VigiCruesException e) {
        logger.info("Unable to retrieve station location details {} : {}", config.id, e.getMessage());
    }
    try {
        CdStationHydro refineStation = apiHandler.getStationDetails(config.id);
        if (refineStation.vigilanceCrues.cruesHistoriques == null) {
            throw new VigiCruesException("No historical data available");
        }
        refineStation.vigilanceCrues.cruesHistoriques.stream().forEach(crue -> properties.putAll(crue.getDescription()));
        String codeTerritoire = refineStation.vigilanceCrues.pereBoitEntVigiCru.cdEntVigiCru;
        TerEntVigiCru territoire = apiHandler.getTerritoire(codeTerritoire);
        for (VicANMoinsUn troncon : territoire.vicTerEntVigiCru.vicANMoinsUn) {
            TronEntVigiCru detail = apiHandler.getTroncon(troncon.vicCdEntVigiCru);
            if (detail.getStations().anyMatch(s -> config.id.equalsIgnoreCase(s.vicCdEntVigiCru))) {
                properties.put(TRONCON, troncon.vicCdEntVigiCru);
                break;
            }
        }
    } catch (VigiCruesException e) {
        logger.info("Historical flooding data are not available {} : {}", config.id, e.getMessage());
        channels.removeIf(channel -> channel.getUID().getId().contains(RELATIVE_PREFIX));
    }
    if (!properties.containsKey(TRONCON)) {
        channels.removeIf(channel -> channel.getUID().getId().contains(ALERT));
        channels.removeIf(channel -> channel.getUID().getId().contains(COMMENT));
    }
    try {
        OpenDatasoftResponse measures = apiHandler.getMeasures(config.id);
        measures.getFirstRecord().ifPresent(field -> {
            if (field.getHeight() == -1) {
                channels.removeIf(channel -> (channel.getUID().getId().contains(HEIGHT)));
            }
            if (field.getFlow() == -1) {
                channels.removeIf(channel -> (channel.getUID().getId().contains(FLOW)));
            }
        });
    } catch (VigiCruesException e) {
        logger.warn("Unable to read measurements data {} : {}", config.id, e.getMessage());
    }
    thingBuilder.withChannels(channels);
    updateThing(thingBuilder.build());
    return properties;
}
Also used : CdStationHydro(org.openhab.binding.vigicrues.internal.dto.vigicrues.CdStationHydro) SIUnits(org.openhab.core.library.unit.SIUnits) ScheduledFuture(java.util.concurrent.ScheduledFuture) Unit(javax.measure.Unit) StringType(org.openhab.core.library.types.StringType) ZonedDateTime(java.time.ZonedDateTime) ApiHandler(org.openhab.binding.vigicrues.internal.api.ApiHandler) LocationProvider(org.openhab.core.i18n.LocationProvider) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) DateTimeType(org.openhab.core.library.types.DateTimeType) InfoVigiCru(org.openhab.binding.vigicrues.internal.dto.vigicrues.InfoVigiCru) ArrayList(java.util.ArrayList) Thing(org.openhab.core.thing.Thing) Nullable(org.eclipse.jdt.annotation.Nullable) Locale(java.util.Locale) Map(java.util.Map) VigiCruesException(org.openhab.binding.vigicrues.internal.api.VigiCruesException) ThingBuilder(org.openhab.core.thing.binding.builder.ThingBuilder) ChannelUID(org.openhab.core.thing.ChannelUID) StationConfiguration(org.openhab.binding.vigicrues.internal.StationConfiguration) DecimalType(org.openhab.core.library.types.DecimalType) Units(org.openhab.core.library.unit.Units) QuantityType(org.openhab.core.library.types.QuantityType) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) ThingStatus(org.openhab.core.thing.ThingStatus) Command(org.openhab.core.types.Command) Logger(org.slf4j.Logger) VigiCruesBindingConstants(org.openhab.binding.vigicrues.internal.VigiCruesBindingConstants) OpenDatasoftResponse(org.openhab.binding.vigicrues.internal.dto.opendatasoft.OpenDatasoftResponse) UnDefType(org.openhab.core.types.UnDefType) RefreshType(org.openhab.core.types.RefreshType) BaseThingHandler(org.openhab.core.thing.binding.BaseThingHandler) IOException(java.io.IOException) CdStationHydro(org.openhab.binding.vigicrues.internal.dto.vigicrues.CdStationHydro) ThingStatusDetail(org.openhab.core.thing.ThingStatusDetail) HubEauResponse(org.openhab.binding.vigicrues.internal.dto.hubeau.HubEauResponse) Collectors(java.util.stream.Collectors) VicANMoinsUn(org.openhab.binding.vigicrues.internal.dto.vigicrues.VicANMoinsUn) TimeUnit(java.util.concurrent.TimeUnit) RawType(org.openhab.core.library.types.RawType) Channel(org.openhab.core.thing.Channel) List(java.util.List) PointType(org.openhab.core.library.types.PointType) TerEntVigiCru(org.openhab.binding.vigicrues.internal.dto.vigicrues.TerEntVigiCru) TronEntVigiCru(org.openhab.binding.vigicrues.internal.dto.vigicrues.TronEntVigiCru) InputStream(java.io.InputStream) ThingBuilder(org.openhab.core.thing.binding.builder.ThingBuilder) OpenDatasoftResponse(org.openhab.binding.vigicrues.internal.dto.opendatasoft.OpenDatasoftResponse) TronEntVigiCru(org.openhab.binding.vigicrues.internal.dto.vigicrues.TronEntVigiCru) HashMap(java.util.HashMap) Channel(org.openhab.core.thing.Channel) ArrayList(java.util.ArrayList) VicANMoinsUn(org.openhab.binding.vigicrues.internal.dto.vigicrues.VicANMoinsUn) TerEntVigiCru(org.openhab.binding.vigicrues.internal.dto.vigicrues.TerEntVigiCru) HubEauResponse(org.openhab.binding.vigicrues.internal.dto.hubeau.HubEauResponse) QuantityType(org.openhab.core.library.types.QuantityType) PointType(org.openhab.core.library.types.PointType) DecimalType(org.openhab.core.library.types.DecimalType) VigiCruesException(org.openhab.binding.vigicrues.internal.api.VigiCruesException)

Example 38 with ThingBuilder

use of org.openhab.core.thing.binding.builder.ThingBuilder in project openhab-addons by openhab.

the class NUTHandler method initDynamicChannels.

/**
 * Initializes any channels configured by the user by creating complementary channel types and recreate the channels
 * of the thing.
 */
private void initDynamicChannels() {
    final NUTChannelTypeProvider localChannelTypeProvider = channelTypeProvider;
    final NUTDynamicChannelFactory localDynamicChannelFactory = dynamicChannelFactory;
    if (localChannelTypeProvider == null || localDynamicChannelFactory == null) {
        return;
    }
    final List<Channel> updatedChannels = new ArrayList<>();
    boolean rebuildChannels = false;
    for (final Channel channel : thing.getChannels()) {
        if (channel.getConfiguration().getProperties().isEmpty()) {
            updatedChannels.add(channel);
        } else {
            // If the channel has a custom created channel type id the channel should be recreated.
            // This is specific for Quantity type channels created in thing files.
            final boolean customChannel = channel.getChannelTypeUID() == null;
            final NUTDynamicChannelConfiguration channelConfig = channel.getConfiguration().as(NUTDynamicChannelConfiguration.class);
            final Channel dynamicChannel;
            rebuildChannels = customChannel;
            if (customChannel) {
                dynamicChannel = localDynamicChannelFactory.createChannel(channel, channelConfig);
                if (dynamicChannel == null) {
                    logger.debug("Could not initialize the dynamic channel '{}'. This channel will be ignored ", channel.getUID());
                    continue;
                } else {
                    logger.debug("Updating channel '{}' with dynamic channelType settings: {}", channel.getUID(), dynamicChannel.getChannelTypeUID());
                }
            } else {
                logger.debug("Mapping standard dynamic channel '{}' with dynamic channelType settings: {}", channel.getUID(), channel.getChannelTypeUID());
                dynamicChannel = channel;
            }
            userChannelToNutMap.put(channel.getUID(), channelConfig);
            updatedChannels.add(dynamicChannel);
        }
    }
    if (rebuildChannels) {
        final ThingBuilder thingBuilder = editThing();
        thingBuilder.withChannels(updatedChannels);
        updateThing(thingBuilder.build());
    }
}
Also used : ThingBuilder(org.openhab.core.thing.binding.builder.ThingBuilder) Channel(org.openhab.core.thing.Channel) ArrayList(java.util.ArrayList)

Example 39 with ThingBuilder

use of org.openhab.core.thing.binding.builder.ThingBuilder in project openhab-addons by openhab.

the class SomfyTahomaBaseThingHandler method createChannel.

private void createChannel(String name, String type, String label, ChannelTypeUID channelType) {
    ThingBuilder thingBuilder = editThing();
    Channel channel = ChannelBuilder.create(new ChannelUID(thing.getUID(), name), type).withLabel(label).withType(channelType).build();
    thingBuilder.withChannel(channel);
    updateThing(thingBuilder.build());
}
Also used : ThingBuilder(org.openhab.core.thing.binding.builder.ThingBuilder) ChannelUID(org.openhab.core.thing.ChannelUID) Channel(org.openhab.core.thing.Channel)

Example 40 with ThingBuilder

use of org.openhab.core.thing.binding.builder.ThingBuilder in project openhab-addons by openhab.

the class SimpleDeviceHandler method assertChannel.

/**
 * Assert that all channels inside of our thing are well defined.
 *
 * Only channels which can not be found are created.
 *
 * @param solarwattChannel channel description with name and unit
 */
protected void assertChannel(SolarwattChannel solarwattChannel) {
    ChannelUID channelUID = new ChannelUID(this.getThing().getUID(), solarwattChannel.getChannelName());
    ChannelTypeUID channelType = this.channelTypeProvider.assertChannelType(solarwattChannel);
    if (this.getThing().getChannel(channelUID) == null) {
        ThingBuilder thingBuilder = this.editThing();
        thingBuilder.withChannel(getChannelBuilder(solarwattChannel, channelUID, channelType).build());
        this.updateThing(thingBuilder.build());
    }
}
Also used : ThingBuilder(org.openhab.core.thing.binding.builder.ThingBuilder) ChannelTypeUID(org.openhab.core.thing.type.ChannelTypeUID) ChannelUID(org.openhab.core.thing.ChannelUID)

Aggregations

ThingBuilder (org.openhab.core.thing.binding.builder.ThingBuilder)105 Channel (org.openhab.core.thing.Channel)71 ChannelUID (org.openhab.core.thing.ChannelUID)59 ChannelTypeUID (org.openhab.core.thing.type.ChannelTypeUID)38 ArrayList (java.util.ArrayList)37 Thing (org.openhab.core.thing.Thing)28 HashMap (java.util.HashMap)22 ChannelBuilder (org.openhab.core.thing.binding.builder.ChannelBuilder)19 Map (java.util.Map)18 Bridge (org.openhab.core.thing.Bridge)17 ThingStatus (org.openhab.core.thing.ThingStatus)17 ThingStatusDetail (org.openhab.core.thing.ThingStatusDetail)17 Logger (org.slf4j.Logger)17 LoggerFactory (org.slf4j.LoggerFactory)17 NonNullByDefault (org.eclipse.jdt.annotation.NonNullByDefault)16 Nullable (org.eclipse.jdt.annotation.Nullable)15 List (java.util.List)14 Collectors (java.util.stream.Collectors)14 Configuration (org.openhab.core.config.core.Configuration)14 Command (org.openhab.core.types.Command)11