2 * Copyright (c) 2010-2022 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.netatmo.internal.discovery;
15 import static java.util.Comparator.*;
17 import java.util.HashMap;
19 import java.util.stream.Collectors;
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.openhab.binding.netatmo.internal.api.AircareApi;
24 import org.openhab.binding.netatmo.internal.api.HomeApi;
25 import org.openhab.binding.netatmo.internal.api.ListBodyResponse;
26 import org.openhab.binding.netatmo.internal.api.NetatmoException;
27 import org.openhab.binding.netatmo.internal.api.WeatherApi;
28 import org.openhab.binding.netatmo.internal.api.data.ModuleType;
29 import org.openhab.binding.netatmo.internal.api.data.NetatmoConstants.FeatureArea;
30 import org.openhab.binding.netatmo.internal.api.dto.HomeDataModule;
31 import org.openhab.binding.netatmo.internal.api.dto.NAMain;
32 import org.openhab.binding.netatmo.internal.api.dto.NAModule;
33 import org.openhab.binding.netatmo.internal.config.NAThingConfiguration;
34 import org.openhab.binding.netatmo.internal.handler.ApiBridgeHandler;
35 import org.openhab.core.config.discovery.AbstractDiscoveryService;
36 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
37 import org.openhab.core.config.discovery.DiscoveryService;
38 import org.openhab.core.thing.ThingTypeUID;
39 import org.openhab.core.thing.ThingUID;
40 import org.openhab.core.thing.binding.ThingHandler;
41 import org.openhab.core.thing.binding.ThingHandlerService;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
46 * The {@link NetatmoDiscoveryService} searches for available Netatmo things
48 * @author Gaƫl L'hopital - Initial contribution
52 public class NetatmoDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService, DiscoveryService {
53 private static final int DISCOVER_TIMEOUT_SECONDS = 3;
54 private final Logger logger = LoggerFactory.getLogger(NetatmoDiscoveryService.class);
56 private @Nullable ApiBridgeHandler handler;
58 public NetatmoDiscoveryService() {
59 super(ModuleType.AS_SET.stream().filter(mt -> !mt.apiName.isBlank()).map(mt -> mt.thingTypeUID)
60 .collect(Collectors.toSet()), DISCOVER_TIMEOUT_SECONDS);
64 public void startScan() {
65 ApiBridgeHandler localHandler = handler;
66 if (localHandler != null) {
67 ThingUID accountUID = localHandler.getThing().getUID();
69 AircareApi airCareApi = localHandler.getRestManager(AircareApi.class);
70 if (airCareApi != null) { // Search Healthy Home Coaches
71 ListBodyResponse<NAMain> body = airCareApi.getHomeCoachData(null).getBody();
73 body.getElements().stream().forEach(homeCoach -> createThing(homeCoach, accountUID));
76 WeatherApi weatherApi = localHandler.getRestManager(WeatherApi.class);
77 if (weatherApi != null) { // Search owned or favorite stations
78 weatherApi.getFavoriteAndGuestStationsData().stream().forEach(station -> {
79 if (!station.isReadOnly() || localHandler.getReadFriends()) {
80 ThingUID stationUID = createThing(station, accountUID);
81 station.getModules().values().stream().forEach(module -> createThing(module, stationUID));
85 HomeApi homeApi = localHandler.getRestManager(HomeApi.class);
86 if (homeApi != null) { // Search those depending from a home that has modules + not only weather modules
87 homeApi.getHomesData(null, null).stream()
88 .filter(h -> !(h.getFeatures().isEmpty()
89 || h.getFeatures().contains(FeatureArea.WEATHER) && h.getFeatures().size() == 1))
91 ThingUID homeUID = createThing(home, accountUID);
93 home.getKnownPersons().forEach(person -> createThing(person, homeUID));
95 Map<String, ThingUID> bridgesUids = new HashMap<>();
97 home.getRooms().values().stream().forEach(room -> {
98 room.getModuleIds().stream().map(id -> home.getModules().get(id))
99 .map(m -> m != null ? m.getType().feature : FeatureArea.NONE)
100 .filter(f -> FeatureArea.ENERGY.equals(f)).findAny()
101 .ifPresent(f -> bridgesUids.put(room.getId(), createThing(room, homeUID)));
104 // Creating modules that have no bridge first, avoiding weather station itself
105 home.getModules().values().stream()
106 .filter(module -> module.getType().feature != FeatureArea.WEATHER)
107 .sorted(comparing(HomeDataModule::getBridge, nullsFirst(naturalOrder())))
109 String bridgeId = module.getBridge();
110 if (bridgeId == null) {
111 bridgesUids.put(module.getId(), createThing(module, homeUID));
113 createThing(module, bridgesUids.getOrDefault(bridgeId, homeUID));
118 } catch (NetatmoException e) {
119 logger.warn("Error during discovery process : {}", e.getMessage());
124 private ThingUID findThingUID(ModuleType thingType, String thingId, ThingUID bridgeUID) {
125 ThingTypeUID thingTypeUID = thingType.thingTypeUID;
126 return getSupportedThingTypes().stream().filter(supported -> supported.equals(thingTypeUID)).findFirst()
127 .map(supported -> new ThingUID(supported, bridgeUID, thingId.replaceAll("[^a-zA-Z0-9_]", "")))
128 .orElseThrow(() -> new IllegalArgumentException("Unsupported device type discovered : " + thingType));
131 private ThingUID createThing(NAModule module, ThingUID bridgeUID) {
132 ThingUID moduleUID = findThingUID(module.getType(), module.getId(), bridgeUID);
133 DiscoveryResultBuilder resultBuilder = DiscoveryResultBuilder.create(moduleUID)
134 .withProperty(NAThingConfiguration.ID, module.getId())
135 .withRepresentationProperty(NAThingConfiguration.ID)
136 .withLabel(module.getName() != null ? module.getName() : module.getId()).withBridge(bridgeUID);
137 thingDiscovered(resultBuilder.build());
142 public void setThingHandler(ThingHandler handler) {
143 if (handler instanceof ApiBridgeHandler) {
144 this.handler = (ApiBridgeHandler) handler;
149 public @Nullable ThingHandler getThingHandler() {
154 public void deactivate() {