forked from eclipse-archived/smarthome
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TradfriGatewayHandler.java
248 lines (218 loc) · 8.98 KB
/
TradfriGatewayHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
/**
* Copyright (c) 2014-2017 by the respective copyright holders.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.smarthome.binding.tradfri.handler;
import static org.eclipse.smarthome.binding.tradfri.TradfriBindingConstants.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.eclipse.californium.core.network.CoapEndpoint;
import org.eclipse.californium.core.network.config.NetworkConfig;
import org.eclipse.californium.scandium.DTLSConnector;
import org.eclipse.californium.scandium.config.DtlsConnectorConfig;
import org.eclipse.californium.scandium.dtls.pskstore.StaticPskStore;
import org.eclipse.smarthome.binding.tradfri.GatewayConfig;
import org.eclipse.smarthome.binding.tradfri.internal.CoapCallback;
import org.eclipse.smarthome.binding.tradfri.internal.DeviceUpdateListener;
import org.eclipse.smarthome.binding.tradfri.internal.TradfriCoapClient;
import org.eclipse.smarthome.binding.tradfri.internal.TradfriCoapHandler;
import org.eclipse.smarthome.core.thing.Bridge;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.ThingStatus;
import org.eclipse.smarthome.core.thing.ThingStatusDetail;
import org.eclipse.smarthome.core.thing.binding.BaseBridgeHandler;
import org.eclipse.smarthome.core.types.Command;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
/**
* The {@link TradfriGatewayHandler} is responsible for handling commands, which are
* sent to one of the channels.
*
* @author Kai Kreuzer - Initial contribution
* @author Mario Smit - Group Handler added
*/
public class TradfriGatewayHandler extends BaseBridgeHandler {
private final Logger logger = LoggerFactory.getLogger(TradfriGatewayHandler.class);
public MyCoapCallback devices, groups;
private DTLSConnector dtlsConnector;
private CoapEndpoint endPoint;
private Set<DeviceUpdateListener> deviceUpdateListeners = new CopyOnWriteArraySet<>();
private ScheduledFuture<?> scanJob;
public TradfriGatewayHandler(Bridge bridge) {
super(bridge);
}
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
// there are no channels on the gateway yet
}
@Override
public void initialize() {
GatewayConfig configuration = getConfigAs(GatewayConfig.class);
if (configuration.host == null || configuration.host.isEmpty()) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
"Host must be specified in the configuration!");
return;
}
if (configuration.code == null || configuration.code.isEmpty()) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
"Security code must be provided in the configuration!");
return;
}
DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder(new InetSocketAddress(0));
builder.setPskStore(new StaticPskStore("", configuration.code.getBytes()));
dtlsConnector = new DTLSConnector(builder.build());
endPoint = new CoapEndpoint(dtlsConnector, NetworkConfig.getStandard());
// setup DEVICES scanner
devices = new MyCoapCallback();
devices.gatewayURI = "coaps://" + configuration.host + ":" + configuration.port + "/" + DEVICES;
try {
URI uri = new URI(devices.gatewayURI);
devices.client = new TradfriCoapClient(uri);
} catch (URISyntaxException e) {
logger.debug("Illegal gateway URI `{}`: {}", devices.gatewayURI, e.getMessage());
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
return;
}
devices.client.setEndpoint(endPoint);
// setup GROUPS scanner
groups = new MyCoapCallback();
groups.gatewayURI = "coaps://" + configuration.host + ":" + configuration.port + "/" + GROUPS;
try {
URI uri = new URI(groups.gatewayURI);
groups.client = new TradfriCoapClient(uri);
} catch (URISyntaxException e) {
logger.debug("Illegal gateway URI `{}`: {}", groups.gatewayURI, e.getMessage());
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
return;
}
groups.client.setEndpoint(endPoint);
updateStatus(ThingStatus.UNKNOWN);
// schedule a new scan every minute
scanJob = scheduler.scheduleWithFixedDelay(() -> {
devices.startScan();
groups.startScan();
}, 0, 60, TimeUnit.SECONDS);
}
@Override
public void dispose() {
if (scanJob != null) {
scanJob.cancel(true);
scanJob = null;
}
if (devices.client != null) {
devices.client.shutdown();
devices.client = null;
}
if (groups.client != null) {
groups.client.shutdown();
groups.client = null;
}
if (endPoint != null) {
endPoint.destroy();
endPoint = null;
}
super.dispose();
}
public class MyCoapCallback implements CoapCallback {
private TradfriCoapClient client;
private String gatewayURI;
MyCoapCallback() {
}
/**
* Does a request to the gateway to list all available devices/services.
* The response is received and processed by the method {@link onUpdate(JsonElement data)}.
*/
public void startScan() {
if (endPoint != null) {
client.get(new TradfriCoapHandler(this));
}
}
/**
* Returns the root URI of the gateway.
*
* @return root URI of the gateway with coaps scheme
*/
public String getGatewayURI() {
return gatewayURI;
}
/**
* Returns the coap endpoint that can be used within coap clients.
*
* @return the coap endpoint
*/
public CoapEndpoint getEndpoint() {
return endPoint;
}
@Override
public void onUpdate(JsonElement data) {
logger.debug("Gateway response: {}", data);
if (endPoint != null) {
try {
JsonArray array = data.getAsJsonArray();
for (int i = 0; i < array.size(); i++) {
requestDeviceDetails(array.get(i).getAsString());
}
} catch (JsonSyntaxException e) {
logger.debug("JSON error: {}", e.getMessage());
setStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
}
}
}
private void requestDeviceDetails(String instanceId) {
// we are reusing our coap client and merely temporarily set a sub-URI to call
client.setURI(gatewayURI + "/" + instanceId);
client.asyncGet().thenAccept(data -> {
logger.debug("Response: {}", data);
JsonObject json = new JsonParser().parse(data).getAsJsonObject();
deviceUpdateListeners.forEach(listener -> listener.onUpdate(instanceId, json));
});
// restore root URI
client.setURI(gatewayURI);
}
@Override
public void setStatus(ThingStatus status, ThingStatusDetail statusDetail) {
// are we still connected at all?
if (endPoint != null) {
updateStatus(status, statusDetail);
if (dtlsConnector != null && status == ThingStatus.OFFLINE) {
try {
dtlsConnector.stop();
dtlsConnector.start();
} catch (IOException e) {
logger.debug("Error restarting the DTLS connector: {}", e.getMessage());
}
}
}
}
}
/**
* Registers a listener, which is informed about device details.
*
* @param listener the listener to register
*/
public void registerDeviceUpdateListener(DeviceUpdateListener listener) {
this.deviceUpdateListeners.add(listener);
}
/**
* Unregisters a given listener.
*
* @param listener the listener to unregister
*/
public void unregisterDeviceUpdateListener(DeviceUpdateListener listener) {
this.deviceUpdateListeners.remove(listener);
}
}