]> git.basschouten.com Git - openhab-addons.git/blob
d4ab2251cbc75021f258e05d307a4c22e6be7275
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.mqtt.homeassistant.internal.component;
14
15 import java.util.List;
16 import java.util.Map;
17 import java.util.TreeMap;
18 import java.util.concurrent.CompletableFuture;
19 import java.util.concurrent.ScheduledExecutorService;
20 import java.util.stream.Collectors;
21
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;
41
42 /**
43  * A HomeAssistant component is comparable to a channel group.
44  * It has a name and consists of multiple channels.
45  *
46  * @author David Graeff - Initial contribution
47  * @param <C> Config class derived from {@link AbstractChannelConfiguration}
48  */
49 @NonNullByDefault
50 public abstract class AbstractComponent<C extends AbstractChannelConfiguration> {
51     private static final String JINJA_PREFIX = "JINJA:";
52
53     // Component location fields
54     private final ComponentConfiguration componentConfiguration;
55     protected final ChannelGroupTypeUID channelGroupTypeUID;
56     protected final ChannelGroupUID channelGroupUID;
57     protected final HaID haID;
58
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;
66
67     protected boolean configSeen;
68
69     /**
70      * Creates component based on generic configuration and component configuration type.
71      *
72      * @param componentConfiguration generic componentConfiguration with not parsed JSON config
73      * @param clazz target configuration type
74      */
75     public AbstractComponent(ComponentFactory.ComponentConfiguration componentConfiguration, Class<C> clazz) {
76         this.componentConfiguration = componentConfiguration;
77
78         this.channelConfigurationJson = componentConfiguration.getConfigJSON();
79         this.channelConfiguration = componentConfiguration.getConfig(clazz);
80         this.configHash = channelConfigurationJson.hashCode();
81
82         this.haID = componentConfiguration.getHaID();
83
84         String groupId = this.haID.getGroupId(channelConfiguration.getUniqueId());
85
86         this.channelGroupTypeUID = new ChannelGroupTypeUID(MqttBindingConstants.BINDING_ID, groupId);
87         this.channelGroupUID = new ChannelGroupUID(componentConfiguration.getThingUID(), groupId);
88
89         this.configSeen = false;
90
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;
96             }
97             componentConfiguration.getTracker().addAvailabilityTopic(availabilityTopic,
98                     this.channelConfiguration.getPayloadAvailable(), this.channelConfiguration.getPayloadNotAvailable(),
99                     availabilityTemplate, componentConfiguration.getTransformationServiceProvider());
100         }
101     }
102
103     protected ComponentChannel.Builder buildChannel(String channelID, Value valueState, String label,
104             ChannelStateUpdateListener channelStateUpdateListener) {
105         return new ComponentChannel.Builder(this, channelID, valueState, label, channelStateUpdateListener);
106     }
107
108     public void setConfigSeen() {
109         this.configSeen = true;
110     }
111
112     /**
113      * Subscribes to all state channels of the component and adds all channels to the provided channel type provider.
114      *
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
119      *         errors.
120      */
121     public CompletableFuture<@Nullable Void> start(MqttBrokerConnection connection, ScheduledExecutorService scheduler,
122             int timeout) {
123         return channels.values().stream().map(cChannel -> cChannel.start(connection, scheduler, timeout))
124                 .collect(FutureCollector.allOf());
125     }
126
127     /**
128      * Unsubscribes from all state channels of the component.
129      *
130      * @return A future that completes as soon as all subscriptions removals have been performed. Completes
131      *         exceptionally on errors.
132      */
133     public CompletableFuture<@Nullable Void> stop() {
134         return channels.values().stream().map(ComponentChannel::stop).collect(FutureCollector.allOf());
135     }
136
137     /**
138      * Add all channel types to the channel type provider.
139      *
140      * @param channelTypeProvider The channel type provider
141      */
142     public void addChannelTypes(MqttChannelTypeProvider channelTypeProvider) {
143         channelTypeProvider.setChannelGroupType(getGroupTypeUID(), getType());
144         channels.values().forEach(v -> v.addChannelTypes(channelTypeProvider));
145     }
146
147     /**
148      * Removes all channels from the channel type provider.
149      * Call this if the corresponding Thing handler gets disposed.
150      *
151      * @param channelTypeProvider The channel type provider
152      */
153     public void removeChannelTypes(MqttChannelTypeProvider channelTypeProvider) {
154         channels.values().forEach(v -> v.removeChannelTypes(channelTypeProvider));
155         channelTypeProvider.removeChannelGroupType(getGroupTypeUID());
156     }
157
158     /**
159      * Each HomeAssistant component corresponds to a Channel Group Type.
160      */
161     public ChannelGroupTypeUID getGroupTypeUID() {
162         return channelGroupTypeUID;
163     }
164
165     /**
166      * The unique id of this component.
167      */
168     public ChannelGroupUID getGroupUID() {
169         return channelGroupUID;
170     }
171
172     /**
173      * Component (Channel Group) name.
174      */
175     public String getName() {
176         return channelConfiguration.getName();
177     }
178
179     /**
180      * Each component consists of multiple Channels.
181      */
182     public Map<String, ComponentChannel> getChannelMap() {
183         return channels;
184     }
185
186     /**
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}.
190      *
191      * @param channelID The channel ID
192      * @return A components channel
193      */
194     public @Nullable ComponentChannel getChannel(String channelID) {
195         return channels.get(channelID);
196     }
197
198     /**
199      * @return Returns the configuration hash value for easy comparison.
200      */
201     public int getConfigHash() {
202         return configHash;
203     }
204
205     /**
206      * Return the channel group type.
207      */
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();
213     }
214
215     /**
216      * Resets all channel states to state UNDEF. Call this method after the connection
217      * to the MQTT broker got lost.
218      */
219     public void resetState() {
220         channels.values().forEach(ComponentChannel::resetState);
221     }
222
223     /**
224      * Return the channel group definition for this component.
225      */
226     public ChannelGroupDefinition getGroupDefinition() {
227         return new ChannelGroupDefinition(channelGroupUID.getId(), getGroupTypeUID(), getName(), null);
228     }
229
230     public HaID getHaID() {
231         return haID;
232     }
233
234     public String getChannelConfigurationJson() {
235         return channelConfigurationJson;
236     }
237
238     @Nullable
239     public TransformationServiceProvider getTransformationServiceProvider() {
240         return componentConfiguration.getTransformationServiceProvider();
241     }
242
243     public boolean isEnabledByDefault() {
244         return channelConfiguration.isEnabledByDefault();
245     }
246 }