]> git.basschouten.com Git - openhab-addons.git/blob
540f4bb8ddae21e43987dbb7f3a09a3bae0def3e
[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.core.thing.Thing.*;
16
17 import java.net.URI;
18 import java.net.URISyntaxException;
19 import java.util.concurrent.TimeUnit;
20
21 import org.eclipse.californium.core.CoapObserveRelation;
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.openhab.binding.tradfri.internal.CoapCallback;
25 import org.openhab.binding.tradfri.internal.TradfriCoapClient;
26 import org.openhab.binding.tradfri.internal.config.TradfriDeviceConfig;
27 import org.openhab.binding.tradfri.internal.model.TradfriDeviceData;
28 import org.openhab.core.thing.Bridge;
29 import org.openhab.core.thing.Thing;
30 import org.openhab.core.thing.ThingStatus;
31 import org.openhab.core.thing.ThingStatusDetail;
32 import org.openhab.core.thing.ThingStatusInfo;
33 import org.openhab.core.thing.binding.BaseThingHandler;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 /**
38  * The {@link TradfriThingHandler} is the abstract base class for individual device handlers.
39  *
40  * @author Kai Kreuzer - Initial contribution
41  * @author Christoph Weitkamp - Restructuring and refactoring of the binding
42  */
43 @NonNullByDefault
44 public abstract class TradfriThingHandler extends BaseThingHandler implements CoapCallback {
45
46     private final Logger logger = LoggerFactory.getLogger(TradfriThingHandler.class);
47
48     // the unique instance id of the device
49     protected @Nullable Integer id;
50
51     // used to check whether we have already been disposed when receiving data asynchronously
52     protected volatile boolean active;
53
54     protected @NonNullByDefault({}) TradfriCoapClient coapClient;
55
56     private @Nullable CoapObserveRelation observeRelation;
57
58     public TradfriThingHandler(Thing thing) {
59         super(thing);
60     }
61
62     @Override
63     @SuppressWarnings("null")
64     public synchronized void initialize() {
65         Bridge tradfriGateway = getBridge();
66         this.id = getConfigAs(TradfriDeviceConfig.class).id;
67         TradfriGatewayHandler handler = (TradfriGatewayHandler) tradfriGateway.getHandler();
68
69         String uriString = handler.getGatewayURI() + "/" + id;
70         try {
71             URI uri = new URI(uriString);
72             coapClient = new TradfriCoapClient(uri);
73             coapClient.setEndpoint(handler.getEndpoint());
74         } catch (URISyntaxException e) {
75             logger.debug("Illegal device URI `{}`: {}", uriString, e.getMessage());
76             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
77             return;
78         }
79         active = true;
80         updateStatus(ThingStatus.UNKNOWN);
81         switch (tradfriGateway.getStatus()) {
82             case ONLINE:
83                 scheduler.schedule(() -> {
84                     observeRelation = coapClient.startObserve(this);
85                 }, 3, TimeUnit.SECONDS);
86                 break;
87             case OFFLINE:
88             default:
89                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE,
90                         String.format("Gateway offline '%s'", tradfriGateway.getStatusInfo()));
91                 break;
92         }
93     }
94
95     @Override
96     public synchronized void dispose() {
97         active = false;
98         if (observeRelation != null) {
99             observeRelation.reactiveCancel();
100             observeRelation = null;
101         }
102         if (coapClient != null) {
103             coapClient.shutdown();
104         }
105         super.dispose();
106     }
107
108     @Override
109     @SuppressWarnings("null")
110     public void setStatus(ThingStatus status, ThingStatusDetail statusDetail) {
111         if (active && getBridge().getStatus() != ThingStatus.OFFLINE && status != ThingStatus.ONLINE) {
112             updateStatus(status, statusDetail);
113             // we are offline and lost our observe relation - let's try to establish the connection in 10 seconds again
114             scheduler.schedule(() -> {
115                 if (observeRelation != null) {
116                     observeRelation.reactiveCancel();
117                     observeRelation = null;
118                 }
119                 observeRelation = coapClient.startObserve(this);
120             }, 10, TimeUnit.SECONDS);
121         }
122     }
123
124     @Override
125     public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
126         super.bridgeStatusChanged(bridgeStatusInfo);
127         // the status might have changed because the bridge is completely reconfigured - so we need to re-establish
128         // our CoAP connection as well
129         if (bridgeStatusInfo.getStatus() == ThingStatus.OFFLINE) {
130             dispose();
131         } else if (bridgeStatusInfo.getStatus() == ThingStatus.ONLINE) {
132             initialize();
133         }
134     }
135
136     protected void set(String payload) {
137         logger.debug("Sending payload: {}", payload);
138         coapClient.asyncPut(payload, this, scheduler);
139     }
140
141     protected void updateDeviceProperties(TradfriDeviceData state) {
142         String firmwareVersion = state.getFirmwareVersion();
143         if (firmwareVersion != null) {
144             getThing().setProperty(PROPERTY_FIRMWARE_VERSION, firmwareVersion);
145         }
146
147         String modelId = state.getModelId();
148         if (modelId != null) {
149             getThing().setProperty(PROPERTY_MODEL_ID, modelId);
150         }
151
152         String vendor = state.getVendor();
153         if (vendor != null) {
154             getThing().setProperty(PROPERTY_VENDOR, vendor);
155         }
156     }
157 }