]> git.basschouten.com Git - openhab-addons.git/blob
0d51d174f440d025bbd3f6797e4c9cf6b546ae08
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.knx.internal.channel;
14
15 import java.util.Map;
16 import java.util.Set;
17 import java.util.function.Function;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.openhab.core.thing.Channel;
21 import org.openhab.core.thing.type.ChannelTypeUID;
22
23 /**
24  * Helper class to find the matching {@link KNXChannel} for any given {@link ChannelTypeUID}.
25  *
26  * @author Simon Kaufmann - Initial contribution
27  * @author Jan N. Klug - Refactored to factory class
28  *
29  */
30 @NonNullByDefault
31 public final class KNXChannelFactory {
32
33     private static final Map<Set<String>, Function<Channel, KNXChannel>> TYPES = Map.ofEntries( //
34             Map.entry(TypeColor.SUPPORTED_CHANNEL_TYPES, TypeColor::new), //
35             Map.entry(TypeContact.SUPPORTED_CHANNEL_TYPES, TypeContact::new), //
36             Map.entry(TypeDateTime.SUPPORTED_CHANNEL_TYPES, TypeDateTime::new), //
37             Map.entry(TypeDimmer.SUPPORTED_CHANNEL_TYPES, TypeDimmer::new), //
38             Map.entry(TypeNumber.SUPPORTED_CHANNEL_TYPES, TypeNumber::new), //
39             Map.entry(TypeRollershutter.SUPPORTED_CHANNEL_TYPES, TypeRollershutter::new), //
40             Map.entry(TypeString.SUPPORTED_CHANNEL_TYPES, TypeString::new), //
41             Map.entry(TypeSwitch.SUPPORTED_CHANNEL_TYPES, TypeSwitch::new));
42
43     private KNXChannelFactory() {
44         // prevent instantiation
45     }
46
47     public static KNXChannel createKnxChannel(Channel channel) throws IllegalArgumentException {
48         ChannelTypeUID channelTypeUID = channel.getChannelTypeUID();
49         if (channelTypeUID == null) {
50             throw new IllegalArgumentException("Could not determine ChannelTypeUID for channel " + channel.getUID());
51         }
52
53         String channelType = channelTypeUID.getId();
54
55         Function<Channel, KNXChannel> supplier = TYPES.entrySet().stream().filter(e -> e.getKey().contains(channelType))
56                 .map(Map.Entry::getValue).findFirst()
57                 .orElseThrow(() -> new IllegalArgumentException(channelTypeUID + " is not a valid channel type ID"));
58
59         // typecast to avoid warning about unsafe return type; we know that the lookup returns non null values
60         return (KNXChannel) supplier.apply(channel);
61     }
62 }