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