]> git.basschouten.com Git - openhab-addons.git/blob
542fac8073e2a9e0b37c23f6911c164714a503c2
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.homematic.internal.handler;
14
15 import static org.openhab.binding.homematic.internal.HomematicBindingConstants.*;
16 import static org.openhab.binding.homematic.internal.misc.HomematicConstants.*;
17
18 import java.io.IOException;
19 import java.math.BigDecimal;
20 import java.util.ArrayList;
21 import java.util.HashMap;
22 import java.util.Iterator;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.Objects;
27 import java.util.concurrent.Future;
28
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.openhab.binding.homematic.internal.HomematicBindingConstants;
31 import org.openhab.binding.homematic.internal.common.HomematicConfig;
32 import org.openhab.binding.homematic.internal.communicator.HomematicGateway;
33 import org.openhab.binding.homematic.internal.converter.ConverterException;
34 import org.openhab.binding.homematic.internal.converter.ConverterFactory;
35 import org.openhab.binding.homematic.internal.converter.ConverterTypeException;
36 import org.openhab.binding.homematic.internal.converter.TypeConverter;
37 import org.openhab.binding.homematic.internal.misc.HomematicClientException;
38 import org.openhab.binding.homematic.internal.misc.HomematicConstants;
39 import org.openhab.binding.homematic.internal.model.HmChannel;
40 import org.openhab.binding.homematic.internal.model.HmDatapoint;
41 import org.openhab.binding.homematic.internal.model.HmDatapointConfig;
42 import org.openhab.binding.homematic.internal.model.HmDatapointInfo;
43 import org.openhab.binding.homematic.internal.model.HmDevice;
44 import org.openhab.binding.homematic.internal.model.HmParamsetType;
45 import org.openhab.binding.homematic.internal.type.HomematicChannelTypeProvider;
46 import org.openhab.binding.homematic.internal.type.HomematicTypeGeneratorImpl;
47 import org.openhab.binding.homematic.internal.type.MetadataUtils;
48 import org.openhab.binding.homematic.internal.type.UidUtils;
49 import org.openhab.core.config.core.Configuration;
50 import org.openhab.core.config.core.validation.ConfigValidationException;
51 import org.openhab.core.library.types.OnOffType;
52 import org.openhab.core.library.types.StopMoveType;
53 import org.openhab.core.thing.Bridge;
54 import org.openhab.core.thing.Channel;
55 import org.openhab.core.thing.ChannelUID;
56 import org.openhab.core.thing.Thing;
57 import org.openhab.core.thing.ThingStatus;
58 import org.openhab.core.thing.ThingStatusDetail;
59 import org.openhab.core.thing.binding.BaseThingHandler;
60 import org.openhab.core.thing.binding.ThingHandler;
61 import org.openhab.core.thing.binding.builder.ChannelBuilder;
62 import org.openhab.core.thing.type.ChannelType;
63 import org.openhab.core.thing.type.ChannelTypeUID;
64 import org.openhab.core.types.Command;
65 import org.openhab.core.types.RefreshType;
66 import org.openhab.core.types.State;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
69
70 /**
71  * The {@link HomematicThingHandler} is responsible for handling commands, which are sent to one of the channels.
72  *
73  * @author Gerhard Riegler - Initial contribution
74  */
75 public class HomematicThingHandler extends BaseThingHandler {
76     private final Logger logger = LoggerFactory.getLogger(HomematicThingHandler.class);
77     private final HomematicChannelTypeProvider channelTypeProvider;
78     private Future<?> initFuture;
79     private final Object initLock = new Object();
80     private volatile boolean deviceDeletionPending = false;
81
82     public HomematicThingHandler(Thing thing, HomematicChannelTypeProvider channelTypeProvider) {
83         super(thing);
84         this.channelTypeProvider = channelTypeProvider;
85     }
86
87     @Override
88     public void initialize() {
89         if (initFuture != null) {
90             return;
91         }
92
93         initFuture = scheduler.submit(() -> {
94             initFuture = null;
95             try {
96                 synchronized (initLock) {
97                     doInitializeInBackground();
98                 }
99             } catch (HomematicClientException ex) {
100                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, ex.getMessage());
101             } catch (IOException ex) {
102                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, ex.getMessage());
103             } catch (GatewayNotAvailableException ex) {
104                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, ex.getMessage());
105             } catch (Exception ex) {
106                 logger.error("{}", ex.getMessage(), ex);
107                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, ex.getMessage());
108             }
109         });
110     }
111
112     private void doInitializeInBackground() throws GatewayNotAvailableException, HomematicClientException, IOException {
113         HomematicGateway gateway = getHomematicGateway();
114         HmDevice device = gateway.getDevice(UidUtils.getHomematicAddress(getThing()));
115         HmChannel channelZero = device.getChannel(0);
116         loadHomematicChannelValues(channelZero);
117         updateStatus(device);
118         logger.debug("Initializing thing '{}' from gateway '{}'", getThing().getUID(), gateway.getId());
119
120         // update properties
121         Map<String, String> properties = editProperties();
122         setProperty(properties, channelZero, PROPERTY_BATTERY_TYPE, VIRTUAL_DATAPOINT_NAME_BATTERY_TYPE);
123         setProperty(properties, channelZero, Thing.PROPERTY_FIRMWARE_VERSION, VIRTUAL_DATAPOINT_NAME_FIRMWARE);
124         setProperty(properties, channelZero, Thing.PROPERTY_SERIAL_NUMBER, device.getAddress());
125         setProperty(properties, channelZero, PROPERTY_AES_KEY, DATAPOINT_NAME_AES_KEY);
126         updateProperties(properties);
127
128         // update data point list for reconfigurable channels
129         for (HmChannel channel : device.getChannels()) {
130             if (channel.isReconfigurable()) {
131                 loadHomematicChannelValues(channel);
132                 if (channel.checkForChannelFunctionChange()) {
133                     gateway.updateChannelValueDatapoints(channel);
134                 }
135             }
136         }
137
138         // update configurations
139         Configuration config = editConfiguration();
140         for (HmChannel channel : device.getChannels()) {
141             loadHomematicChannelValues(channel);
142             for (HmDatapoint dp : channel.getDatapoints()) {
143                 if (dp.getParamsetType() == HmParamsetType.MASTER) {
144                     config.put(MetadataUtils.getParameterName(dp), getValueForConfiguration(dp));
145                 }
146             }
147         }
148         updateConfiguration(config);
149
150         boolean channelsChanged = false;
151
152         // update thing channel list for reconfigurable channels (relies on the new value of the
153         // CHANNEL_FUNCTION datapoint fetched during configuration update)
154         List<Channel> thingChannels = new ArrayList<>(getThing().getChannels());
155
156         if (thingChannels.isEmpty()) {
157             for (HmChannel channel : device.getChannels()) {
158                 for (HmDatapoint dp : channel.getDatapoints()) {
159                     if (HomematicTypeGeneratorImpl.isIgnoredDatapoint(dp)
160                             || dp.getParamsetType() != HmParamsetType.VALUES) {
161                         continue;
162                     }
163                     ChannelUID channelUID = UidUtils.generateChannelUID(dp, getThing().getUID());
164                     if (containsChannel(thingChannels, channelUID)) {
165                         // Channel is already present
166                         continue;
167                     }
168
169                     ChannelTypeUID channelTypeUID = UidUtils.generateChannelTypeUID(dp);
170                     ChannelType channelType = channelTypeProvider.getInternalChannelType(channelTypeUID);
171                     if (channelType == null) {
172                         channelType = HomematicTypeGeneratorImpl.createChannelType(dp, channelTypeUID);
173                         channelTypeProvider.addChannelType(channelType);
174                     }
175
176                     Channel thingChannel = ChannelBuilder.create(channelUID, MetadataUtils.getItemType(dp))
177                             .withLabel(MetadataUtils.getLabel(dp))
178                             .withDescription(MetadataUtils.getDatapointDescription(dp)).withType(channelType.getUID())
179                             .build();
180                     thingChannels.add(thingChannel);
181
182                     logger.debug(
183                             "Updated value datapoints for channel {} of device '{}' (function {}), now has {} datapoints",
184                             channel, channel.getDevice().getAddress(), channel.getCurrentFunction(),
185                             channel.getDatapoints().size());
186                 }
187             }
188             channelsChanged = true;
189         }
190
191         if (updateDynamicChannelList(device, thingChannels)) {
192             channelsChanged = true;
193         }
194
195         if (channelsChanged) {
196             updateThing(editThing().withChannels(thingChannels).build());
197         }
198
199         thingChannels.forEach(channel -> {
200             if (isLinked(channel.getUID())) {
201                 channelLinked(channel.getUID());
202             }
203         });
204     }
205
206     /**
207      * Update the given thing channel list to reflect the device's current datapoint set
208      *
209      * @return true if the list was modified, false if it was not modified
210      */
211     private boolean updateDynamicChannelList(HmDevice device, List<Channel> thingChannels) {
212         boolean changed = false;
213         for (HmChannel channel : device.getChannels()) {
214             if (!channel.isReconfigurable()) {
215                 continue;
216             }
217             final String expectedFunction = channel
218                     .getDatapoint(HmParamsetType.MASTER, HomematicConstants.DATAPOINT_NAME_CHANNEL_FUNCTION)
219                     .getOptionValue();
220             final String propertyName = String.format(PROPERTY_DYNAMIC_FUNCTION_FORMAT, channel.getNumber());
221
222             // remove thing channels that were configured for a different function
223             Iterator<Channel> channelIter = thingChannels.iterator();
224             while (channelIter.hasNext()) {
225                 Map<String, String> properties = channelIter.next().getProperties();
226                 String function = properties.get(propertyName);
227                 if (function != null && !function.equals(expectedFunction)) {
228                     channelIter.remove();
229                     changed = true;
230                 }
231             }
232             for (HmDatapoint dp : channel.getDatapoints()) {
233                 if (HomematicTypeGeneratorImpl.isIgnoredDatapoint(dp)
234                         || dp.getParamsetType() != HmParamsetType.VALUES) {
235                     continue;
236                 }
237                 ChannelUID channelUID = UidUtils.generateChannelUID(dp, getThing().getUID());
238                 if (containsChannel(thingChannels, channelUID)) {
239                     // Channel is already present -> channel configuration likely hasn't changed
240                     continue;
241                 }
242
243                 Map<String, String> channelProps = new HashMap<>();
244                 channelProps.put(propertyName, expectedFunction);
245
246                 ChannelTypeUID channelTypeUID = UidUtils.generateChannelTypeUID(dp);
247                 ChannelType channelType = channelTypeProvider.getInternalChannelType(channelTypeUID);
248                 if (channelType == null) {
249                     channelType = HomematicTypeGeneratorImpl.createChannelType(dp, channelTypeUID);
250                     channelTypeProvider.addChannelType(channelType);
251                 }
252
253                 Channel thingChannel = ChannelBuilder.create(channelUID, MetadataUtils.getItemType(dp))
254                         .withProperties(channelProps).withLabel(MetadataUtils.getLabel(dp))
255                         .withDescription(MetadataUtils.getDatapointDescription(dp)).withType(channelType.getUID())
256                         .build();
257                 thingChannels.add(thingChannel);
258                 changed = true;
259             }
260         }
261
262         return changed;
263     }
264
265     /**
266      * Checks whether the given list includes a channel with the given UID
267      */
268     private static boolean containsChannel(List<Channel> channels, ChannelUID channelUID) {
269         for (Channel channel : channels) {
270             ChannelUID uid = channel.getUID();
271             if (Objects.equals(channelUID.getGroupId(), uid.getGroupId())
272                     && Objects.equals(channelUID.getId(), uid.getId())) {
273                 return true;
274             }
275         }
276         return false;
277     }
278
279     /**
280      * Sets a thing property with a datapoint value.
281      */
282     private void setProperty(Map<String, String> properties, HmChannel channelZero, String propertyName,
283             String datapointName) {
284         HmDatapoint dp = channelZero
285                 .getDatapoint(new HmDatapointInfo(HmParamsetType.VALUES, channelZero, datapointName));
286         if (dp != null) {
287             properties.put(propertyName, Objects.toString(dp.getValue(), ""));
288         }
289     }
290
291     @Override
292     public void channelLinked(ChannelUID channelUID) {
293         handleRefresh(channelUID);
294     }
295
296     /**
297      * Updates the state of the given channel.
298      */
299     protected void handleRefresh(ChannelUID channelUID) {
300         try {
301             if (thing.getStatus() == ThingStatus.ONLINE) {
302                 logger.debug("Updating channel '{}' from thing id '{}'", channelUID, getThing().getUID().getId());
303                 updateChannelState(channelUID);
304             }
305         } catch (Exception ex) {
306             logger.warn("{}", ex.getMessage());
307         }
308     }
309
310     @Override
311     public void handleCommand(ChannelUID channelUID, Command command) {
312         logger.debug("Received command '{}' for channel '{}'", command, channelUID);
313         HmDatapoint dp = null;
314         try {
315             HomematicGateway gateway = getHomematicGateway();
316             HmDatapointInfo dpInfo = UidUtils.createHmDatapointInfo(channelUID);
317             if (RefreshType.REFRESH == command) {
318                 logger.debug("Refreshing {}", dpInfo);
319                 dpInfo = new HmDatapointInfo(dpInfo.getAddress(), HmParamsetType.VALUES, 0,
320                         VIRTUAL_DATAPOINT_NAME_RELOAD_FROM_GATEWAY);
321                 dp = gateway.getDatapoint(dpInfo);
322                 sendDatapoint(dp, new HmDatapointConfig(), Boolean.TRUE);
323             } else {
324                 Channel channel = getThing().getChannel(channelUID.getId());
325                 if (channel == null) {
326                     logger.warn("Channel '{}' not found in thing '{}' on gateway '{}'", channelUID, getThing().getUID(),
327                             gateway.getId());
328                 } else {
329                     if (StopMoveType.STOP == command && DATAPOINT_NAME_LEVEL.equals(dpInfo.getName())) {
330                         // special case with stop type (rollershutter)
331                         dpInfo.setName(DATAPOINT_NAME_STOP);
332                         HmDatapoint stopDp = gateway.getDatapoint(dpInfo);
333                         ChannelUID stopChannelUID = UidUtils.generateChannelUID(stopDp, getThing().getUID());
334                         handleCommand(stopChannelUID, OnOffType.ON);
335                     } else {
336                         dp = gateway.getDatapoint(dpInfo);
337                         TypeConverter<?> converter = ConverterFactory.createConverter(channel.getAcceptedItemType());
338                         Object newValue = converter.convertToBinding(command, dp);
339                         HmDatapointConfig config = getChannelConfig(channel, dp);
340                         sendDatapoint(dp, config, newValue);
341                     }
342                 }
343             }
344         } catch (HomematicClientException | GatewayNotAvailableException ex) {
345             logger.warn("{}", ex.getMessage());
346         } catch (IOException ex) {
347             if (dp != null && dp.getChannel().getDevice().isOffline()) {
348                 logger.warn("Device '{}' is OFFLINE, can't send command '{}' for channel '{}'",
349                         dp.getChannel().getDevice().getAddress(), command, channelUID);
350                 logger.trace("{}", ex.getMessage(), ex);
351             } else {
352                 logger.error("{}", ex.getMessage(), ex);
353             }
354         } catch (ConverterTypeException ex) {
355             logger.warn("{}, please check the item type and the commands in your scripts", ex.getMessage());
356         } catch (Exception ex) {
357             logger.error("{}", ex.getMessage(), ex);
358         }
359     }
360
361     private void sendDatapoint(HmDatapoint dp, HmDatapointConfig config, Object newValue)
362             throws IOException, HomematicClientException, GatewayNotAvailableException {
363         String rxMode = getRxModeForDatapointTransmission(dp.getName(), dp.getValue(), newValue);
364         getHomematicGateway().sendDatapoint(dp, config, newValue, rxMode);
365     }
366
367     /**
368      * Returns the rx mode that shall be used for transmitting a new value of a datapoint to the device. The
369      * HomematicThingHandler always uses the default rx mode; custom thing handlers can override this method to
370      * adjust the rx mode.
371      *
372      * @param datapointName The datapoint that will be updated on the device
373      * @param currentValue The current value of the datapoint
374      * @param newValue The value that will be sent to the device
375      * @return The rxMode ({@link HomematicBindingConstants#RX_BURST_MODE "BURST"} for burst mode,
376      *         {@link HomematicBindingConstants#RX_WAKEUP_MODE "WAKEUP"} for wakeup mode, or null for the default mode)
377      */
378     protected String getRxModeForDatapointTransmission(String datapointName, Object currentValue, Object newValue) {
379         return null;
380     }
381
382     /**
383      * Evaluates the channel and datapoint for this channelUID and updates the state of the channel.
384      */
385     private void updateChannelState(ChannelUID channelUID)
386             throws GatewayNotAvailableException, HomematicClientException, IOException, ConverterException {
387         HomematicGateway gateway = getHomematicGateway();
388         HmDatapointInfo dpInfo = UidUtils.createHmDatapointInfo(channelUID);
389         HmDatapoint dp = gateway.getDatapoint(dpInfo);
390         Channel channel = getThing().getChannel(channelUID.getId());
391         updateChannelState(dp, channel);
392     }
393
394     /**
395      * Sets the configuration or evaluates the channel for this datapoint and updates the state of the channel.
396      */
397     protected void updateDatapointState(HmDatapoint dp) {
398         try {
399             updateStatus(dp.getChannel().getDevice());
400
401             if (dp.getParamsetType() == HmParamsetType.MASTER) {
402                 // update configuration
403                 Configuration config = editConfiguration();
404                 config.put(MetadataUtils.getParameterName(dp), getValueForConfiguration(dp));
405                 updateConfiguration(config);
406             } else if (!HomematicTypeGeneratorImpl.isIgnoredDatapoint(dp)) {
407                 // update channel
408                 ChannelUID channelUID = UidUtils.generateChannelUID(dp, thing.getUID());
409                 Channel channel = thing.getChannel(channelUID.getId());
410                 if (channel != null) {
411                     updateChannelState(dp, channel);
412                 } else {
413                     logger.warn("Channel not found for datapoint '{}'", new HmDatapointInfo(dp));
414                 }
415             }
416         } catch (GatewayNotAvailableException ex) {
417             // ignore
418         } catch (Exception ex) {
419             logger.error("{}", ex.getMessage(), ex);
420         }
421     }
422
423     private @Nullable Object getValueForConfiguration(HmDatapoint dp) {
424         if (dp.getValue() == null) {
425             return null;
426         }
427         if (dp.isEnumType()) {
428             return dp.getOptionValue();
429         }
430         if (dp.isNumberType()) {
431             // For number datapoints that are only used depending on the value of other datapoints,
432             // the CCU may return invalid (out of range) values if the datapoint currently is not in use.
433             // Make sure to not invalidate the whole configuration by returning the datapoint's default
434             // value in that case.
435             final boolean minValid, maxValid;
436             if (dp.isFloatType()) {
437                 Double numValue = dp.getDoubleValue();
438                 minValid = dp.getMinValue() == null || numValue >= dp.getMinValue().doubleValue();
439                 maxValid = dp.getMaxValue() == null || numValue <= dp.getMaxValue().doubleValue();
440             } else {
441                 Integer numValue = dp.getIntegerValue();
442                 minValid = dp.getMinValue() == null || numValue >= dp.getMinValue().intValue();
443                 maxValid = dp.getMaxValue() == null || numValue <= dp.getMaxValue().intValue();
444             }
445             if (minValid && maxValid) {
446                 return dp.getValue();
447             }
448             logger.warn("Value for datapoint {} is outside of valid range, using default value for config.", dp);
449             return dp.getDefaultValue();
450         }
451         return dp.getValue();
452     }
453
454     /**
455      * Converts the value of the datapoint to a State, updates the channel and also sets the thing status if necessary.
456      */
457     private void updateChannelState(final HmDatapoint dp, Channel channel)
458             throws IOException, GatewayNotAvailableException, ConverterException {
459         if (dp.isTrigger()) {
460             final Object value = dp.getValue();
461             if (value != null && !value.equals(dp.getPreviousValue())) {
462                 triggerChannel(channel.getUID(), value.toString());
463             }
464         } else if (isLinked(channel)) {
465             loadHomematicChannelValues(dp.getChannel());
466
467             TypeConverter<?> converter = ConverterFactory.createConverter(channel.getAcceptedItemType());
468             State state = converter.convertFromBinding(dp);
469             if (state != null) {
470                 updateState(channel.getUID(), state);
471             } else {
472                 logger.debug("Failed to get converted state from datapoint '{}'", dp.getName());
473             }
474         }
475     }
476
477     /**
478      * Loads all values for the given Homematic channel if it is not initialized.
479      */
480     private void loadHomematicChannelValues(HmChannel hmChannel) throws GatewayNotAvailableException, IOException {
481         if (!hmChannel.isInitialized()) {
482             synchronized (this) {
483                 if (!hmChannel.isInitialized()) {
484                     try {
485                         getHomematicGateway().loadChannelValues(hmChannel);
486                     } catch (IOException ex) {
487                         if (hmChannel.getDevice().isOffline()) {
488                             logger.warn("Device '{}' is OFFLINE, can't update channel '{}'",
489                                     hmChannel.getDevice().getAddress(), hmChannel.getNumber());
490                         } else {
491                             throw ex;
492                         }
493                     }
494                 }
495             }
496         }
497     }
498
499     /**
500      * Updates the thing status based on device status.
501      */
502     private void updateStatus(HmDevice device) throws GatewayNotAvailableException, IOException {
503         loadHomematicChannelValues(device.getChannel(0));
504
505         ThingStatus oldStatus = thing.getStatus();
506         if (oldStatus == ThingStatus.UNINITIALIZED) {
507             return;
508         }
509         ThingStatus newStatus = ThingStatus.ONLINE;
510         ThingStatusDetail newDetail = ThingStatusDetail.NONE;
511
512         if ((getBridge() != null) && (getBridge().getStatus() == ThingStatus.OFFLINE)) {
513             newStatus = ThingStatus.OFFLINE;
514             newDetail = ThingStatusDetail.BRIDGE_OFFLINE;
515         } else if (device.isFirmwareUpdating()) {
516             newStatus = ThingStatus.OFFLINE;
517             newDetail = ThingStatusDetail.FIRMWARE_UPDATING;
518         } else if (device.isUnreach()) {
519             newStatus = ThingStatus.OFFLINE;
520             newDetail = ThingStatusDetail.COMMUNICATION_ERROR;
521         } else if (device.isConfigPending() || device.isUpdatePending()) {
522             newDetail = ThingStatusDetail.CONFIGURATION_PENDING;
523         }
524
525         if (thing.getStatus() != newStatus || thing.getStatusInfo().getStatusDetail() != newDetail) {
526             updateStatus(newStatus, newDetail);
527         }
528         if (oldStatus == ThingStatus.OFFLINE && newStatus == ThingStatus.ONLINE) {
529             initialize();
530         }
531     }
532
533     /**
534      * Returns true, if the channel is linked at least to one item.
535      */
536     private boolean isLinked(Channel channel) {
537         return channel != null && super.isLinked(channel.getUID().getId());
538     }
539
540     /**
541      * Returns the channel config for the given datapoint.
542      */
543     protected HmDatapointConfig getChannelConfig(HmDatapoint dp) {
544         ChannelUID channelUid = UidUtils.generateChannelUID(dp, getThing().getUID());
545         Channel channel = getThing().getChannel(channelUid.getId());
546         return channel != null ? getChannelConfig(channel, dp) : new HmDatapointConfig();
547     }
548
549     /**
550      * Returns the config for a channel.
551      */
552     private HmDatapointConfig getChannelConfig(Channel channel, HmDatapoint dp) {
553         return channel.getConfiguration().as(HmDatapointConfig.class);
554     }
555
556     /**
557      * Returns the Homematic gateway if the bridge is available.
558      */
559     private HomematicGateway getHomematicGateway() throws GatewayNotAvailableException {
560         final Bridge bridge = getBridge();
561         if (bridge != null) {
562             HomematicBridgeHandler bridgeHandler = (HomematicBridgeHandler) bridge.getHandler();
563             if (bridgeHandler != null && bridgeHandler.getGateway() != null) {
564                 return bridgeHandler.getGateway();
565             }
566         }
567
568         throw new GatewayNotAvailableException("HomematicGateway not yet available!");
569     }
570
571     @Override
572     public void handleConfigurationUpdate(Map<String, Object> configurationParameters)
573             throws ConfigValidationException {
574         super.handleConfigurationUpdate(configurationParameters);
575
576         try {
577             HomematicGateway gateway = getHomematicGateway();
578             HmDevice device = gateway.getDevice(UidUtils.getHomematicAddress(getThing()));
579
580             for (Entry<String, Object> configurationParameter : configurationParameters.entrySet()) {
581                 String key = configurationParameter.getKey();
582                 Object newValue = configurationParameter.getValue();
583
584                 if (key.startsWith("HMP_")) {
585                     key = key.substring(4);
586                     int sepPos = key.indexOf("_");
587                     Integer channelNumber = Integer.valueOf(key.substring(0, sepPos));
588                     String dpName = key.substring(sepPos + 1);
589
590                     HmDatapointInfo dpInfo = new HmDatapointInfo(device.getAddress(), HmParamsetType.MASTER,
591                             channelNumber, dpName);
592                     HmDatapoint dp = device.getChannel(channelNumber).getDatapoint(dpInfo);
593
594                     if (dp != null) {
595                         try {
596                             if (newValue != null) {
597                                 if (newValue instanceof BigDecimal) {
598                                     final BigDecimal decimal = (BigDecimal) newValue;
599                                     if (dp.isIntegerType()) {
600                                         newValue = decimal.intValue();
601                                     } else if (dp.isFloatType()) {
602                                         newValue = decimal.doubleValue();
603                                     }
604                                 } else if (newValue instanceof String && dp.isEnumType()) {
605                                     newValue = dp.getOptionIndex((String) newValue);
606                                 }
607                                 if (!Objects.equals(dp.getValue(), newValue)) {
608                                     sendDatapoint(dp, new HmDatapointConfig(), newValue);
609                                 }
610                             }
611                         } catch (IOException ex) {
612                             logger.error("Error setting thing property {}: {}", dpInfo, ex.getMessage());
613                         }
614                     } else {
615                         logger.error("Can't find datapoint for thing property {}", dpInfo);
616                     }
617                 }
618             }
619             gateway.triggerDeviceValuesReload(device);
620         } catch (HomematicClientException | GatewayNotAvailableException ex) {
621             logger.error("Error setting thing properties: {}", ex.getMessage(), ex);
622         }
623     }
624
625     @SuppressWarnings("null")
626     @Override
627     public synchronized void handleRemoval() {
628         final Bridge bridge;
629         final ThingHandler handler;
630
631         if ((bridge = getBridge()) == null || (handler = bridge.getHandler()) == null) {
632             super.handleRemoval();
633             return;
634         }
635
636         final HomematicConfig config = bridge.getConfiguration().as(HomematicConfig.class);
637         final boolean factoryResetOnDeletion = config.isFactoryResetOnDeletion();
638         final boolean unpairOnDeletion = factoryResetOnDeletion || config.isUnpairOnDeletion();
639
640         if (unpairOnDeletion) {
641             deviceDeletionPending = true;
642             ((HomematicBridgeHandler) handler).deleteFromGateway(UidUtils.getHomematicAddress(thing),
643                     factoryResetOnDeletion, false, true);
644         } else {
645             super.handleRemoval();
646         }
647     }
648
649     /**
650      * Called by the bridgeHandler when this device has been removed from the gateway.
651      */
652     public synchronized void deviceRemoved() {
653         deviceDeletionPending = false;
654         if (getThing().getStatus() == ThingStatus.REMOVING) {
655             // thing removal was initiated
656             updateStatus(ThingStatus.REMOVED);
657         } else {
658             // device removal was initiated on homematic side, thing is not removed
659             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.GONE);
660         }
661     }
662
663     /**
664      * Called by the bridgeHandler when the device for this thing has been added to the gateway.
665      * This is used to reconnect a device that was previously unpaired.
666      *
667      * @param device The device that has been added to the gateway
668      */
669     public void deviceLoaded(HmDevice device) {
670         try {
671             updateStatus(device);
672         } catch (GatewayNotAvailableException ex) {
673             // ignore
674         } catch (IOException ex) {
675             logger.warn("Could not reinitialize the device '{}': {}", device.getAddress(), ex.getMessage(), ex);
676         }
677     }
678
679     /**
680      * Returns whether the device deletion is pending.
681      *
682      * @return true, if the deletion of this device on its gateway has been triggered but has not yet completed
683      */
684     public synchronized boolean isDeletionPending() {
685         return deviceDeletionPending;
686     }
687 }