2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.webthing.internal.link;
15 import java.util.function.BiConsumer;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.openhab.binding.webthing.internal.ChannelHandler;
19 import org.openhab.binding.webthing.internal.client.ConsumedThing;
20 import org.openhab.core.thing.Channel;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
25 * The {@link PropertyToChannelLink} represents a downstream link from a WebThing property to a Channel.
27 * @author Gregor Roth - Initial contribution
30 public class PropertyToChannelLink implements BiConsumer<String, Object> {
31 private final Logger logger = LoggerFactory.getLogger(PropertyToChannelLink.class);
32 private final ChannelHandler channelHandler;
33 private final Channel channel;
34 private final TypeConverter typeConverter;
37 * establish downstream link from a WebTHing property to a Channel
39 * @param webThing the WebThing to be linked
40 * @param propertyName the property name
41 * @param channelHandler the channel handler that provides updating the Item state of a channel
42 * @param channel the channel to be linked
43 * @throws UnknownPropertyException if the a WebThing property should be link that does not exist
45 public static void establish(ConsumedThing webThing, String propertyName, ChannelHandler channelHandler,
46 Channel channel) throws UnknownPropertyException {
47 new PropertyToChannelLink(webThing, propertyName, channelHandler, channel);
50 private PropertyToChannelLink(ConsumedThing webThing, String propertyName, ChannelHandler channelHandler,
51 Channel channel) throws UnknownPropertyException {
52 this.channel = channel;
53 var optionalProperty = webThing.getThingDescription().getProperty(propertyName);
54 if (optionalProperty.isPresent()) {
55 var propertyType = optionalProperty.get().type;
56 var acceptedType = channel.getAcceptedItemType();
57 if (acceptedType == null) {
58 this.typeConverter = TypeConverters.create("String", propertyType);
60 this.typeConverter = TypeConverters.create(acceptedType, propertyType);
62 this.channelHandler = channelHandler;
63 webThing.observeProperty(propertyName, this);
65 throw new UnknownPropertyException("property " + propertyName + " does not exits");
70 public void accept(String propertyName, Object value) {
71 var stateCommand = typeConverter.toStateCommand(value);
72 channelHandler.updateItemState(channel.getUID(), stateCommand);
73 logger.debug("channel {} updated with {} ({})", channel.getUID().getAsString(), value,
74 channel.getAcceptedItemType());