]> git.basschouten.com Git - openhab-addons.git/blob
e1f3649debbf83e8eb96844ac0ce34f2f738c8aa
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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.discovery;
14
15 import java.nio.charset.StandardCharsets;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.Comparator;
20 import java.util.HashMap;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Objects;
24 import java.util.Set;
25 import java.util.TreeMap;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ScheduledFuture;
28 import java.util.concurrent.TimeUnit;
29 import java.util.function.Function;
30 import java.util.stream.Collector;
31 import java.util.stream.Collectors;
32 import java.util.stream.Stream;
33
34 import org.eclipse.jdt.annotation.NonNullByDefault;
35 import org.eclipse.jdt.annotation.Nullable;
36 import org.openhab.binding.mqtt.discovery.AbstractMQTTDiscovery;
37 import org.openhab.binding.mqtt.discovery.MQTTTopicDiscoveryService;
38 import org.openhab.binding.mqtt.generic.MqttChannelTypeProvider;
39 import org.openhab.binding.mqtt.homeassistant.generic.internal.MqttBindingConstants;
40 import org.openhab.binding.mqtt.homeassistant.internal.HaID;
41 import org.openhab.binding.mqtt.homeassistant.internal.HandlerConfiguration;
42 import org.openhab.binding.mqtt.homeassistant.internal.config.ChannelConfigurationTypeAdapterFactory;
43 import org.openhab.binding.mqtt.homeassistant.internal.config.dto.AbstractChannelConfiguration;
44 import org.openhab.binding.mqtt.homeassistant.internal.exception.ConfigurationException;
45 import org.openhab.core.config.discovery.DiscoveryResult;
46 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
47 import org.openhab.core.config.discovery.DiscoveryService;
48 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
49 import org.openhab.core.thing.ThingTypeUID;
50 import org.openhab.core.thing.ThingUID;
51 import org.openhab.core.thing.type.ThingType;
52 import org.osgi.service.component.annotations.Component;
53 import org.osgi.service.component.annotations.Reference;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 import com.google.gson.Gson;
58 import com.google.gson.GsonBuilder;
59
60 /**
61  * The {@link HomeAssistantDiscovery} is responsible for discovering device nodes that follow the
62  * Home Assistant MQTT discovery convention (https://www.home-assistant.io/docs/mqtt/discovery/).
63  *
64  * @author David Graeff - Initial contribution
65  */
66 @Component(service = DiscoveryService.class, configurationPid = "discovery.mqttha")
67 @NonNullByDefault
68 public class HomeAssistantDiscovery extends AbstractMQTTDiscovery {
69     private final Logger logger = LoggerFactory.getLogger(HomeAssistantDiscovery.class);
70     protected final Map<String, Set<HaID>> componentsPerThingID = new TreeMap<>();
71     protected final Map<String, ThingUID> thingIDPerTopic = new TreeMap<>();
72     protected final Map<String, DiscoveryResult> results = new ConcurrentHashMap<>();
73
74     private @Nullable ScheduledFuture<?> future;
75     private final Gson gson;
76
77     public static final Map<String, String> HA_COMP_TO_NAME = new TreeMap<>();
78     {
79         HA_COMP_TO_NAME.put("alarm_control_panel", "Alarm Control Panel");
80         HA_COMP_TO_NAME.put("binary_sensor", "Sensor");
81         HA_COMP_TO_NAME.put("camera", "Camera");
82         HA_COMP_TO_NAME.put("cover", "Blind");
83         HA_COMP_TO_NAME.put("fan", "Fan");
84         HA_COMP_TO_NAME.put("climate", "Climate Control");
85         HA_COMP_TO_NAME.put("light", "Light");
86         HA_COMP_TO_NAME.put("lock", "Lock");
87         HA_COMP_TO_NAME.put("sensor", "Sensor");
88         HA_COMP_TO_NAME.put("switch", "Switch");
89     }
90
91     static final String BASE_TOPIC = "homeassistant";
92
93     @NonNullByDefault({})
94     protected MqttChannelTypeProvider typeProvider;
95
96     @NonNullByDefault({})
97     protected MQTTTopicDiscoveryService mqttTopicDiscovery;
98
99     public HomeAssistantDiscovery() {
100         super(null, 3, true, BASE_TOPIC + "/#");
101         this.gson = new GsonBuilder().registerTypeAdapterFactory(new ChannelConfigurationTypeAdapterFactory()).create();
102     }
103
104     @Reference
105     public void setMQTTTopicDiscoveryService(MQTTTopicDiscoveryService service) {
106         mqttTopicDiscovery = service;
107     }
108
109     public void unsetMQTTTopicDiscoveryService(@Nullable MQTTTopicDiscoveryService service) {
110         mqttTopicDiscovery.unsubscribe(this);
111         this.mqttTopicDiscovery = null;
112     }
113
114     @Override
115     protected MQTTTopicDiscoveryService getDiscoveryService() {
116         return mqttTopicDiscovery;
117     }
118
119     @Reference
120     protected void setTypeProvider(MqttChannelTypeProvider provider) {
121         this.typeProvider = provider;
122     }
123
124     protected void unsetTypeProvider(MqttChannelTypeProvider provider) {
125         this.typeProvider = null;
126     }
127
128     @Override
129     public Set<ThingTypeUID> getSupportedThingTypes() {
130         return typeProvider.getThingTypeUIDs();
131     }
132
133     /**
134      * Summarize components such as {Switch, Switch, Sensor} into string "Sensor, 2x Switch"
135      *
136      * @param componentNames stream of component names
137      * @return summary string of component names and their counts
138      */
139     static String getComponentNamesSummary(Stream<String> componentNames) {
140         StringBuilder summary = new StringBuilder();
141         Collector<String, ?, Long> countingCollector = Collectors.counting();
142         Map<String, Long> componentCounts = componentNames
143                 .collect(Collectors.groupingBy(Function.identity(), countingCollector));
144         componentCounts.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(entry -> {
145             String componentName = entry.getKey();
146             long count = entry.getValue();
147             if (summary.length() > 0) {
148                 // not the first entry, so let's add the separating comma
149                 summary.append(", ");
150             }
151             if (count > 1) {
152                 summary.append(count);
153                 summary.append("x ");
154             }
155             summary.append(componentName);
156         });
157         return summary.toString();
158     }
159
160     @Override
161     public void receivedMessage(ThingUID connectionBridge, MqttBrokerConnection connection, String topic,
162             byte[] payload) {
163         resetTimeout();
164
165         // For HomeAssistant we need to subscribe to a wildcard topic, because topics can either be:
166         // homeassistant/<component>/<node_id>/<object_id>/config OR
167         // homeassistant/<component>/<object_id>/config.
168         // We check for the last part to filter all non-config topics out.
169         if (!topic.endsWith("/config")) {
170             return;
171         }
172
173         // Reset the found-component timer.
174         // We will collect components for the thing label description for another 2 seconds.
175         final ScheduledFuture<?> future = this.future;
176         if (future != null) {
177             future.cancel(false);
178         }
179         this.future = scheduler.schedule(this::publishResults, 2, TimeUnit.SECONDS);
180
181         // We will of course find multiple of the same unique Thing IDs, for each different component another one.
182         // Therefore the components are assembled into a list and given to the DiscoveryResult label for the user to
183         // easily recognize object capabilities.
184         HaID haID = new HaID(topic);
185
186         try {
187             AbstractChannelConfiguration config = AbstractChannelConfiguration
188                     .fromString(new String(payload, StandardCharsets.UTF_8), gson);
189
190             final String thingID = config.getThingId(haID.objectID);
191
192             final ThingTypeUID typeID = new ThingTypeUID(MqttBindingConstants.BINDING_ID,
193                     MqttBindingConstants.HOMEASSISTANT_MQTT_THING.getId() + "_" + thingID);
194
195             final ThingUID thingUID = new ThingUID(typeID, connectionBridge, thingID);
196
197             thingIDPerTopic.put(topic, thingUID);
198
199             // We need to keep track of already found component topics for a specific thing
200             final List<HaID> components;
201             {
202                 Set<HaID> componentsUnordered = componentsPerThingID.computeIfAbsent(thingID,
203                         key -> ConcurrentHashMap.newKeySet());
204
205                 // Invariant. For compiler, computeIfAbsent above returns always
206                 // non-null
207                 Objects.requireNonNull(componentsUnordered);
208                 componentsUnordered.add(haID);
209
210                 components = componentsUnordered.stream().collect(Collectors.toList());
211                 // We sort the components for consistent jsondb serialization order of 'topics' thing property
212                 // Sorting key is HaID::toString, i.e. using the full topic string
213                 components.sort(Comparator.comparing(HaID::toString));
214             }
215
216             final String componentNames = getComponentNamesSummary(
217                     components.stream().map(id -> id.component).map(c -> HA_COMP_TO_NAME.getOrDefault(c, c)));
218
219             final List<String> topics = components.stream().map(HaID::toShortTopic).collect(Collectors.toList());
220
221             Map<String, Object> properties = new HashMap<>();
222             HandlerConfiguration handlerConfig = new HandlerConfiguration(haID.baseTopic, topics);
223             properties = handlerConfig.appendToProperties(properties);
224             properties = config.appendToProperties(properties);
225             properties.put("deviceId", thingID);
226
227             // Because we need the new properties map with the updated "components" list
228             results.put(thingUID.getAsString(),
229                     DiscoveryResultBuilder.create(thingUID).withProperties(properties)
230                             .withRepresentationProperty("deviceId").withBridge(connectionBridge)
231                             .withLabel(config.getThingName() + " (" + componentNames + ")").build());
232         } catch (ConfigurationException e) {
233             logger.warn("HomeAssistant discover error: invalid configuration of thing {} component {}: {}",
234                     haID.objectID, haID.component, e.getMessage());
235         } catch (Exception e) {
236             logger.warn("HomeAssistant discover error: {}", e.getMessage());
237         }
238     }
239
240     protected void publishResults() {
241         Collection<DiscoveryResult> localResults;
242
243         localResults = new ArrayList<>(results.values());
244         results.clear();
245         componentsPerThingID.clear();
246         for (DiscoveryResult result : localResults) {
247             final ThingTypeUID typeID = result.getThingTypeUID();
248             ThingType type = typeProvider.derive(typeID, MqttBindingConstants.HOMEASSISTANT_MQTT_THING).build();
249             typeProvider.setThingTypeIfAbsent(typeID, type);
250
251             thingDiscovered(result);
252         }
253     }
254
255     @Override
256     public void topicVanished(ThingUID connectionBridge, MqttBrokerConnection connection, String topic) {
257         if (!topic.endsWith("/config")) {
258             return;
259         }
260         if (thingIDPerTopic.containsKey(topic)) {
261             ThingUID thingUID = thingIDPerTopic.remove(topic);
262             if (thingUID != null) {
263                 final String thingID = thingUID.getId();
264
265                 HaID haID = new HaID(topic);
266
267                 Set<HaID> components = componentsPerThingID.getOrDefault(thingID, Collections.emptySet());
268                 components.remove(haID);
269                 if (components.isEmpty()) {
270                     thingRemoved(thingUID);
271                 }
272             }
273         }
274     }
275 }