]> git.basschouten.com Git - openhab-addons.git/blob
8cc05429ec1b652f440d61f73ddecd43bcb53fd1
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.generic.internal.handler;
14
15 import java.util.ArrayList;
16 import java.util.HashMap;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.Optional;
20 import java.util.concurrent.CompletableFuture;
21 import java.util.stream.Collectors;
22 import java.util.stream.Stream;
23
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;
47
48 /**
49  * This handler manages manual created Things with manually added channels to link to MQTT topics.
50  *
51  * @author David Graeff - Initial contribution
52  */
53 @NonNullByDefault
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;
59
60     /**
61      * Creates a new Thing handler for generic MQTT channels.
62      *
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
67      */
68     public GenericMQTTThingHandler(Thing thing, MqttChannelStateDescriptionProvider stateDescProvider,
69             TransformationServiceProvider transformationServiceProvider, int subscribeTimeout) {
70         super(thing, subscribeTimeout);
71         this.stateDescProvider = stateDescProvider;
72         this.transformationServiceProvider = transformationServiceProvider;
73     }
74
75     @Override
76     public @Nullable ChannelState getChannelState(ChannelUID channelUID) {
77         return channelStateByChannelUID.get(channelUID);
78     }
79
80     /**
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.
83      *
84      * @param connection A started broker connection
85      */
86     @Override
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);
90     }
91
92     @Override
93     protected void stop() {
94         channelStateByChannelUID.values().forEach(c -> c.getCache().resetState());
95         super.stop();
96     }
97
98     @Override
99     public void dispose() {
100         // Remove all state descriptions of this handler
101         channelStateByChannelUID.forEach((uid, state) -> stateDescProvider.remove(uid));
102         super.dispose();
103         // there is a design flaw, we can't clean up our stuff because it is needed by the super-class on disposal for
104         // unsubscribing
105         channelStateByChannelUID.clear();
106     }
107
108     @Override
109     public CompletableFuture<Void> unsubscribeAll() {
110         return CompletableFuture.allOf(
111                 channelStateByChannelUID.values().stream().map(ChannelState::stop).toArray(CompletableFuture[]::new));
112     }
113
114     /**
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.
117      *
118      * @param channelConfig The channel configuration that contains MQTT state and command topic and multiple other
119      *            configurations.
120      * @param channelUID The channel UID
121      * @param valueState The channel value state
122      * @return
123      */
124     protected ChannelState createChannelState(ChannelConfig channelConfig, ChannelUID channelUID, Value valueState) {
125         ChannelState state = new ChannelState(channelConfig, channelUID, valueState, this);
126         String[] transformations;
127
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));
133
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));
139
140         return state;
141     }
142
143     @Override
144     public void initialize() {
145         GenericThingConfiguration config = getConfigAs(GenericThingConfiguration.class);
146
147         String availabilityTopic = config.availabilityTopic;
148
149         if (availabilityTopic != null) {
150             addAvailabilityTopic(availabilityTopic, config.payloadAvailable, config.payloadNotAvailable);
151         } else {
152             clearAllAvailabilityTopics();
153         }
154
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());
160                 continue;
161             }
162             final ChannelConfig channelConfig = channel.getConfiguration().as(ChannelConfig.class);
163             try {
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);
171                 }
172             } catch (IllegalArgumentException e) {
173                 logger.warn("Channel configuration error", e);
174                 configErrors.add(channel.getUID());
175             }
176         }
177
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(",")));
183             return;
184         }
185         super.initialize();
186     }
187
188     @Override
189     protected void updateThingStatus(boolean messageReceived, Optional<Boolean> availibilityTopicsSeen) {
190         if (availibilityTopicsSeen.orElse(true)) {
191             updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
192         } else {
193             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE);
194         }
195     }
196 }