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.mqtt.homeassistant.internal.component;
15 import java.util.List;
17 import java.util.TreeMap;
18 import java.util.concurrent.CompletableFuture;
19 import java.util.concurrent.ScheduledExecutorService;
20 import java.util.stream.Collectors;
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.openhab.binding.mqtt.generic.ChannelStateUpdateListener;
25 import org.openhab.binding.mqtt.generic.MqttChannelTypeProvider;
26 import org.openhab.binding.mqtt.generic.TransformationServiceProvider;
27 import org.openhab.binding.mqtt.generic.utils.FutureCollector;
28 import org.openhab.binding.mqtt.generic.values.Value;
29 import org.openhab.binding.mqtt.homeassistant.generic.internal.MqttBindingConstants;
30 import org.openhab.binding.mqtt.homeassistant.internal.ComponentChannel;
31 import org.openhab.binding.mqtt.homeassistant.internal.HaID;
32 import org.openhab.binding.mqtt.homeassistant.internal.component.ComponentFactory.ComponentConfiguration;
33 import org.openhab.binding.mqtt.homeassistant.internal.config.dto.AbstractChannelConfiguration;
34 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
35 import org.openhab.core.thing.ChannelGroupUID;
36 import org.openhab.core.thing.type.ChannelDefinition;
37 import org.openhab.core.thing.type.ChannelGroupDefinition;
38 import org.openhab.core.thing.type.ChannelGroupType;
39 import org.openhab.core.thing.type.ChannelGroupTypeBuilder;
40 import org.openhab.core.thing.type.ChannelGroupTypeUID;
43 * A HomeAssistant component is comparable to a channel group.
44 * It has a name and consists of multiple channels.
46 * @author David Graeff - Initial contribution
47 * @param <C> Config class derived from {@link AbstractChannelConfiguration}
50 public abstract class AbstractComponent<C extends AbstractChannelConfiguration> {
51 private static final String JINJA_PREFIX = "JINJA:";
53 // Component location fields
54 private final ComponentConfiguration componentConfiguration;
55 protected final ChannelGroupTypeUID channelGroupTypeUID;
56 protected final ChannelGroupUID channelGroupUID;
57 protected final HaID haID;
59 // Channels and configuration
60 protected final Map<String, ComponentChannel> channels = new TreeMap<>();
61 // The hash code ({@link String#hashCode()}) of the configuration string
62 // Used to determine if a component has changed.
63 protected final int configHash;
64 protected final String channelConfigurationJson;
65 protected final C channelConfiguration;
67 protected boolean configSeen;
70 * Creates component based on generic configuration and component configuration type.
72 * @param componentConfiguration generic componentConfiguration with not parsed JSON config
73 * @param clazz target configuration type
75 public AbstractComponent(ComponentFactory.ComponentConfiguration componentConfiguration, Class<C> clazz) {
76 this.componentConfiguration = componentConfiguration;
78 this.channelConfigurationJson = componentConfiguration.getConfigJSON();
79 this.channelConfiguration = componentConfiguration.getConfig(clazz);
80 this.configHash = channelConfigurationJson.hashCode();
82 this.haID = componentConfiguration.getHaID();
84 String groupId = this.haID.getGroupId(channelConfiguration.getUniqueId());
86 this.channelGroupTypeUID = new ChannelGroupTypeUID(MqttBindingConstants.BINDING_ID, groupId);
87 this.channelGroupUID = new ChannelGroupUID(componentConfiguration.getThingUID(), groupId);
89 this.configSeen = false;
91 String availabilityTopic = this.channelConfiguration.getAvailabilityTopic();
92 if (availabilityTopic != null) {
93 String availabilityTemplate = this.channelConfiguration.getAvailabilityTemplate();
94 if (availabilityTemplate != null) {
95 availabilityTemplate = JINJA_PREFIX + availabilityTemplate;
97 componentConfiguration.getTracker().addAvailabilityTopic(availabilityTopic,
98 this.channelConfiguration.getPayloadAvailable(), this.channelConfiguration.getPayloadNotAvailable(),
99 availabilityTemplate, componentConfiguration.getTransformationServiceProvider());
103 protected ComponentChannel.Builder buildChannel(String channelID, Value valueState, String label,
104 ChannelStateUpdateListener channelStateUpdateListener) {
105 return new ComponentChannel.Builder(this, channelID, valueState, label, channelStateUpdateListener);
108 public void setConfigSeen() {
109 this.configSeen = true;
113 * Subscribes to all state channels of the component and adds all channels to the provided channel type provider.
115 * @param connection connection to the MQTT broker
116 * @param scheduler thing scheduler
117 * @param timeout channel subscription timeout
118 * @return A future that completes as soon as all subscriptions have been performed. Completes exceptionally on
121 public CompletableFuture<@Nullable Void> start(MqttBrokerConnection connection, ScheduledExecutorService scheduler,
123 return channels.values().stream().map(cChannel -> cChannel.start(connection, scheduler, timeout))
124 .collect(FutureCollector.allOf());
128 * Unsubscribes from all state channels of the component.
130 * @return A future that completes as soon as all subscriptions removals have been performed. Completes
131 * exceptionally on errors.
133 public CompletableFuture<@Nullable Void> stop() {
134 return channels.values().stream().map(ComponentChannel::stop).collect(FutureCollector.allOf());
138 * Add all channel types to the channel type provider.
140 * @param channelTypeProvider The channel type provider
142 public void addChannelTypes(MqttChannelTypeProvider channelTypeProvider) {
143 channelTypeProvider.setChannelGroupType(getGroupTypeUID(), getType());
144 channels.values().forEach(v -> v.addChannelTypes(channelTypeProvider));
148 * Removes all channels from the channel type provider.
149 * Call this if the corresponding Thing handler gets disposed.
151 * @param channelTypeProvider The channel type provider
153 public void removeChannelTypes(MqttChannelTypeProvider channelTypeProvider) {
154 channels.values().forEach(v -> v.removeChannelTypes(channelTypeProvider));
155 channelTypeProvider.removeChannelGroupType(getGroupTypeUID());
159 * Each HomeAssistant component corresponds to a Channel Group Type.
161 public ChannelGroupTypeUID getGroupTypeUID() {
162 return channelGroupTypeUID;
166 * The unique id of this component.
168 public ChannelGroupUID getGroupUID() {
169 return channelGroupUID;
173 * Component (Channel Group) name.
175 public String getName() {
176 return channelConfiguration.getName();
180 * Each component consists of multiple Channels.
182 public Map<String, ComponentChannel> getChannelMap() {
187 * Return a components channel. A HomeAssistant MQTT component consists of multiple functions
188 * and those are mapped to one or more channels. The channel IDs are constants within the
189 * derived Component, like the {@link Switch#SWITCH_CHANNEL_ID}.
191 * @param channelID The channel ID
192 * @return A components channel
194 public @Nullable ComponentChannel getChannel(String channelID) {
195 return channels.get(channelID);
199 * @return Returns the configuration hash value for easy comparison.
201 public int getConfigHash() {
206 * Return the channel group type.
208 public ChannelGroupType getType() {
209 final List<ChannelDefinition> channelDefinitions = channels.values().stream().map(ComponentChannel::type)
210 .collect(Collectors.toList());
211 return ChannelGroupTypeBuilder.instance(channelGroupTypeUID, getName())
212 .withChannelDefinitions(channelDefinitions).build();
216 * Resets all channel states to state UNDEF. Call this method after the connection
217 * to the MQTT broker got lost.
219 public void resetState() {
220 channels.values().forEach(ComponentChannel::resetState);
224 * Return the channel group definition for this component.
226 public ChannelGroupDefinition getGroupDefinition() {
227 return new ChannelGroupDefinition(channelGroupUID.getId(), getGroupTypeUID(), getName(), null);
230 public HaID getHaID() {
234 public String getChannelConfigurationJson() {
235 return channelConfigurationJson;
239 public TransformationServiceProvider getTransformationServiceProvider() {
240 return componentConfiguration.getTransformationServiceProvider();
243 public boolean isEnabledByDefault() {
244 return channelConfiguration.isEnabledByDefault();