]> git.basschouten.com Git - openhab-addons.git/blob
c99a5f85b520f80b2179d91ffd361be358608e81
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.tradfri.internal.handler;
14
15 import static org.openhab.binding.tradfri.internal.TradfriBindingConstants.*;
16
17 import java.io.IOException;
18 import java.net.URI;
19 import java.net.URISyntaxException;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.Set;
23 import java.util.UUID;
24 import java.util.concurrent.CopyOnWriteArraySet;
25 import java.util.concurrent.ScheduledFuture;
26 import java.util.concurrent.TimeUnit;
27
28 import org.eclipse.californium.core.CoapClient;
29 import org.eclipse.californium.core.CoapResponse;
30 import org.eclipse.californium.core.network.CoapEndpoint;
31 import org.eclipse.californium.elements.exception.ConnectorException;
32 import org.eclipse.californium.scandium.DTLSConnector;
33 import org.eclipse.californium.scandium.config.DtlsConnectorConfig;
34 import org.eclipse.californium.scandium.dtls.pskstore.StaticPskStore;
35 import org.eclipse.jdt.annotation.NonNullByDefault;
36 import org.eclipse.jdt.annotation.Nullable;
37 import org.openhab.binding.tradfri.internal.CoapCallback;
38 import org.openhab.binding.tradfri.internal.DeviceUpdateListener;
39 import org.openhab.binding.tradfri.internal.TradfriBindingConstants;
40 import org.openhab.binding.tradfri.internal.TradfriCoapClient;
41 import org.openhab.binding.tradfri.internal.TradfriCoapHandler;
42 import org.openhab.binding.tradfri.internal.config.TradfriGatewayConfig;
43 import org.openhab.binding.tradfri.internal.discovery.TradfriDiscoveryService;
44 import org.openhab.binding.tradfri.internal.model.TradfriVersion;
45 import org.openhab.core.config.core.Configuration;
46 import org.openhab.core.thing.Bridge;
47 import org.openhab.core.thing.ChannelUID;
48 import org.openhab.core.thing.Thing;
49 import org.openhab.core.thing.ThingStatus;
50 import org.openhab.core.thing.ThingStatusDetail;
51 import org.openhab.core.thing.binding.BaseBridgeHandler;
52 import org.openhab.core.thing.binding.ThingHandler;
53 import org.openhab.core.thing.binding.ThingHandlerService;
54 import org.openhab.core.types.Command;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 import com.google.gson.JsonArray;
59 import com.google.gson.JsonElement;
60 import com.google.gson.JsonObject;
61 import com.google.gson.JsonParseException;
62 import com.google.gson.JsonParser;
63 import com.google.gson.JsonSyntaxException;
64
65 /**
66  * The {@link TradfriGatewayHandler} is responsible for handling commands, which are
67  * sent to one of the channels.
68  *
69  * @author Kai Kreuzer - Initial contribution
70  */
71 @NonNullByDefault
72 public class TradfriGatewayHandler extends BaseBridgeHandler implements CoapCallback {
73
74     protected final Logger logger = LoggerFactory.getLogger(getClass());
75
76     private static final TradfriVersion MIN_SUPPORTED_VERSION = new TradfriVersion("1.2.42");
77
78     private @NonNullByDefault({}) TradfriCoapClient deviceClient;
79     private @NonNullByDefault({}) String gatewayURI;
80     private @NonNullByDefault({}) String gatewayInfoURI;
81     private @NonNullByDefault({}) DTLSConnector dtlsConnector;
82     private @Nullable CoapEndpoint endPoint;
83
84     private final Set<DeviceUpdateListener> deviceUpdateListeners = new CopyOnWriteArraySet<>();
85
86     private @Nullable ScheduledFuture<?> scanJob;
87
88     public TradfriGatewayHandler(Bridge bridge) {
89         super(bridge);
90     }
91
92     @Override
93     public void handleCommand(ChannelUID channelUID, Command command) {
94         // there are no channels on the gateway yet
95     }
96
97     @Override
98     public void initialize() {
99         TradfriGatewayConfig configuration = getConfigAs(TradfriGatewayConfig.class);
100
101         if (isNullOrEmpty(configuration.host)) {
102             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
103                     "Host must be specified in the configuration!");
104             return;
105         }
106
107         if (isNullOrEmpty(configuration.code)) {
108             if (isNullOrEmpty(configuration.identity) || isNullOrEmpty(configuration.preSharedKey)) {
109                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
110                         "Either security code or identity and pre-shared key must be provided in the configuration!");
111                 return;
112             } else {
113                 establishConnection();
114             }
115         } else {
116             String currentFirmware = thing.getProperties().get(Thing.PROPERTY_FIRMWARE_VERSION);
117             if (!isNullOrEmpty(currentFirmware)
118                     && MIN_SUPPORTED_VERSION.compareTo(new TradfriVersion(currentFirmware)) > 0) {
119                 // older firmware not supported
120                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
121                         String.format(
122                                 "Gateway firmware version '%s' is too old! Minimum supported firmware version is '%s'.",
123                                 currentFirmware, MIN_SUPPORTED_VERSION.toString()));
124                 return;
125             }
126
127             // Running async operation to retrieve new <'identity','key'> pair
128             scheduler.execute(() -> {
129                 boolean success = obtainIdentityAndPreSharedKey();
130                 if (success) {
131                     establishConnection();
132                 }
133             });
134         }
135     }
136
137     @Override
138     public Collection<Class<? extends ThingHandlerService>> getServices() {
139         return Collections.singleton(TradfriDiscoveryService.class);
140     }
141
142     private void establishConnection() {
143         TradfriGatewayConfig configuration = getConfigAs(TradfriGatewayConfig.class);
144
145         this.gatewayURI = "coaps://" + configuration.host + ":" + configuration.port + "/" + DEVICES;
146         this.gatewayInfoURI = "coaps://" + configuration.host + ":" + configuration.port + "/" + GATEWAY + "/"
147                 + GATEWAY_DETAILS;
148         try {
149             URI uri = new URI(gatewayURI);
150             deviceClient = new TradfriCoapClient(uri);
151         } catch (URISyntaxException e) {
152             logger.error("Illegal gateway URI '{}': {}", gatewayURI, e.getMessage());
153             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
154             return;
155         }
156
157         DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder();
158         builder.setPskStore(new StaticPskStore(configuration.identity, configuration.preSharedKey.getBytes()));
159         builder.setMaxConnections(100);
160         builder.setStaleConnectionThreshold(60);
161         dtlsConnector = new DTLSConnector(builder.build());
162         endPoint = new CoapEndpoint.Builder().setConnector(dtlsConnector).build();
163         deviceClient.setEndpoint(endPoint);
164         updateStatus(ThingStatus.UNKNOWN);
165
166         // schedule a new scan every minute
167         scanJob = scheduler.scheduleWithFixedDelay(this::startScan, 0, 1, TimeUnit.MINUTES);
168     }
169
170     /**
171      * Authenticates against the gateway with the security code in order to receive a pre-shared key for a newly
172      * generated identity.
173      * As this requires a remote request, this method might be long-running.
174      *
175      * @return true, if credentials were successfully obtained, false otherwise
176      */
177     protected boolean obtainIdentityAndPreSharedKey() {
178         TradfriGatewayConfig configuration = getConfigAs(TradfriGatewayConfig.class);
179
180         String identity = UUID.randomUUID().toString().replace("-", "");
181         String preSharedKey = null;
182
183         CoapResponse gatewayResponse;
184         String authUrl = null;
185         String responseText = null;
186         try {
187             DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder();
188             builder.setPskStore(new StaticPskStore("Client_identity", configuration.code.getBytes()));
189
190             DTLSConnector dtlsConnector = new DTLSConnector(builder.build());
191             CoapEndpoint.Builder authEndpointBuilder = new CoapEndpoint.Builder();
192             authEndpointBuilder.setConnector(dtlsConnector);
193             CoapEndpoint authEndpoint = authEndpointBuilder.build();
194             authUrl = "coaps://" + configuration.host + ":" + configuration.port + "/15011/9063";
195
196             CoapClient deviceClient = new CoapClient(new URI(authUrl));
197             deviceClient.setTimeout(TimeUnit.SECONDS.toMillis(10));
198             deviceClient.setEndpoint(authEndpoint);
199
200             JsonObject json = new JsonObject();
201             json.addProperty(CLIENT_IDENTITY_PROPOSED, identity);
202
203             gatewayResponse = deviceClient.post(json.toString(), 0);
204
205             authEndpoint.destroy();
206             deviceClient.shutdown();
207
208             if (gatewayResponse == null) {
209                 // seems we ran in a timeout, which potentially also happens
210                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
211                         "No response from gateway. Might be due to an invalid security code.");
212                 return false;
213             }
214
215             if (gatewayResponse.isSuccess()) {
216                 responseText = gatewayResponse.getResponseText();
217                 json = new JsonParser().parse(responseText).getAsJsonObject();
218                 preSharedKey = json.get(NEW_PSK_BY_GW).getAsString();
219
220                 if (isNullOrEmpty(preSharedKey)) {
221                     logger.error("Received pre-shared key is empty for thing {} on gateway at {}", getThing().getUID(),
222                             configuration.host);
223                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
224                             "Pre-shared key was not obtain successfully");
225                     return false;
226                 } else {
227                     logger.info("Received pre-shared key for gateway '{}'", configuration.host);
228                     logger.debug("Using identity '{}' with pre-shared key '{}'.", identity, preSharedKey);
229
230                     Configuration editedConfig = editConfiguration();
231                     editedConfig.put(TradfriBindingConstants.GATEWAY_CONFIG_CODE, null);
232                     editedConfig.put(TradfriBindingConstants.GATEWAY_CONFIG_IDENTITY, identity);
233                     editedConfig.put(TradfriBindingConstants.GATEWAY_CONFIG_PRE_SHARED_KEY, preSharedKey);
234                     updateConfiguration(editedConfig);
235
236                     return true;
237                 }
238             } else {
239                 logger.warn(
240                         "Failed obtaining pre-shared key for identity '{}' (response code '{}', response text '{}')",
241                         identity, gatewayResponse.getCode(),
242                         isNullOrEmpty(gatewayResponse.getResponseText()) ? "<empty>"
243                                 : gatewayResponse.getResponseText());
244                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, String
245                         .format("Failed obtaining pre-shared key with status code '%s'", gatewayResponse.getCode()));
246             }
247         } catch (URISyntaxException e) {
248             logger.error("Illegal gateway URI '{}'", authUrl, e);
249             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
250         } catch (JsonParseException e) {
251             logger.warn("Invalid response received from gateway '{}'", responseText, e);
252             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
253                     String.format("Invalid response received from gateway '%s'", responseText));
254         } catch (ConnectorException | IOException e) {
255             logger.debug("Error connecting to gateway ", e);
256             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
257                     String.format("Error connecting to gateway."));
258         }
259         return false;
260     }
261
262     @Override
263     public void dispose() {
264         if (scanJob != null) {
265             scanJob.cancel(true);
266             scanJob = null;
267         }
268         if (endPoint != null) {
269             endPoint.destroy();
270             endPoint = null;
271         }
272         if (deviceClient != null) {
273             deviceClient.shutdown();
274             deviceClient = null;
275         }
276         super.dispose();
277     }
278
279     /**
280      * Does a request to the gateway to list all available devices/services.
281      * The response is received and processed by the method {@link onUpdate(JsonElement data)}.
282      */
283     public void startScan() {
284         if (endPoint != null) {
285             requestGatewayInfo();
286             deviceClient.get(new TradfriCoapHandler(this));
287         }
288     }
289
290     /**
291      * Returns the root URI of the gateway.
292      *
293      * @return root URI of the gateway with coaps scheme
294      */
295     public String getGatewayURI() {
296         return gatewayURI;
297     }
298
299     /**
300      * Returns the coap endpoint that can be used within coap clients.
301      *
302      * @return the coap endpoint
303      */
304     public @Nullable CoapEndpoint getEndpoint() {
305         return endPoint;
306     }
307
308     @Override
309     public void onUpdate(JsonElement data) {
310         logger.debug("onUpdate response: {}", data);
311         if (endPoint != null) {
312             try {
313                 JsonArray array = data.getAsJsonArray();
314                 for (int i = 0; i < array.size(); i++) {
315                     requestDeviceDetails(array.get(i).getAsString());
316                 }
317             } catch (JsonSyntaxException e) {
318                 logger.debug("JSON error: {}", e.getMessage());
319                 setStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
320             }
321         }
322     }
323
324     private synchronized void requestGatewayInfo() {
325         // we are reusing our coap client and merely temporarily set a gateway info to call
326         deviceClient.setURI(gatewayInfoURI);
327         deviceClient.asyncGet().thenAccept(data -> {
328             logger.debug("requestGatewayInfo response: {}", data);
329             JsonObject json = new JsonParser().parse(data).getAsJsonObject();
330             String firmwareVersion = json.get(VERSION).getAsString();
331             getThing().setProperty(Thing.PROPERTY_FIRMWARE_VERSION, firmwareVersion);
332             updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
333         });
334         // restore root URI
335         deviceClient.setURI(gatewayURI);
336     }
337
338     private synchronized void requestDeviceDetails(String instanceId) {
339         // we are reusing our coap client and merely temporarily set a sub-URI to call
340         deviceClient.setURI(gatewayURI + "/" + instanceId);
341         deviceClient.asyncGet().thenAccept(data -> {
342             logger.debug("requestDeviceDetails response: {}", data);
343             JsonObject json = new JsonParser().parse(data).getAsJsonObject();
344             deviceUpdateListeners.forEach(listener -> listener.onUpdate(instanceId, json));
345         });
346         // restore root URI
347         deviceClient.setURI(gatewayURI);
348     }
349
350     @Override
351     public void setStatus(ThingStatus status, ThingStatusDetail statusDetail) {
352         // to fix connection issues after a gateway reboot, a session resume is forced for the next command
353         if (status == ThingStatus.OFFLINE && statusDetail == ThingStatusDetail.COMMUNICATION_ERROR) {
354             logger.debug("Gateway communication error. Forcing a re-initialization!");
355             dispose();
356             initialize();
357         }
358
359         // are we still connected at all?
360         if (endPoint != null) {
361             updateStatus(status, statusDetail);
362         }
363     }
364
365     /**
366      * Registers a listener, which is informed about device details.
367      *
368      * @param listener the listener to register
369      */
370     public void registerDeviceUpdateListener(DeviceUpdateListener listener) {
371         this.deviceUpdateListeners.add(listener);
372     }
373
374     /**
375      * Unregisters a given listener.
376      *
377      * @param listener the listener to unregister
378      */
379     public void unregisterDeviceUpdateListener(DeviceUpdateListener listener) {
380         this.deviceUpdateListeners.remove(listener);
381     }
382
383     private boolean isNullOrEmpty(@Nullable String string) {
384         return string == null || string.isEmpty();
385     }
386
387     @Override
388     public void thingUpdated(Thing thing) {
389         super.thingUpdated(thing);
390
391         logger.info("Bridge configuration updated. Updating paired things (if any).");
392         for (Thing t : getThing().getThings()) {
393             final ThingHandler thingHandler = t.getHandler();
394             if (thingHandler != null) {
395                 thingHandler.thingUpdated(t);
396             }
397         }
398     }
399 }