]> git.basschouten.com Git - openhab-addons.git/blob
5e6eb0f58354307488034824b6d64658173650db
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.nuki.internal.discovery;
14
15 import java.util.Set;
16
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jetty.client.HttpClient;
19 import org.eclipse.jetty.client.api.ContentResponse;
20 import org.eclipse.jetty.http.HttpStatus;
21 import org.openhab.binding.nuki.internal.constants.NukiBindingConstants;
22 import org.openhab.binding.nuki.internal.constants.NukiLinkBuilder;
23 import org.openhab.binding.nuki.internal.dto.BridgeApiAuthDto;
24 import org.openhab.binding.nuki.internal.dto.WebApiBridgeDiscoveryDto;
25 import org.openhab.binding.nuki.internal.dto.WebApiBridgeDto;
26 import org.openhab.core.config.discovery.AbstractDiscoveryService;
27 import org.openhab.core.config.discovery.DiscoveryResult;
28 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
29 import org.openhab.core.config.discovery.DiscoveryService;
30 import org.openhab.core.io.net.http.HttpClientFactory;
31 import org.openhab.core.thing.ThingRegistry;
32 import org.osgi.service.component.annotations.Activate;
33 import org.osgi.service.component.annotations.Component;
34 import org.osgi.service.component.annotations.Reference;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 import com.google.gson.Gson;
39
40 /**
41  * Discovery service which uses Nuki Web API to discover all bridges on same network
42  * and uses authentication API to obtain access token.
43  *
44  * @author Jan Vybíral - Initial contribution
45  */
46 @NonNullByDefault
47 @Component(service = DiscoveryService.class, configurationPid = "discovery." + NukiBindingConstants.BINDING_ID)
48 public class NukiBridgeDiscoveryService extends AbstractDiscoveryService {
49
50     private final Logger logger = LoggerFactory.getLogger(NukiBridgeDiscoveryService.class);
51
52     private final HttpClient httpClient;
53     private final ThingRegistry thingRegistry;
54     private final Gson gson = new Gson();
55
56     @Activate
57     public NukiBridgeDiscoveryService(@Reference final HttpClientFactory httpClientFactory,
58             @Reference final ThingRegistry thingRegistry) {
59         super(Set.of(NukiBindingConstants.THING_TYPE_BRIDGE), 30, false);
60         this.httpClient = httpClientFactory.getCommonHttpClient();
61         this.thingRegistry = thingRegistry;
62     }
63
64     @Override
65     protected void startScan() {
66         try {
67             ContentResponse response = this.httpClient.GET(NukiLinkBuilder.URI_BRIDGE_DISCOVERY);
68             if (response.getStatus() == HttpStatus.OK_200) {
69                 String responseString = response.getContentAsString();
70                 WebApiBridgeDiscoveryDto discoveryResult = gson.fromJson(responseString,
71                         WebApiBridgeDiscoveryDto.class);
72                 if (discoveryResult == null) {
73                     logger.debug("Bridge discovery failed - API returned invalid body {}", responseString);
74                 } else if (discoveryResult.getErrorCode() == 0) {
75                     discoverBridges(discoveryResult);
76                 } else {
77                     logger.debug("Bridge discovery failed - API returned error code '{}': {}",
78                             discoveryResult.getErrorCode(), responseString);
79                 }
80             } else {
81                 logger.debug("Bridge discovery failed - invalid status {}: '{}'", response.getStatus(),
82                         response.getContentAsString());
83             }
84         } catch (Exception e) {
85             logger.debug("Bridge discovery failed", e);
86         }
87     }
88
89     private void discoverBridges(WebApiBridgeDiscoveryDto discoveryResult) {
90         logger.debug("Discovery finished, found {} bridges", discoveryResult);
91
92         discoveryResult.getBridges().forEach(bridge -> {
93             if (thingRegistry.get(bridge.getThingUid()) != null) {
94                 logger.debug("Bridge {} already exists, skipping discovery", bridge.getThingUid());
95             } else {
96                 scheduler.execute(new BridgeInitializer(bridge));
97             }
98         });
99     }
100
101     private void discoverBridge(WebApiBridgeDto bridgeData, String token) {
102         String name;
103         if (token.isBlank()) {
104             logger.debug("Nuki bridge {}({}) discovered without api token", bridgeData.getIp(),
105                     bridgeData.getBridgeId());
106             name = "Nuki Bridge (no API token)";
107         } else {
108             logger.info("Nuki bridge {}({}) discovered and initialized", bridgeData.getIp(), bridgeData.getBridgeId());
109             name = "Nuki Bridge";
110         }
111
112         DiscoveryResult result = DiscoveryResultBuilder.create(bridgeData.getThingUid()).withLabel(name)
113                 .withProperty(NukiBindingConstants.PROPERTY_BRIDGE_ID, bridgeData.getBridgeId())
114                 .withProperty(NukiBindingConstants.CONFIG_IP, bridgeData.getIp())
115                 .withProperty(NukiBindingConstants.CONFIG_PORT, bridgeData.getPort())
116                 .withProperty(NukiBindingConstants.CONFIG_API_TOKEN, token)
117                 .withRepresentationProperty(NukiBindingConstants.PROPERTY_BRIDGE_ID).build();
118         thingDiscovered(result);
119     }
120
121     private class BridgeInitializer implements Runnable {
122         private final WebApiBridgeDto bridge;
123
124         private BridgeInitializer(WebApiBridgeDto bridge) {
125             this.bridge = bridge;
126         }
127
128         @Override
129         public void run() {
130             logger.info("Discovered Nuki bridge {}({}) - obtaining API token, press button on bridge to complete",
131                     bridge.getIp(), bridge.getBridgeId());
132             try {
133                 ContentResponse response = httpClient.GET(NukiLinkBuilder.getAuthUri(bridge.getIp(), bridge.getPort()));
134                 String responseData = response.getContentAsString();
135                 if (response.getStatus() == HttpStatus.OK_200) {
136                     BridgeApiAuthDto authResult = gson.fromJson(responseData, BridgeApiAuthDto.class);
137                     if (authResult != null && authResult.isSuccess()) {
138                         discoverBridge(bridge, authResult.getToken());
139                     } else {
140                         logger.warn(
141                                 "Failed to get API token for bridge {}({}) - bridge did not return success response, make sure button on bridge was pressed during discovery",
142                                 bridge.getIp(), bridge.getBridgeId());
143                         discoverBridge(bridge, "");
144                     }
145                 } else if (response.getStatus() == HttpStatus.FORBIDDEN_403) {
146                     logger.warn(
147                             "Failed to get API token for bridge {}({}) - bridge authentication is disabled, check settings",
148                             bridge.getIp(), bridge.getBridgeId());
149                     discoverBridge(bridge, "");
150                 } else {
151                     logger.warn("Failed to get API token for bridge {}({}) - invalid status {}: {}", bridge.getIp(),
152                             bridge.getBridgeId(), response.getStatus(), responseData);
153                 }
154             } catch (Exception e) {
155                 logger.warn("Failed to get API token for bridge {}({})", bridge.getIp(), bridge.getBridgeId(), e);
156             }
157         }
158     }
159 }