2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.tradfri.internal.handler;
15 import static org.openhab.binding.tradfri.internal.TradfriBindingConstants.*;
17 import java.io.IOException;
19 import java.net.URISyntaxException;
20 import java.util.Collection;
21 import java.util.Collections;
23 import java.util.UUID;
24 import java.util.concurrent.CopyOnWriteArraySet;
25 import java.util.concurrent.ScheduledFuture;
26 import java.util.concurrent.TimeUnit;
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;
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;
66 * The {@link TradfriGatewayHandler} is responsible for handling commands, which are
67 * sent to one of the channels.
69 * @author Kai Kreuzer - Initial contribution
72 public class TradfriGatewayHandler extends BaseBridgeHandler implements CoapCallback {
74 protected final Logger logger = LoggerFactory.getLogger(getClass());
76 private static final TradfriVersion MIN_SUPPORTED_VERSION = new TradfriVersion("1.2.42");
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;
84 private final Set<DeviceUpdateListener> deviceUpdateListeners = new CopyOnWriteArraySet<>();
86 private @Nullable ScheduledFuture<?> scanJob;
88 public TradfriGatewayHandler(Bridge bridge) {
93 public void handleCommand(ChannelUID channelUID, Command command) {
94 // there are no channels on the gateway yet
98 public void initialize() {
99 TradfriGatewayConfig configuration = getConfigAs(TradfriGatewayConfig.class);
101 if (isNullOrEmpty(configuration.host)) {
102 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
103 "Host must be specified in the configuration!");
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!");
113 establishConnection();
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,
122 "Gateway firmware version '%s' is too old! Minimum supported firmware version is '%s'.",
123 currentFirmware, MIN_SUPPORTED_VERSION.toString()));
127 // Running async operation to retrieve new <'identity','key'> pair
128 scheduler.execute(() -> {
129 boolean success = obtainIdentityAndPreSharedKey();
131 establishConnection();
138 public Collection<Class<? extends ThingHandlerService>> getServices() {
139 return Collections.singleton(TradfriDiscoveryService.class);
142 private void establishConnection() {
143 TradfriGatewayConfig configuration = getConfigAs(TradfriGatewayConfig.class);
145 this.gatewayURI = "coaps://" + configuration.host + ":" + configuration.port + "/" + DEVICES;
146 this.gatewayInfoURI = "coaps://" + configuration.host + ":" + configuration.port + "/" + GATEWAY + "/"
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());
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);
166 // schedule a new scan every minute
167 scanJob = scheduler.scheduleWithFixedDelay(this::startScan, 0, 1, TimeUnit.MINUTES);
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.
175 * @return true, if credentials were successfully obtained, false otherwise
177 protected boolean obtainIdentityAndPreSharedKey() {
178 TradfriGatewayConfig configuration = getConfigAs(TradfriGatewayConfig.class);
180 String identity = UUID.randomUUID().toString().replace("-", "");
181 String preSharedKey = null;
183 CoapResponse gatewayResponse;
184 String authUrl = null;
185 String responseText = null;
187 DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder();
188 builder.setPskStore(new StaticPskStore("Client_identity", configuration.code.getBytes()));
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";
196 CoapClient deviceClient = new CoapClient(new URI(authUrl));
197 deviceClient.setTimeout(TimeUnit.SECONDS.toMillis(10));
198 deviceClient.setEndpoint(authEndpoint);
200 JsonObject json = new JsonObject();
201 json.addProperty(CLIENT_IDENTITY_PROPOSED, identity);
203 gatewayResponse = deviceClient.post(json.toString(), 0);
205 authEndpoint.destroy();
206 deviceClient.shutdown();
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.");
215 if (gatewayResponse.isSuccess()) {
216 responseText = gatewayResponse.getResponseText();
217 json = new JsonParser().parse(responseText).getAsJsonObject();
218 preSharedKey = json.get(NEW_PSK_BY_GW).getAsString();
220 if (isNullOrEmpty(preSharedKey)) {
221 logger.error("Received pre-shared key is empty for thing {} on gateway at {}", getThing().getUID(),
223 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
224 "Pre-shared key was not obtain successfully");
227 logger.info("Received pre-shared key for gateway '{}'", configuration.host);
228 logger.debug("Using identity '{}' with pre-shared key '{}'.", identity, preSharedKey);
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);
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()));
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."));
263 public void dispose() {
264 if (scanJob != null) {
265 scanJob.cancel(true);
268 if (endPoint != null) {
272 if (deviceClient != null) {
273 deviceClient.shutdown();
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)}.
283 public void startScan() {
284 if (endPoint != null) {
285 requestGatewayInfo();
286 deviceClient.get(new TradfriCoapHandler(this));
291 * Returns the root URI of the gateway.
293 * @return root URI of the gateway with coaps scheme
295 public String getGatewayURI() {
300 * Returns the coap endpoint that can be used within coap clients.
302 * @return the coap endpoint
304 public @Nullable CoapEndpoint getEndpoint() {
309 public void onUpdate(JsonElement data) {
310 logger.debug("onUpdate response: {}", data);
311 if (endPoint != null) {
313 JsonArray array = data.getAsJsonArray();
314 for (int i = 0; i < array.size(); i++) {
315 requestDeviceDetails(array.get(i).getAsString());
317 } catch (JsonSyntaxException e) {
318 logger.debug("JSON error: {}", e.getMessage());
319 setStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
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);
335 deviceClient.setURI(gatewayURI);
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));
347 deviceClient.setURI(gatewayURI);
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!");
359 // are we still connected at all?
360 if (endPoint != null) {
361 updateStatus(status, statusDetail);
366 * Registers a listener, which is informed about device details.
368 * @param listener the listener to register
370 public void registerDeviceUpdateListener(DeviceUpdateListener listener) {
371 this.deviceUpdateListeners.add(listener);
375 * Unregisters a given listener.
377 * @param listener the listener to unregister
379 public void unregisterDeviceUpdateListener(DeviceUpdateListener listener) {
380 this.deviceUpdateListeners.remove(listener);
383 private boolean isNullOrEmpty(@Nullable String string) {
384 return string == null || string.isEmpty();
388 public void thingUpdated(Thing thing) {
389 super.thingUpdated(thing);
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);