]> git.basschouten.com Git - openhab-addons.git/blob
b76c426c1c004829183479e8215c6339157e7ac3
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.netatmo.internal.discovery;
14
15 import static java.util.Comparator.*;
16
17 import java.util.HashMap;
18 import java.util.Map;
19 import java.util.stream.Collectors;
20
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;
44
45 /**
46  * The {@link NetatmoDiscoveryService} searches for available Netatmo things
47  *
48  * @author GaĆ«l L'hopital - Initial contribution
49  *
50  */
51 @NonNullByDefault
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);
55
56     private @Nullable ApiBridgeHandler handler;
57
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);
61     }
62
63     @Override
64     public void startScan() {
65         ApiBridgeHandler localHandler = handler;
66         if (localHandler != null) {
67             ThingUID accountUID = localHandler.getThing().getUID();
68             try {
69                 AircareApi airCareApi = localHandler.getRestManager(AircareApi.class);
70                 if (airCareApi != null) { // Search Healthy Home Coaches
71                     ListBodyResponse<NAMain> body = airCareApi.getHomeCoachData(null).getBody();
72                     if (body != null) {
73                         body.getElements().stream().forEach(homeCoach -> createThing(homeCoach, accountUID));
74                     }
75                 }
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));
82                         }
83                     });
84                 }
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))
90                             .forEach(home -> {
91                                 ThingUID homeUID = createThing(home, accountUID);
92
93                                 home.getKnownPersons().forEach(person -> createThing(person, homeUID));
94
95                                 Map<String, ThingUID> bridgesUids = new HashMap<>();
96
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)));
102                                 });
103
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())))
108                                         .forEach(module -> {
109                                             String bridgeId = module.getBridge();
110                                             if (bridgeId == null) {
111                                                 bridgesUids.put(module.getId(), createThing(module, homeUID));
112                                             } else {
113                                                 createThing(module, bridgesUids.getOrDefault(bridgeId, homeUID));
114                                             }
115                                         });
116                             });
117                 }
118             } catch (NetatmoException e) {
119                 logger.warn("Error during discovery process : {}", e.getMessage());
120             }
121         }
122     }
123
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));
129     }
130
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());
138         return moduleUID;
139     }
140
141     @Override
142     public void setThingHandler(ThingHandler handler) {
143         if (handler instanceof ApiBridgeHandler) {
144             this.handler = (ApiBridgeHandler) handler;
145         }
146     }
147
148     @Override
149     public @Nullable ThingHandler getThingHandler() {
150         return handler;
151     }
152
153     @Override
154     public void deactivate() {
155         super.deactivate();
156     }
157 }