This repository has been archived by the owner on May 7, 2020. It is now read-only.
/
HomematicBridgeHandler.java
426 lines (383 loc) · 16.3 KB
/
HomematicBridgeHandler.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
/**
* Copyright (c) 2014,2018 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.smarthome.binding.homematic.handler;
import static org.eclipse.smarthome.binding.homematic.HomematicBindingConstants.CHANNEL_TYPE_DUTY_CYCLE_RATIO;
import static org.eclipse.smarthome.core.thing.Thing.*;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.smarthome.binding.homematic.internal.common.HomematicConfig;
import org.eclipse.smarthome.binding.homematic.internal.communicator.HomematicGateway;
import org.eclipse.smarthome.binding.homematic.internal.communicator.HomematicGatewayAdapter;
import org.eclipse.smarthome.binding.homematic.internal.communicator.HomematicGatewayFactory;
import org.eclipse.smarthome.binding.homematic.internal.discovery.HomematicDeviceDiscoveryService;
import org.eclipse.smarthome.binding.homematic.internal.misc.HomematicClientException;
import org.eclipse.smarthome.binding.homematic.internal.model.HmDatapoint;
import org.eclipse.smarthome.binding.homematic.internal.model.HmDatapointConfig;
import org.eclipse.smarthome.binding.homematic.internal.model.HmDevice;
import org.eclipse.smarthome.binding.homematic.internal.model.HmGatewayInfo;
import org.eclipse.smarthome.binding.homematic.internal.type.HomematicTypeGenerator;
import org.eclipse.smarthome.binding.homematic.internal.type.UidUtils;
import org.eclipse.smarthome.config.discovery.DiscoveryService;
import org.eclipse.smarthome.core.library.types.DecimalType;
import org.eclipse.smarthome.core.thing.Bridge;
import org.eclipse.smarthome.core.thing.Channel;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.Thing;
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.thing.binding.ThingHandler;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.RefreshType;
import org.osgi.framework.ServiceRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@link HomematicBridgeHandler} is the handler for a Homematic gateway and connects it to the framework.
*
* @author Gerhard Riegler - Initial contribution
*/
public class HomematicBridgeHandler extends BaseBridgeHandler implements HomematicGatewayAdapter {
private final Logger logger = LoggerFactory.getLogger(HomematicBridgeHandler.class);
private static final long REINITIALIZE_DELAY_SECONDS = 10;
private static final int DUTY_CYCLE_RATIO_LIMIT = 99;
private static SimplePortPool portPool = new SimplePortPool();
private final Object dutyCycleRatioUpdateLock = new Object();
private HomematicConfig config;
private HomematicGateway gateway;
private final HomematicTypeGenerator typeGenerator;
private final HttpClient httpClient;
private HomematicDeviceDiscoveryService discoveryService;
private ServiceRegistration<?> discoveryServiceRegistration;
private final String ipv4Address;
private boolean isInDutyCycle = false;
private int dutyCycleRatio = 0;
public HomematicBridgeHandler(@NonNull Bridge bridge, HomematicTypeGenerator typeGenerator, String ipv4Address,
HttpClient httpClient) {
super(bridge);
this.typeGenerator = typeGenerator;
this.ipv4Address = ipv4Address;
this.httpClient = httpClient;
}
@Override
public void initialize() {
config = createHomematicConfig();
registerDeviceDiscoveryService();
final HomematicBridgeHandler instance = this;
scheduler.execute(() -> {
try {
String id = getThing().getUID().getId();
gateway = HomematicGatewayFactory.createGateway(id, config, instance, httpClient);
configureThingProperties();
gateway.initialize();
// scan for already known devices (new devices will not be discovered,
// since installMode==true is only achieved if the bridge is online
discoveryService.startScan(null);
discoveryService.waitForScanFinishing();
updateStatus(ThingStatus.ONLINE);
if (!config.getGatewayInfo().isHomegear()) {
try {
gateway.loadRssiValues();
} catch (IOException ex) {
logger.warn("Unable to load RSSI values from bridge '{}'", getThing().getUID().getId());
logger.error("{}", ex.getMessage(), ex);
}
}
gateway.startWatchdogs();
} catch (IOException ex) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, ex.getMessage());
logger.debug(
"Homematic bridge was set to OFFLINE-COMMUNICATION_ERROR due to the following exception: {}",
ex.getMessage(), ex);
dispose();
scheduleReinitialize();
}
});
}
private void configureThingProperties() {
final HmGatewayInfo info = config.getGatewayInfo();
final Map<String, String> properties = getThing().getProperties();
if (!properties.containsKey(PROPERTY_FIRMWARE_VERSION)) {
getThing().setProperty(PROPERTY_FIRMWARE_VERSION, info.getFirmware());
}
if (!properties.containsKey(PROPERTY_SERIAL_NUMBER)) {
getThing().setProperty(PROPERTY_SERIAL_NUMBER, info.getAddress());
}
if (!properties.containsKey(PROPERTY_MODEL_ID)) {
getThing().setProperty(PROPERTY_MODEL_ID, info.getType());
}
}
/**
* Schedules a reinitialization, if the Homematic gateway is not reachable at bridge startup.
*/
private void scheduleReinitialize() {
scheduler.schedule(() -> {
initialize();
}, REINITIALIZE_DELAY_SECONDS, TimeUnit.SECONDS);
}
@Override
public void dispose() {
logger.debug("Disposing bridge '{}'", getThing().getUID().getId());
super.dispose();
if (discoveryService != null) {
discoveryService.stopScan();
unregisterDeviceDiscoveryService();
}
if (gateway != null) {
gateway.dispose();
}
if (config != null) {
portPool.release(config.getXmlCallbackPort());
portPool.release(config.getBinCallbackPort());
}
}
/**
* Registers the DeviceDiscoveryService.
*/
private void registerDeviceDiscoveryService() {
if (bundleContext != null) {
logger.trace("Registering HomematicDeviceDiscoveryService for bridge '{}'", getThing().getUID().getId());
discoveryService = new HomematicDeviceDiscoveryService(this);
discoveryServiceRegistration = bundleContext.registerService(DiscoveryService.class.getName(),
discoveryService, new Hashtable<String, Object>());
discoveryService.activate();
}
}
/**
* Unregisters the DeviceDisoveryService.
*/
private void unregisterDeviceDiscoveryService() {
if (discoveryServiceRegistration != null && bundleContext != null) {
HomematicDeviceDiscoveryService service = (HomematicDeviceDiscoveryService) bundleContext
.getService(discoveryServiceRegistration.getReference());
if (service != null) {
service.deactivate();
}
discoveryServiceRegistration.unregister();
discoveryServiceRegistration = null;
discoveryService = null;
}
}
/**
* Sets the OFFLINE status for all things of this bridge that has been removed from the gateway.
*/
@SuppressWarnings("null")
public void setOfflineStatus() {
for (Thing hmThing : getThing().getThings()) {
try {
gateway.getDevice(UidUtils.getHomematicAddress(hmThing));
} catch (HomematicClientException e) {
if (hmThing.getHandler() != null) {
((HomematicThingHandler) hmThing.getHandler()).handleRemoval();
}
}
}
}
/**
* Creates the configuration for the HomematicGateway.
*/
private HomematicConfig createHomematicConfig() {
HomematicConfig homematicConfig = getThing().getConfiguration().as(HomematicConfig.class);
if (homematicConfig.getCallbackHost() == null) {
homematicConfig.setCallbackHost(this.ipv4Address);
}
if (homematicConfig.getXmlCallbackPort() == 0) {
homematicConfig.setXmlCallbackPort(portPool.getNextPort());
} else {
portPool.setInUse(homematicConfig.getXmlCallbackPort());
}
if (homematicConfig.getBinCallbackPort() == 0) {
homematicConfig.setBinCallbackPort(portPool.getNextPort());
} else {
portPool.setInUse(homematicConfig.getBinCallbackPort());
}
logger.debug("{}", homematicConfig);
return homematicConfig;
}
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
if (RefreshType.REFRESH == command) {
logger.debug("Refreshing bridge '{}'", getThing().getUID().getId());
reloadAllDeviceValues();
}
}
/**
* Returns the TypeGenerator.
*/
public HomematicTypeGenerator getTypeGenerator() {
return typeGenerator;
}
/**
* Returns the HomematicGateway.
*/
public HomematicGateway getGateway() {
return gateway;
}
/**
* Updates the thing for the given Homematic device.
*/
private void updateThing(HmDevice device) {
Thing hmThing = getThingByUID(UidUtils.generateThingUID(device, getThing()));
if (hmThing != null) {
HomematicThingHandler thingHandler = (HomematicThingHandler) hmThing.getHandler();
if (thingHandler != null) {
thingHandler.thingUpdated(hmThing);
for (Channel channel : hmThing.getChannels()) {
thingHandler.handleRefresh(channel.getUID());
}
}
}
}
@Override
public void onStateUpdated(HmDatapoint dp) {
Thing hmThing = getThingByUID(UidUtils.generateThingUID(dp.getChannel().getDevice(), getThing()));
if (hmThing != null) {
final ThingStatus status = hmThing.getStatus();
if (status == ThingStatus.ONLINE || status == ThingStatus.OFFLINE) {
HomematicThingHandler thingHandler = (HomematicThingHandler) hmThing.getHandler();
if (thingHandler != null) {
thingHandler.updateDatapointState(dp);
}
}
}
}
@Override
public HmDatapointConfig getDatapointConfig(HmDatapoint dp) {
Thing hmThing = getThingByUID(UidUtils.generateThingUID(dp.getChannel().getDevice(), getThing()));
if (hmThing != null) {
HomematicThingHandler thingHandler = (HomematicThingHandler) hmThing.getHandler();
if (thingHandler != null) {
return thingHandler.getChannelConfig(dp);
}
}
return new HmDatapointConfig();
}
@Override
public void onNewDevice(HmDevice device) {
onDeviceLoaded(device);
updateThing(device);
}
@SuppressWarnings("null")
@Override
public void onDeviceDeleted(HmDevice device) {
discoveryService.deviceRemoved(device);
updateThing(device);
Thing hmThing = getThingByUID(UidUtils.generateThingUID(device, getThing()));
if (hmThing != null && hmThing.getHandler() != null) {
((HomematicThingHandler) hmThing.getHandler()).deviceRemoved();
}
}
@Override
public void onConnectionLost() {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Connection lost");
}
@Override
public void onConnectionResumed() {
updateStatus(ThingStatus.ONLINE);
reloadAllDeviceValues();
}
@Override
public void onDeviceLoaded(HmDevice device) {
typeGenerator.generate(device);
if (discoveryService != null) {
discoveryService.deviceDiscovered(device);
}
Thing hmThing = getThingByUID(UidUtils.generateThingUID(device, getThing()));
if (hmThing != null) {
HomematicThingHandler thingHandler = (HomematicThingHandler) hmThing.getHandler();
if (thingHandler != null) {
thingHandler.deviceLoaded(device);
}
}
}
@Override
public void onDutyCycleRatioUpdate(int dutyCycleRatio) {
synchronized (dutyCycleRatioUpdateLock) {
this.dutyCycleRatio = dutyCycleRatio;
Channel dutyCycleRatioChannel = thing.getChannel(CHANNEL_TYPE_DUTY_CYCLE_RATIO);
if (dutyCycleRatioChannel != null) {
this.updateState(dutyCycleRatioChannel.getUID(), new DecimalType(dutyCycleRatio));
}
if (!isInDutyCycle && dutyCycleRatio >= DUTY_CYCLE_RATIO_LIMIT) {
logger.info("Duty cycle threshold exceeded by homematic bridge {}, it will go OFFLINE.",
thing.getUID());
isInDutyCycle = true;
this.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.DUTY_CYCLE);
} else if (isInDutyCycle && dutyCycleRatio < DUTY_CYCLE_RATIO_LIMIT) {
logger.info("Homematic bridge {} fell below duty cycle threshold and will come ONLINE again.",
thing.getUID());
isInDutyCycle = false;
this.updateStatus(ThingStatus.ONLINE);
}
}
}
/**
* Returns the last value for the duty cycle ratio that was retrieved from the homematic gateway.
*
* @return The duty cycle ratio of the gateway
*/
public int getDutyCycleRatio() {
return dutyCycleRatio;
}
@Override
public void reloadDeviceValues(HmDevice device) {
updateThing(device);
if (device.isGatewayExtras()) {
typeGenerator.generate(device);
}
}
@Override
public void reloadAllDeviceValues() {
for (Thing hmThing : getThing().getThings()) {
try {
HmDevice device = gateway.getDevice(UidUtils.getHomematicAddress(hmThing));
gateway.triggerDeviceValuesReload(device);
} catch (HomematicClientException ex) {
logger.warn("{}", ex.getMessage());
}
}
}
@Override
public void childHandlerDisposed(ThingHandler childHandler, Thing childThing) {
if (((HomematicThingHandler) childHandler).isDeletionPending()) {
deleteFromGateway(UidUtils.getHomematicAddress(childThing), false, true, false);
}
}
/**
* Updates the {@link HmDatapoint} by reloading the value from the homematic gateway.
*
* @param dp The HmDatapoint that shall be updated
* @throws IOException If there is a problem while communicating to the gateway
*/
public void updateDatapoint(HmDatapoint dp) throws IOException {
getGateway().loadDatapointValue(dp);
}
/**
* Deletes a device from the gateway.
*
* @param address The address of the device to be deleted
* @param reset <i>true</i> will perform a factory reset on the device before deleting it.
* @param force <i>true</i> will delete the device even if it is not reachable.
* @param defer <i>true</i> will delete the device once it becomes available.
*/
public void deleteFromGateway(String address, boolean reset, boolean force, boolean defer) {
scheduler.submit(() -> {
logger.debug("Deleting the device '{}' from gateway '{}'", address, getBridge());
getGateway().deleteDevice(address, reset, force, defer);
});
}
}