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 return channelStateByChannelUID.values().stream().map(c -> c.start(connection, scheduler, 0))
89 .collect(FutureCollector.allOf()).thenRun(this::calculateThingStatus);
93 protected void stop() {
94 channelStateByChannelUID.values().forEach(c -> c.getCache().resetState());
99 public void dispose() {
100 // Remove all state descriptions of this handler
101 channelStateByChannelUID.forEach((uid, state) -> stateDescProvider.remove(uid));
103 // there is a design flaw, we can't clean up our stuff because it is needed by the super-class on disposal for
105 channelStateByChannelUID.clear();
109 public CompletableFuture<Void> unsubscribeAll() {
110 return CompletableFuture.allOf(
111 channelStateByChannelUID.values().stream().map(ChannelState::stop).toArray(CompletableFuture[]::new));
115 * For every Thing channel there exists a corresponding {@link ChannelState}. It consists of the MQTT state
116 * and MQTT command topic, the ChannelUID and a value state.
118 * @param channelConfig The channel configuration that contains MQTT state and command topic and multiple other
120 * @param channelUID The channel UID
121 * @param valueState The channel value state
124 protected ChannelState createChannelState(ChannelConfig channelConfig, ChannelUID channelUID, Value valueState) {
125 ChannelState state = new ChannelState(channelConfig, channelUID, valueState, this);
126 String[] transformations;
128 // Incoming value transformations
129 transformations = channelConfig.transformationPattern.split("∩");
130 Stream.of(transformations).filter(StringUtils::isNotBlank)
131 .map(t -> new ChannelStateTransformation(t, transformationServiceProvider))
132 .forEach(t -> state.addTransformation(t));
134 // Outgoing value transformations
135 transformations = channelConfig.transformationPatternOut.split("∩");
136 Stream.of(transformations).filter(StringUtils::isNotBlank)
137 .map(t -> new ChannelStateTransformation(t, transformationServiceProvider))
138 .forEach(t -> state.addTransformationOut(t));
144 public void initialize() {
145 GenericThingConfiguration config = getConfigAs(GenericThingConfiguration.class);
147 String availabilityTopic = config.availabilityTopic;
149 if (availabilityTopic != null) {
150 addAvailabilityTopic(availabilityTopic, config.payloadAvailable, config.payloadNotAvailable);
152 clearAllAvailabilityTopics();
155 List<ChannelUID> configErrors = new ArrayList<>();
156 for (Channel channel : thing.getChannels()) {
157 final ChannelTypeUID channelTypeUID = channel.getChannelTypeUID();
158 if (channelTypeUID == null) {
159 logger.warn("Channel {} has no type", channel.getLabel());
162 final ChannelConfig channelConfig = channel.getConfiguration().as(ChannelConfig.class);
164 Value value = ValueFactory.createValueState(channelConfig, channelTypeUID.getId());
165 ChannelState channelState = createChannelState(channelConfig, channel.getUID(), value);
166 channelStateByChannelUID.put(channel.getUID(), channelState);
167 StateDescription description = value.createStateDescription(channelConfig.commandTopic.isBlank())
168 .build().toStateDescription();
169 if (description != null) {
170 stateDescProvider.setDescription(channel.getUID(), description);
172 } catch (IllegalArgumentException e) {
173 logger.warn("Channel configuration error", e);
174 configErrors.add(channel.getUID());
178 // If some channels could not start up, put the entire thing offline and display the channels
179 // in question to the user.
180 if (!configErrors.isEmpty()) {
181 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Remove and recreate: "
182 + configErrors.stream().map(ChannelUID::getAsString).collect(Collectors.joining(",")));
189 protected void updateThingStatus(boolean messageReceived, Optional<Boolean> availibilityTopicsSeen) {
190 if (availibilityTopicsSeen.orElse(true)) {
191 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
193 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE);