2 * Copyright (c) 2010-2021 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.generic.internal.handler;
15 import java.util.ArrayList;
16 import java.util.HashMap;
17 import java.util.List;
19 import java.util.Optional;
20 import java.util.concurrent.CompletableFuture;
21 import java.util.stream.Collectors;
22 import java.util.stream.Stream;
24 import org.apache.commons.lang3.StringUtils;
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.openhab.binding.mqtt.generic.AbstractMQTTThingHandler;
28 import org.openhab.binding.mqtt.generic.ChannelConfig;
29 import org.openhab.binding.mqtt.generic.ChannelState;
30 import org.openhab.binding.mqtt.generic.ChannelStateTransformation;
31 import org.openhab.binding.mqtt.generic.ChannelStateUpdateListener;
32 import org.openhab.binding.mqtt.generic.MqttChannelStateDescriptionProvider;
33 import org.openhab.binding.mqtt.generic.TransformationServiceProvider;
34 import org.openhab.binding.mqtt.generic.utils.FutureCollector;
35 import org.openhab.binding.mqtt.generic.values.Value;
36 import org.openhab.binding.mqtt.generic.values.ValueFactory;
37 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
38 import org.openhab.core.thing.Channel;
39 import org.openhab.core.thing.ChannelUID;
40 import org.openhab.core.thing.Thing;
41 import org.openhab.core.thing.ThingStatus;
42 import org.openhab.core.thing.ThingStatusDetail;
43 import org.openhab.core.thing.type.ChannelTypeUID;
44 import org.openhab.core.types.StateDescription;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
49 * This handler manages manual created Things with manually added channels to link to MQTT topics.
51 * @author David Graeff - Initial contribution
54 public class GenericMQTTThingHandler extends AbstractMQTTThingHandler implements ChannelStateUpdateListener {
55 private final Logger logger = LoggerFactory.getLogger(GenericMQTTThingHandler.class);
56 final Map<ChannelUID, ChannelState> channelStateByChannelUID = new HashMap<>();
57 protected final MqttChannelStateDescriptionProvider stateDescProvider;
58 protected final TransformationServiceProvider transformationServiceProvider;
61 * Creates a new Thing handler for generic MQTT channels.
63 * @param thing The thing of this handler
64 * @param stateDescProvider A channel state provider
65 * @param transformationServiceProvider The transformation service provider
66 * @param subscribeTimeout The subscribe timeout
68 public GenericMQTTThingHandler(Thing thing, MqttChannelStateDescriptionProvider stateDescProvider,
69 TransformationServiceProvider transformationServiceProvider, int subscribeTimeout) {
70 super(thing, subscribeTimeout);
71 this.stateDescProvider = stateDescProvider;
72 this.transformationServiceProvider = transformationServiceProvider;
76 public @Nullable ChannelState getChannelState(ChannelUID channelUID) {
77 return channelStateByChannelUID.get(channelUID);
81 * Subscribe on all channel static topics on all {@link ChannelState}s.
82 * If subscribing on all channels worked, the thing is put ONLINE, else OFFLINE.
84 * @param connection A started broker connection
87 protected CompletableFuture<@Nullable Void> start(MqttBrokerConnection connection) {
88 // availability topics are also started asynchronously, so no problem here
89 clearAllAvailabilityTopics();
90 initializeAvailabilityTopicsFromConfig();
91 return channelStateByChannelUID.values().stream().map(c -> c.start(connection, scheduler, 0))
92 .collect(FutureCollector.allOf()).thenRun(this::calculateThingStatus);
96 protected void stop() {
97 channelStateByChannelUID.values().forEach(c -> c.getCache().resetState());
102 public void dispose() {
103 // Remove all state descriptions of this handler
104 channelStateByChannelUID.forEach((uid, state) -> stateDescProvider.remove(uid));
106 // there is a design flaw, we can't clean up our stuff because it is needed by the super-class on disposal for
108 channelStateByChannelUID.clear();
112 public CompletableFuture<Void> unsubscribeAll() {
113 return CompletableFuture.allOf(
114 channelStateByChannelUID.values().stream().map(ChannelState::stop).toArray(CompletableFuture[]::new));
118 * For every Thing channel there exists a corresponding {@link ChannelState}. It consists of the MQTT state
119 * and MQTT command topic, the ChannelUID and a value state.
121 * @param channelConfig The channel configuration that contains MQTT state and command topic and multiple other
123 * @param channelUID The channel UID
124 * @param valueState The channel value state
127 protected ChannelState createChannelState(ChannelConfig channelConfig, ChannelUID channelUID, Value valueState) {
128 ChannelState state = new ChannelState(channelConfig, channelUID, valueState, this);
129 String[] transformations;
131 // Incoming value transformations
132 transformations = channelConfig.transformationPattern.split("∩");
133 Stream.of(transformations).filter(StringUtils::isNotBlank)
134 .map(t -> new ChannelStateTransformation(t, transformationServiceProvider))
135 .forEach(t -> state.addTransformation(t));
137 // Outgoing value transformations
138 transformations = channelConfig.transformationPatternOut.split("∩");
139 Stream.of(transformations).filter(StringUtils::isNotBlank)
140 .map(t -> new ChannelStateTransformation(t, transformationServiceProvider))
141 .forEach(t -> state.addTransformationOut(t));
147 public void initialize() {
148 initializeAvailabilityTopicsFromConfig();
150 List<ChannelUID> configErrors = new ArrayList<>();
151 for (Channel channel : thing.getChannels()) {
152 final ChannelTypeUID channelTypeUID = channel.getChannelTypeUID();
153 if (channelTypeUID == null) {
154 logger.warn("Channel {} has no type", channel.getLabel());
157 final ChannelConfig channelConfig = channel.getConfiguration().as(ChannelConfig.class);
159 Value value = ValueFactory.createValueState(channelConfig, channelTypeUID.getId());
160 ChannelState channelState = createChannelState(channelConfig, channel.getUID(), value);
161 channelStateByChannelUID.put(channel.getUID(), channelState);
162 StateDescription description = value.createStateDescription(channelConfig.commandTopic.isBlank())
163 .build().toStateDescription();
164 if (description != null) {
165 stateDescProvider.setDescription(channel.getUID(), description);
167 } catch (IllegalArgumentException e) {
168 logger.warn("Channel configuration error", e);
169 configErrors.add(channel.getUID());
173 // If some channels could not start up, put the entire thing offline and display the channels
174 // in question to the user.
175 if (!configErrors.isEmpty()) {
176 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Remove and recreate: "
177 + configErrors.stream().map(ChannelUID::getAsString).collect(Collectors.joining(",")));
184 protected void updateThingStatus(boolean messageReceived, Optional<Boolean> availibilityTopicsSeen) {
185 if (availibilityTopicsSeen.orElse(true)) {
186 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
188 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE);
192 private void initializeAvailabilityTopicsFromConfig() {
193 GenericThingConfiguration config = getConfigAs(GenericThingConfiguration.class);
195 String availabilityTopic = config.availabilityTopic;
197 if (availabilityTopic != null) {
198 addAvailabilityTopic(availabilityTopic, config.payloadAvailable, config.payloadNotAvailable);
200 clearAllAvailabilityTopics();