]> git.basschouten.com Git - openhab-addons.git/blob
23bcfdeacd34f4d107e1a3c547c06f81b5184639
[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
54     public NetatmoDiscoveryService() {
55         super(ModuleType.AS_SET.stream().filter(mt -> !SKIPPED_TYPES.contains(mt)).map(mt -> mt.thingTypeUID)
56                 .collect(Collectors.toSet()), DISCOVER_TIMEOUT_SECONDS);
57     }
58
59     @Override
60     public void startScan() {
61         ApiBridgeHandler localHandler = handler;
62         if (localHandler != null) {
63             ThingUID apiBridgeUID = localHandler.getThing().getUID();
64             try {
65                 AircareApi airCareApi = localHandler.getRestManager(AircareApi.class);
66                 if (airCareApi != null) { // Search Healthy Home Coaches
67                     ListBodyResponse<NAMain> body = airCareApi.getHomeCoachData(null).getBody();
68                     if (body != null) {
69                         body.getElements().stream().forEach(homeCoach -> createThing(homeCoach, apiBridgeUID));
70                     }
71                 }
72                 if (localHandler.getReadFriends()) {
73                     WeatherApi weatherApi = localHandler.getRestManager(WeatherApi.class);
74                     if (weatherApi != null) { // Search favorite stations
75                         weatherApi.getFavoriteAndGuestStationsData().stream().filter(NAMain::isReadOnly)
76                                 .forEach(station -> {
77                                     ThingUID bridgeUID = createThing(station, apiBridgeUID);
78                                     station.getModules().values().stream()
79                                             .forEach(module -> createThing(module, bridgeUID));
80                                 });
81                     }
82                 }
83                 HomeApi homeApi = localHandler.getRestManager(HomeApi.class);
84                 if (homeApi != null) { // Search all the rest
85                     homeApi.getHomesData(null, null).stream().filter(h -> !h.getFeatures().isEmpty()).forEach(home -> {
86                         ThingUID homeUID = createThing(home, apiBridgeUID);
87                         home.getKnownPersons().forEach(person -> createThing(person, homeUID));
88                         home.getModules().values().stream().forEach(device -> {
89                             ModuleType deviceType = device.getType();
90                             String deviceBridge = device.getBridge();
91                             ThingUID bridgeUID = deviceBridge != null && deviceType.getBridge() != ModuleType.HOME
92                                     ? findThingUID(deviceType.getBridge(), deviceBridge, apiBridgeUID)
93                                     : deviceType.getBridge() == ModuleType.HOME ? homeUID : apiBridgeUID;
94                             createThing(device, bridgeUID);
95                         });
96                         home.getRooms().values().stream().forEach(room -> {
97                             room.getModuleIds().stream().map(id -> home.getModules().get(id))
98                                     .map(m -> m != null ? m.getType().feature : FeatureArea.NONE)
99                                     .filter(f -> FeatureArea.ENERGY.equals(f)).findAny()
100                                     .ifPresent(f -> createThing(room, homeUID));
101                         });
102                     });
103                 }
104             } catch (NetatmoException e) {
105                 logger.warn("Error during discovery process : {}", e.getMessage());
106             }
107         }
108     }
109
110     private ThingUID findThingUID(ModuleType thingType, String thingId, @Nullable ThingUID brigdeUID) {
111         for (ThingTypeUID supported : getSupportedThingTypes()) {
112             ThingTypeUID thingTypeUID = thingType.thingTypeUID;
113             if (supported.equals(thingTypeUID)) {
114                 String id = thingId.replaceAll("[^a-zA-Z0-9_]", "");
115                 return brigdeUID == null ? new ThingUID(supported, id) : new ThingUID(supported, brigdeUID, id);
116             }
117         }
118         throw new IllegalArgumentException("Unsupported device type discovered : " + thingType);
119     }
120
121     private ThingUID createThing(NAModule module, @Nullable ThingUID bridgeUID) {
122         ThingUID moduleUID = findThingUID(module.getType(), module.getId(), bridgeUID);
123         DiscoveryResultBuilder resultBuilder = DiscoveryResultBuilder.create(moduleUID)
124                 .withProperty(NAThingConfiguration.ID, module.getId())
125                 .withRepresentationProperty(NAThingConfiguration.ID)
126                 .withLabel(module.getName() != null ? module.getName() : module.getId());
127         if (bridgeUID != null) {
128             resultBuilder.withBridge(bridgeUID);
129         }
130         thingDiscovered(resultBuilder.build());
131         return moduleUID;
132     }
133
134     @Override
135     public void setThingHandler(ThingHandler handler) {
136         if (handler instanceof ApiBridgeHandler) {
137             this.handler = (ApiBridgeHandler) handler;
138         }
139     }
140
141     @Override
142     public @Nullable ThingHandler getThingHandler() {
143         return handler;
144     }
145
146     @Override
147     public void deactivate() {
148         super.deactivate();
149     }
150 }