]> git.basschouten.com Git - openhab-addons.git/blob
523ff2d009e07ff87b82a10dddbb46c9b9db8f00
[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                         ListBodyResponse<NAMain> body = weatherApi.getStationsData(null, true).getBody();
77                         if (body != null) {
78                             body.getElements().stream().filter(NAMain::isReadOnly).forEach(station -> {
79                                 ThingUID bridgeUID = createThing(station, apiBridgeUID);
80                                 station.getModules().values().stream()
81                                         .forEach(module -> createThing(module, bridgeUID));
82                             });
83                         }
84                     }
85                 }
86                 HomeApi homeApi = localHandler.getRestManager(HomeApi.class);
87                 if (homeApi != null) { // Search all the rest
88                     homeApi.getHomesData(null, null).stream().filter(h -> !h.getFeatures().isEmpty()).forEach(home -> {
89                         ThingUID homeUID = createThing(home, apiBridgeUID);
90                         home.getKnownPersons().forEach(person -> createThing(person, homeUID));
91                         home.getModules().values().stream().forEach(device -> {
92                             ModuleType deviceType = device.getType();
93                             String deviceBridge = device.getBridge();
94                             ThingUID bridgeUID = deviceBridge != null && deviceType.getBridge() != ModuleType.HOME
95                                     ? findThingUID(deviceType.getBridge(), deviceBridge, apiBridgeUID)
96                                     : deviceType.getBridge() == ModuleType.HOME ? homeUID : apiBridgeUID;
97                             createThing(device, bridgeUID);
98                         });
99                         home.getRooms().values().stream().forEach(room -> {
100                             room.getModuleIds().stream().map(id -> home.getModules().get(id))
101                                     .map(m -> m != null ? m.getType().feature : FeatureArea.NONE)
102                                     .filter(f -> FeatureArea.ENERGY.equals(f)).findAny()
103                                     .ifPresent(f -> createThing(room, homeUID));
104                         });
105                     });
106                 }
107             } catch (NetatmoException e) {
108                 logger.warn("Error during discovery process : {}", e.getMessage());
109             }
110         }
111     }
112
113     private ThingUID findThingUID(ModuleType thingType, String thingId, @Nullable ThingUID brigdeUID) {
114         for (ThingTypeUID supported : getSupportedThingTypes()) {
115             ThingTypeUID thingTypeUID = thingType.thingTypeUID;
116             if (supported.equals(thingTypeUID)) {
117                 String id = thingId.replaceAll("[^a-zA-Z0-9_]", "");
118                 return brigdeUID == null ? new ThingUID(supported, id) : new ThingUID(supported, brigdeUID, id);
119             }
120         }
121         throw new IllegalArgumentException("Unsupported device type discovered : " + thingType);
122     }
123
124     private ThingUID createThing(NAModule module, @Nullable ThingUID bridgeUID) {
125         ThingUID moduleUID = findThingUID(module.getType(), module.getId(), bridgeUID);
126         DiscoveryResultBuilder resultBuilder = DiscoveryResultBuilder.create(moduleUID)
127                 .withProperty(NAThingConfiguration.ID, module.getId())
128                 .withRepresentationProperty(NAThingConfiguration.ID)
129                 .withLabel(module.getName() != null ? module.getName() : module.getId());
130         if (bridgeUID != null) {
131             resultBuilder.withBridge(bridgeUID);
132         }
133         thingDiscovered(resultBuilder.build());
134         return moduleUID;
135     }
136
137     @Override
138     public void setThingHandler(ThingHandler handler) {
139         if (handler instanceof ApiBridgeHandler) {
140             this.handler = (ApiBridgeHandler) handler;
141             this.readFriends = ((ApiBridgeHandler) handler).getReadFriends();
142         }
143     }
144
145     @Override
146     public @Nullable ThingHandler getThingHandler() {
147         return handler;
148     }
149
150     @Override
151     public void deactivate() {
152         super.deactivate();
153     }
154 }