]> git.basschouten.com Git - openhab-addons.git/blob
a518971a41e96a8a5c46ef8a0b8c483a230d9974
[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 java.util.HashMap;
16 import java.util.Map;
17 import java.util.Set;
18 import java.util.stream.Collectors;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.openhab.binding.netatmo.internal.api.AircareApi;
23 import org.openhab.binding.netatmo.internal.api.HomeApi;
24 import org.openhab.binding.netatmo.internal.api.ListBodyResponse;
25 import org.openhab.binding.netatmo.internal.api.NetatmoException;
26 import org.openhab.binding.netatmo.internal.api.WeatherApi;
27 import org.openhab.binding.netatmo.internal.api.data.ModuleType;
28 import org.openhab.binding.netatmo.internal.api.data.NetatmoConstants.FeatureArea;
29 import org.openhab.binding.netatmo.internal.api.dto.NAMain;
30 import org.openhab.binding.netatmo.internal.api.dto.NAModule;
31 import org.openhab.binding.netatmo.internal.config.NAThingConfiguration;
32 import org.openhab.binding.netatmo.internal.handler.ApiBridgeHandler;
33 import org.openhab.core.config.discovery.AbstractDiscoveryService;
34 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
35 import org.openhab.core.config.discovery.DiscoveryService;
36 import org.openhab.core.thing.ThingTypeUID;
37 import org.openhab.core.thing.ThingUID;
38 import org.openhab.core.thing.binding.ThingHandler;
39 import org.openhab.core.thing.binding.ThingHandlerService;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * The {@link NetatmoDiscoveryService} searches for available Netatmo things
45  *
46  * @author GaĆ«l L'hopital - Initial contribution
47  *
48  */
49 @NonNullByDefault
50 public class NetatmoDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService, DiscoveryService {
51     private static final Set<ModuleType> SKIPPED_TYPES = Set.of(ModuleType.UNKNOWN, ModuleType.ACCOUNT);
52     private static final int DISCOVER_TIMEOUT_SECONDS = 3;
53     private final Logger logger = LoggerFactory.getLogger(NetatmoDiscoveryService.class);
54     private @Nullable ApiBridgeHandler handler;
55
56     public NetatmoDiscoveryService() {
57         super(ModuleType.AS_SET.stream().filter(mt -> !SKIPPED_TYPES.contains(mt)).map(mt -> mt.thingTypeUID)
58                 .collect(Collectors.toSet()), DISCOVER_TIMEOUT_SECONDS);
59     }
60
61     @Override
62     public void startScan() {
63         ApiBridgeHandler localHandler = handler;
64         if (localHandler != null) {
65             ThingUID accountUID = localHandler.getThing().getUID();
66             try {
67                 AircareApi airCareApi = localHandler.getRestManager(AircareApi.class);
68                 if (airCareApi != null) { // Search Healthy Home Coaches
69                     ListBodyResponse<NAMain> body = airCareApi.getHomeCoachData(null).getBody();
70                     if (body != null) {
71                         body.getElements().stream().forEach(homeCoach -> createThing(homeCoach, accountUID));
72                     }
73                 }
74                 if (localHandler.getReadFriends()) {
75                     WeatherApi weatherApi = localHandler.getRestManager(WeatherApi.class);
76                     if (weatherApi != null) { // Search favorite stations
77                         weatherApi.getFavoriteAndGuestStationsData().stream().filter(NAMain::isReadOnly)
78                                 .forEach(station -> {
79                                     ThingUID bridgeUID = createThing(station, accountUID);
80                                     station.getModules().values().stream()
81                                             .forEach(module -> createThing(module, bridgeUID));
82                                 });
83                     }
84                 }
85                 HomeApi homeApi = localHandler.getRestManager(HomeApi.class);
86                 if (homeApi != null) { // Search those who depend from a home
87                     homeApi.getHomesData(null, null).stream().filter(h -> !h.getFeatures().isEmpty()).forEach(home -> {
88                         ThingUID homeUID = createThing(home, accountUID);
89
90                         home.getKnownPersons().forEach(person -> createThing(person, homeUID));
91
92                         Map<String, ThingUID> bridgesUids = new HashMap<>();
93
94                         home.getRooms().values().stream().forEach(room -> {
95                             room.getModuleIds().stream().map(id -> home.getModules().get(id))
96                                     .map(m -> m != null ? m.getType().feature : FeatureArea.NONE)
97                                     .filter(f -> FeatureArea.ENERGY.equals(f)).findAny()
98                                     .ifPresent(f -> bridgesUids.put(room.getId(), createThing(room, homeUID)));
99                         });
100
101                         // Creating modules that have no bridge first
102                         home.getModules().values().stream().filter(module -> module.getBridge() == null)
103                                 .forEach(device -> bridgesUids.put(device.getId(), createThing(device, homeUID)));
104                         // Then the others
105                         home.getModules().values().stream().filter(module -> module.getBridge() != null).forEach(
106                                 device -> createThing(device, bridgesUids.getOrDefault(device.getBridge(), homeUID)));
107                     });
108                 }
109             } catch (NetatmoException e) {
110                 logger.warn("Error during discovery process : {}", e.getMessage());
111             }
112         }
113     }
114
115     private ThingUID findThingUID(ModuleType thingType, String thingId, ThingUID bridgeUID) {
116         ThingTypeUID thingTypeUID = thingType.thingTypeUID;
117         return getSupportedThingTypes().stream().filter(supported -> supported.equals(thingTypeUID)).findFirst()
118                 .map(supported -> new ThingUID(supported, bridgeUID, thingId.replaceAll("[^a-zA-Z0-9_]", "")))
119                 .orElseThrow(() -> new IllegalArgumentException("Unsupported device type discovered : " + thingType));
120     }
121
122     private ThingUID createThing(NAModule module, ThingUID bridgeUID) {
123         ThingUID moduleUID = findThingUID(module.getType(), module.getId(), bridgeUID);
124         DiscoveryResultBuilder resultBuilder = DiscoveryResultBuilder.create(moduleUID)
125                 .withProperty(NAThingConfiguration.ID, module.getId())
126                 .withRepresentationProperty(NAThingConfiguration.ID)
127                 .withLabel(module.getName() != null ? module.getName() : module.getId()).withBridge(bridgeUID);
128         thingDiscovered(resultBuilder.build());
129         return moduleUID;
130     }
131
132     @Override
133     public void setThingHandler(ThingHandler handler) {
134         if (handler instanceof ApiBridgeHandler) {
135             this.handler = (ApiBridgeHandler) handler;
136         }
137     }
138
139     @Override
140     public @Nullable ThingHandler getThingHandler() {
141         return handler;
142     }
143
144     @Override
145     public void deactivate() {
146         super.deactivate();
147     }
148 }