]> git.basschouten.com Git - openhab-addons.git/blob
38666b54d8caf2ccfd24c33ab54b4efb4244e6f2
[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.avmfritz.internal.handler;
14
15 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.BINDING_ID;
16 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_ACTUALTEMP;
17 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_BATTERY;
18 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_BATTERY_LOW;
19 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_BRIGHTNESS;
20 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_COLOR;
21 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_COLORTEMPERATURE;
22 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_COLORTEMPERATURE_ABS;
23 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_COMFORTTEMP;
24 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_CONTACT_STATE;
25 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_DEVICE_LOCKED;
26 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_ECOTEMP;
27 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_ENERGY;
28 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_HUMIDITY;
29 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_LAST_CHANGE;
30 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_LOCKED;
31 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_MODE;
32 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_NEXTTEMP;
33 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_NEXT_CHANGE;
34 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_OBSTRUCTION_ALARM;
35 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_ON_OFF;
36 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_OUTLET;
37 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_POWER;
38 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_RADIATOR_MODE;
39 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_ROLLERSHUTTER;
40 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_SETTEMP;
41 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_TEMPERATURE;
42 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_TEMPERATURE_ALARM;
43 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CHANNEL_VOLTAGE;
44 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.CONFIG_CHANNEL_TEMP_OFFSET;
45 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.MODE_BOOST;
46 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.MODE_COMFORT;
47 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.MODE_ECO;
48 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.MODE_OFF;
49 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.MODE_ON;
50 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.MODE_UNKNOWN;
51 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.MODE_WINDOW_OPEN;
52 import static org.openhab.binding.avmfritz.internal.dto.HeatingModel.TEMP_FRITZ_MAX;
53 import static org.openhab.binding.avmfritz.internal.dto.HeatingModel.TEMP_FRITZ_OFF;
54 import static org.openhab.binding.avmfritz.internal.dto.HeatingModel.TEMP_FRITZ_ON;
55 import static org.openhab.binding.avmfritz.internal.dto.HeatingModel.TEMP_FRITZ_UNDEFINED;
56 import static org.openhab.binding.avmfritz.internal.dto.HeatingModel.fromCelsius;
57 import static org.openhab.binding.avmfritz.internal.dto.HeatingModel.normalizeCelsius;
58 import static org.openhab.binding.avmfritz.internal.dto.HeatingModel.toCelsius;
59
60 import java.math.BigDecimal;
61 import java.time.Instant;
62 import java.time.ZoneId;
63 import java.time.ZonedDateTime;
64 import java.util.Map;
65
66 import javax.measure.quantity.Temperature;
67
68 import org.eclipse.jdt.annotation.NonNullByDefault;
69 import org.eclipse.jdt.annotation.Nullable;
70 import org.openhab.binding.avmfritz.internal.config.AVMFritzDeviceConfiguration;
71 import org.openhab.binding.avmfritz.internal.dto.AVMFritzBaseModel;
72 import org.openhab.binding.avmfritz.internal.dto.AlertModel;
73 import org.openhab.binding.avmfritz.internal.dto.BatteryModel;
74 import org.openhab.binding.avmfritz.internal.dto.ColorControlModel;
75 import org.openhab.binding.avmfritz.internal.dto.DeviceModel;
76 import org.openhab.binding.avmfritz.internal.dto.HeatingModel;
77 import org.openhab.binding.avmfritz.internal.dto.HeatingModel.NextChangeModel;
78 import org.openhab.binding.avmfritz.internal.dto.HumidityModel;
79 import org.openhab.binding.avmfritz.internal.dto.LevelControlModel;
80 import org.openhab.binding.avmfritz.internal.dto.PowerMeterModel;
81 import org.openhab.binding.avmfritz.internal.dto.SimpleOnOffModel;
82 import org.openhab.binding.avmfritz.internal.dto.SwitchModel;
83 import org.openhab.binding.avmfritz.internal.dto.TemperatureModel;
84 import org.openhab.binding.avmfritz.internal.hardware.FritzAhaStatusListener;
85 import org.openhab.binding.avmfritz.internal.hardware.FritzAhaWebInterface;
86 import org.openhab.binding.avmfritz.internal.hardware.callbacks.FritzAhaSetBlindTargetCallback.BlindCommand;
87 import org.openhab.core.config.core.Configuration;
88 import org.openhab.core.library.types.DateTimeType;
89 import org.openhab.core.library.types.DecimalType;
90 import org.openhab.core.library.types.HSBType;
91 import org.openhab.core.library.types.IncreaseDecreaseType;
92 import org.openhab.core.library.types.OnOffType;
93 import org.openhab.core.library.types.OpenClosedType;
94 import org.openhab.core.library.types.PercentType;
95 import org.openhab.core.library.types.QuantityType;
96 import org.openhab.core.library.types.StopMoveType;
97 import org.openhab.core.library.types.StringType;
98 import org.openhab.core.library.types.UpDownType;
99 import org.openhab.core.library.unit.SIUnits;
100 import org.openhab.core.library.unit.Units;
101 import org.openhab.core.thing.Bridge;
102 import org.openhab.core.thing.Channel;
103 import org.openhab.core.thing.ChannelUID;
104 import org.openhab.core.thing.DefaultSystemChannelTypeProvider;
105 import org.openhab.core.thing.Thing;
106 import org.openhab.core.thing.ThingStatus;
107 import org.openhab.core.thing.ThingStatusDetail;
108 import org.openhab.core.thing.ThingUID;
109 import org.openhab.core.thing.binding.BaseThingHandler;
110 import org.openhab.core.thing.binding.BridgeHandler;
111 import org.openhab.core.thing.binding.ThingHandlerCallback;
112 import org.openhab.core.thing.type.ChannelTypeUID;
113 import org.openhab.core.types.Command;
114 import org.openhab.core.types.RefreshType;
115 import org.openhab.core.types.State;
116 import org.openhab.core.types.UnDefType;
117 import org.slf4j.Logger;
118 import org.slf4j.LoggerFactory;
119
120 /**
121  * Abstract handler for a FRITZ! thing. Handles commands, which are sent to one of the channels.
122  *
123  * @author Robert Bausdorf - Initial contribution
124  * @author Christoph Weitkamp - Added support for AVM FRITZ!DECT 300 and Comet DECT
125  * @author Christoph Weitkamp - Added support for groups
126  * @author Ulrich Mertin - Added support for HAN-FUN blinds
127  * @author Christoph Sommer - Added support for color temperature
128  * @author Tobias Lange - Added abs color temperature and fixed on/off behavior of light blub
129  */
130 @NonNullByDefault
131 public abstract class AVMFritzBaseThingHandler extends BaseThingHandler implements FritzAhaStatusListener {
132
133     private final Logger logger = LoggerFactory.getLogger(AVMFritzBaseThingHandler.class);
134
135     /**
136      * keeps track of the current state for handling of increase/decrease
137      */
138     private AVMFritzBaseModel currentDevice = new DeviceModel();
139     private @Nullable String identifier;
140
141     /**
142      * Constructor
143      *
144      * @param thing Thing object representing a FRITZ! device
145      */
146     public AVMFritzBaseThingHandler(Thing thing) {
147         super(thing);
148     }
149
150     @Override
151     public void initialize() {
152         final AVMFritzDeviceConfiguration config = getConfigAs(AVMFritzDeviceConfiguration.class);
153         final String newIdentifier = config.ain;
154         if (newIdentifier == null || newIdentifier.isBlank()) {
155             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
156                     "The 'ain' parameter must be configured.");
157         } else {
158             this.identifier = newIdentifier;
159             updateStatus(ThingStatus.UNKNOWN);
160         }
161     }
162
163     @Override
164     public void onDeviceAdded(AVMFritzBaseModel device) {
165         // nothing to do
166     }
167
168     @Override
169     public void onDeviceUpdated(ThingUID thingUID, AVMFritzBaseModel device) {
170         if (thing.getUID().equals(thingUID)) {
171             logger.debug("Update thing '{}' with device model: {}", thingUID, device);
172             if (device.getPresent() == 1) {
173                 updateStatus(ThingStatus.ONLINE);
174             } else {
175                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "Device not present");
176             }
177             currentDevice = device;
178
179             updateProperties(device, editProperties());
180
181             if (device.isPowermeter()) {
182                 updatePowermeter(device.getPowermeter());
183             }
184             if (device.isSwitchableOutlet()) {
185                 updateSwitchableOutlet(device.getSwitch());
186             }
187             if (device.isHeatingThermostat()) {
188                 updateHeatingThermostat(device.getHkr());
189             }
190             if (device instanceof DeviceModel deviceModel) {
191                 if (deviceModel.isTemperatureSensor()) {
192                     updateTemperatureSensor(deviceModel.getTemperature());
193                 }
194                 if (deviceModel.isHumiditySensor()) {
195                     updateHumiditySensor(deviceModel.getHumidity());
196                 }
197                 if (deviceModel.isHANFUNAlarmSensor()) {
198                     if (deviceModel.isHANFUNBlinds()) {
199                         updateHANFUNBlindsAlarmSensor(deviceModel.getAlert());
200                     } else {
201                         updateHANFUNAlarmSensor(deviceModel.getAlert());
202                     }
203                 }
204                 if (deviceModel.isHANFUNBlinds()) {
205                     updateLevelControl(deviceModel.getLevelControlModel());
206                 } else if (deviceModel.isColorLight()) {
207                     updateColorLight(deviceModel.getColorControlModel(), deviceModel.getLevelControlModel(),
208                             deviceModel.getSimpleOnOffUnit());
209                 } else if (deviceModel.isDimmableLight() && !deviceModel.isHANFUNBlinds()) {
210                     updateDimmableLight(deviceModel.getLevelControlModel());
211                 } else if (deviceModel.isHANFUNUnit() && deviceModel.isHANFUNOnOff()) {
212                     updateSimpleOnOffUnit(deviceModel.getSimpleOnOffUnit());
213                 }
214             }
215         }
216     }
217
218     private void updateHANFUNAlarmSensor(@Nullable AlertModel alertModel) {
219         if (alertModel != null) {
220             updateThingChannelState(CHANNEL_CONTACT_STATE,
221                     AlertModel.ON.equals(alertModel.getState()) ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
222         }
223     }
224
225     private void updateHANFUNBlindsAlarmSensor(@Nullable AlertModel alertModel) {
226         if (alertModel != null) {
227             updateThingChannelState(CHANNEL_OBSTRUCTION_ALARM,
228                     OnOffType.from(alertModel.hasObstructionAlarmOccurred()));
229             updateThingChannelState(CHANNEL_TEMPERATURE_ALARM, OnOffType.from(alertModel.hasTemperaturAlarmOccurred()));
230             if (alertModel.hasUnknownAlarmOccurred()) {
231                 logger.warn("Unknown blinds alarm {}", alertModel.getState());
232             }
233         }
234     }
235
236     protected void updateTemperatureSensor(@Nullable TemperatureModel temperatureModel) {
237         if (temperatureModel != null) {
238             updateThingChannelState(CHANNEL_TEMPERATURE,
239                     new QuantityType<>(temperatureModel.getCelsius(), SIUnits.CELSIUS));
240             updateThingChannelConfiguration(CHANNEL_TEMPERATURE, CONFIG_CHANNEL_TEMP_OFFSET,
241                     temperatureModel.getOffset());
242         }
243     }
244
245     protected void updateHumiditySensor(@Nullable HumidityModel humidityModel) {
246         if (humidityModel != null) {
247             updateThingChannelState(CHANNEL_HUMIDITY,
248                     new QuantityType<>(humidityModel.getRelativeHumidity(), Units.PERCENT));
249         }
250     }
251
252     protected void updateLevelControl(@Nullable LevelControlModel levelControlModel) {
253         if (levelControlModel != null) {
254             updateThingChannelState(CHANNEL_ROLLERSHUTTER, new PercentType(levelControlModel.getLevelPercentage()));
255         }
256     }
257
258     private void updateDimmableLight(@Nullable LevelControlModel levelControlModel) {
259         if (levelControlModel != null) {
260             updateThingChannelState(CHANNEL_BRIGHTNESS, new PercentType(levelControlModel.getLevelPercentage()));
261         }
262     }
263
264     private void updateColorLight(@Nullable ColorControlModel colorControlModel,
265             @Nullable LevelControlModel levelControlModel, @Nullable SimpleOnOffModel simpleOnOff) {
266         if (colorControlModel != null && levelControlModel != null && simpleOnOff != null) {
267             DecimalType hue = new DecimalType(colorControlModel.hue);
268             PercentType saturation = ColorControlModel.toPercent(colorControlModel.saturation);
269             PercentType brightness;
270             if (simpleOnOff.state) {
271                 brightness = new PercentType(levelControlModel.getLevelPercentage());
272             } else {
273                 brightness = PercentType.ZERO;
274             }
275             updateThingChannelState(CHANNEL_COLOR, new HSBType(hue, saturation, brightness));
276
277             if (colorControlModel.currentMode == 4) {
278                 int temperature = colorControlModel.temperature;
279                 int tempMired = 1000000 / temperature;
280                 int tempMinMired = 1000000 / 2700;
281                 int tempMaxMired = 1000000 / 6500;
282                 int pct = (tempMired - tempMinMired) * 100 / (tempMaxMired - tempMinMired);
283                 updateThingChannelState(CHANNEL_COLORTEMPERATURE, new PercentType(pct));
284                 updateThingChannelState(CHANNEL_COLORTEMPERATURE_ABS,
285                         new QuantityType<>(BigDecimal.valueOf(temperature), Units.KELVIN));
286             }
287         }
288     }
289
290     private void updateHeatingThermostat(@Nullable HeatingModel heatingModel) {
291         if (heatingModel != null) {
292             updateThingChannelState(CHANNEL_MODE, new StringType(heatingModel.getMode()));
293             updateThingChannelState(CHANNEL_LOCKED,
294                     BigDecimal.ZERO.equals(heatingModel.getLock()) ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
295             updateThingChannelState(CHANNEL_DEVICE_LOCKED,
296                     BigDecimal.ZERO.equals(heatingModel.getDevicelock()) ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
297             updateThingChannelState(CHANNEL_ACTUALTEMP,
298                     new QuantityType<>(toCelsius(heatingModel.getTist()), SIUnits.CELSIUS));
299             updateThingChannelState(CHANNEL_SETTEMP,
300                     new QuantityType<>(toCelsius(heatingModel.getTsoll()), SIUnits.CELSIUS));
301             updateThingChannelState(CHANNEL_ECOTEMP,
302                     new QuantityType<>(toCelsius(heatingModel.getAbsenk()), SIUnits.CELSIUS));
303             updateThingChannelState(CHANNEL_COMFORTTEMP,
304                     new QuantityType<>(toCelsius(heatingModel.getKomfort()), SIUnits.CELSIUS));
305             updateThingChannelState(CHANNEL_RADIATOR_MODE, new StringType(heatingModel.getRadiatorMode()));
306             NextChangeModel nextChange = heatingModel.getNextchange();
307             if (nextChange != null) {
308                 int endPeriod = nextChange.getEndperiod();
309                 updateThingChannelState(CHANNEL_NEXT_CHANGE, endPeriod == 0 ? UnDefType.UNDEF
310                         : new DateTimeType(
311                                 ZonedDateTime.ofInstant(Instant.ofEpochSecond(endPeriod), ZoneId.systemDefault())));
312                 BigDecimal nextTemperature = nextChange.getTchange();
313                 updateThingChannelState(CHANNEL_NEXTTEMP, TEMP_FRITZ_UNDEFINED.equals(nextTemperature) ? UnDefType.UNDEF
314                         : new QuantityType<>(toCelsius(nextTemperature), SIUnits.CELSIUS));
315             }
316             updateBattery(heatingModel);
317         }
318     }
319
320     protected void updateBattery(BatteryModel batteryModel) {
321         BigDecimal batteryLevel = batteryModel.getBattery();
322         updateThingChannelState(CHANNEL_BATTERY,
323                 batteryLevel == null ? UnDefType.UNDEF : new DecimalType(batteryLevel));
324         BigDecimal lowBattery = batteryModel.getBatterylow();
325         if (lowBattery == null) {
326             updateThingChannelState(CHANNEL_BATTERY_LOW, UnDefType.UNDEF);
327         } else {
328             updateThingChannelState(CHANNEL_BATTERY_LOW, OnOffType.from(BatteryModel.BATTERY_ON.equals(lowBattery)));
329         }
330     }
331
332     private void updateSimpleOnOffUnit(@Nullable SimpleOnOffModel simpleOnOffUnit) {
333         if (simpleOnOffUnit != null) {
334             updateThingChannelState(CHANNEL_ON_OFF, OnOffType.from(simpleOnOffUnit.state));
335         }
336     }
337
338     private void updateSwitchableOutlet(@Nullable SwitchModel switchModel) {
339         if (switchModel != null) {
340             updateThingChannelState(CHANNEL_MODE, new StringType(switchModel.getMode()));
341             updateThingChannelState(CHANNEL_LOCKED,
342                     BigDecimal.ZERO.equals(switchModel.getLock()) ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
343             updateThingChannelState(CHANNEL_DEVICE_LOCKED,
344                     BigDecimal.ZERO.equals(switchModel.getDevicelock()) ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
345             BigDecimal state = switchModel.getState();
346             if (state == null) {
347                 updateThingChannelState(CHANNEL_OUTLET, UnDefType.UNDEF);
348             } else {
349                 updateThingChannelState(CHANNEL_OUTLET, OnOffType.from(SwitchModel.ON.equals(state)));
350             }
351         }
352     }
353
354     private void updatePowermeter(@Nullable PowerMeterModel powerMeterModel) {
355         if (powerMeterModel != null) {
356             updateThingChannelState(CHANNEL_ENERGY, new QuantityType<>(powerMeterModel.getEnergy(), Units.WATT_HOUR));
357             updateThingChannelState(CHANNEL_POWER, new QuantityType<>(powerMeterModel.getPower(), Units.WATT));
358             updateThingChannelState(CHANNEL_VOLTAGE, new QuantityType<>(powerMeterModel.getVoltage(), Units.VOLT));
359         }
360     }
361
362     /**
363      * Updates thing properties.
364      *
365      * @param device the {@link AVMFritzBaseModel}
366      * @param editProperties map of existing properties
367      */
368     protected void updateProperties(AVMFritzBaseModel device, Map<String, String> editProperties) {
369         editProperties.put(Thing.PROPERTY_FIRMWARE_VERSION, device.getFirmwareVersion());
370         updateProperties(editProperties);
371     }
372
373     /**
374      * Updates thing channels and creates dynamic channels if missing.
375      *
376      * @param channelId ID of the channel to be updated.
377      * @param state State to be set.
378      */
379     protected void updateThingChannelState(String channelId, State state) {
380         Channel channel = thing.getChannel(channelId);
381         if (channel != null) {
382             updateState(channel.getUID(), state);
383         } else {
384             logger.debug("Channel '{}' in thing '{}' does not exist, recreating thing.", channelId, thing.getUID());
385             createChannel(channelId);
386         }
387     }
388
389     /**
390      * Creates a {@link ChannelTypeUID} from the given channel id.
391      *
392      * @param channelId ID of the channel type UID to be created.
393      * @return the channel type UID
394      */
395     private ChannelTypeUID createChannelTypeUID(String channelId) {
396         int pos = channelId.indexOf(ChannelUID.CHANNEL_GROUP_SEPARATOR);
397         String id = pos > -1 ? channelId.substring(pos + 1) : channelId;
398         final ChannelTypeUID channelTypeUID;
399         switch (id) {
400             case CHANNEL_BATTERY:
401                 channelTypeUID = DefaultSystemChannelTypeProvider.SYSTEM_CHANNEL_BATTERY_LEVEL.getUID();
402                 break;
403             case CHANNEL_VOLTAGE:
404                 channelTypeUID = DefaultSystemChannelTypeProvider.SYSTEM_ELECTRIC_VOLTAGE.getUID();
405                 break;
406             default:
407                 channelTypeUID = new ChannelTypeUID(BINDING_ID, id);
408                 break;
409         }
410         return channelTypeUID;
411     }
412
413     /**
414      * Creates new channels for the thing.
415      *
416      * @param channelId ID of the channel to be created.
417      */
418     private void createChannel(String channelId) {
419         ThingHandlerCallback callback = getCallback();
420         if (callback != null) {
421             final ChannelUID channelUID = new ChannelUID(thing.getUID(), channelId);
422             final ChannelTypeUID channelTypeUID = createChannelTypeUID(channelId);
423             final Channel channel = callback.createChannelBuilder(channelUID, channelTypeUID).build();
424             updateThing(editThing().withoutChannel(channelUID).withChannel(channel).build());
425         }
426     }
427
428     /**
429      * Updates thing channel configurations.
430      *
431      * @param channelId ID of the channel which configuration to be updated.
432      * @param configId ID of the configuration to be updated.
433      * @param value Value to be set.
434      */
435     protected void updateThingChannelConfiguration(String channelId, String configId, Object value) {
436         Channel channel = thing.getChannel(channelId);
437         if (channel != null) {
438             Configuration editConfig = channel.getConfiguration();
439             editConfig.put(configId, value);
440         }
441     }
442
443     @Override
444     public void onDeviceGone(ThingUID thingUID) {
445         if (thing.getUID().equals(thingUID)) {
446             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.GONE, "Device not present in response");
447         }
448     }
449
450     @Override
451     public void handleCommand(ChannelUID channelUID, Command command) {
452         String channelId = channelUID.getIdWithoutGroup();
453         logger.debug("Handle command '{}' for channel {}", command, channelId);
454         if (command == RefreshType.REFRESH) {
455             handleRefreshCommand();
456             return;
457         }
458         FritzAhaWebInterface fritzBox = getWebInterface();
459         if (fritzBox == null) {
460             logger.debug("Cannot handle command '{}' because connection is missing", command);
461             return;
462         }
463         String ain = getIdentifier();
464         if (ain == null) {
465             logger.debug("Cannot handle command '{}' because AIN is missing", command);
466             return;
467         }
468         switch (channelId) {
469             case CHANNEL_MODE:
470             case CHANNEL_LOCKED:
471             case CHANNEL_DEVICE_LOCKED:
472             case CHANNEL_TEMPERATURE:
473             case CHANNEL_HUMIDITY:
474             case CHANNEL_ENERGY:
475             case CHANNEL_POWER:
476             case CHANNEL_VOLTAGE:
477             case CHANNEL_ACTUALTEMP:
478             case CHANNEL_ECOTEMP:
479             case CHANNEL_COMFORTTEMP:
480             case CHANNEL_NEXT_CHANGE:
481             case CHANNEL_NEXTTEMP:
482             case CHANNEL_BATTERY:
483             case CHANNEL_BATTERY_LOW:
484             case CHANNEL_CONTACT_STATE:
485             case CHANNEL_LAST_CHANGE:
486             case CHANNEL_OBSTRUCTION_ALARM:
487             case CHANNEL_TEMPERATURE_ALARM:
488                 logger.debug("Channel {} is a read-only channel and cannot handle command '{}'", channelId, command);
489                 break;
490             case CHANNEL_OUTLET:
491             case CHANNEL_ON_OFF:
492                 if (command instanceof OnOffType) {
493                     fritzBox.setSwitch(ain, OnOffType.ON.equals(command));
494                 }
495                 break;
496             case CHANNEL_COLOR:
497             case CHANNEL_BRIGHTNESS:
498                 BigDecimal brightness = null;
499                 if (command instanceof HSBType hsbCommand) {
500                     brightness = hsbCommand.getBrightness().toBigDecimal();
501                     fritzBox.setUnmappedHueAndSaturation(ain, hsbCommand.getHue().intValue(),
502                             ColorControlModel.fromPercent(hsbCommand.getSaturation()), 0);
503                 } else if (command instanceof PercentType brightnessPercent) {
504                     brightness = brightnessPercent.toBigDecimal();
505                 } else if (command instanceof OnOffType) {
506                     fritzBox.setSwitch(ain, OnOffType.ON.equals(command));
507                 } else if (command instanceof IncreaseDecreaseType) {
508                     brightness = ((DeviceModel) currentDevice).getLevelControlModel().getLevelPercentage();
509                     if (IncreaseDecreaseType.INCREASE.equals(command)) {
510                         brightness.add(BigDecimal.TEN);
511                     } else {
512                         brightness.subtract(BigDecimal.TEN);
513                     }
514                 }
515                 if (brightness != null) {
516                     if (brightness.equals(BigDecimal.ZERO)) {
517                         fritzBox.setSwitch(ain, false);
518                     } else {
519                         fritzBox.setSwitch(ain, true);
520                         fritzBox.setLevelPercentage(ain, brightness);
521                     }
522                 }
523                 break;
524             case CHANNEL_COLORTEMPERATURE:
525                 BigDecimal colorTemperaturePct = null;
526                 if (command instanceof PercentType percentCommand) {
527                     colorTemperaturePct = percentCommand.toBigDecimal();
528                 }
529                 if (colorTemperaturePct != null) {
530                     int pct = colorTemperaturePct.intValue();
531                     // AHA-HTTP-Inteface docu say that the values typically between 2700K and 6500K
532                     int tempMinMired = 1000000 / 2700;
533                     int tempMaxMired = 1000000 / 6500;
534                     int tempScaledMired = tempMinMired + ((tempMaxMired - tempMinMired) * pct / 100);
535                     int tempKelvin = 1000000 / tempScaledMired;
536                     fritzBox.setColorTemperature(ain, tempKelvin, 0);
537                 }
538                 break;
539             case CHANNEL_COLORTEMPERATURE_ABS:
540                 BigDecimal colorTemperature = null;
541                 if (command instanceof QuantityType quantityCommand) {
542                     QuantityType<?> convertedCommand = quantityCommand.toInvertibleUnit(Units.KELVIN);
543                     if (convertedCommand != null) {
544                         colorTemperature = convertedCommand.toBigDecimal();
545                     }
546                 } else if (command instanceof DecimalType decimalCommand) {
547                     colorTemperature = decimalCommand.toBigDecimal();
548                 }
549                 if (colorTemperature != null) {
550                     fritzBox.setColorTemperature(ain, colorTemperature.intValue(), 0);
551                 }
552                 break;
553             case CHANNEL_SETTEMP:
554                 BigDecimal temperature = null;
555                 if (command instanceof DecimalType decimalCommand) {
556                     temperature = normalizeCelsius(decimalCommand.toBigDecimal());
557                 } else if (command instanceof QuantityType quantityCommand) {
558                     @SuppressWarnings("unchecked")
559                     QuantityType<Temperature> convertedCommand = ((QuantityType<Temperature>) command)
560                             .toUnit(SIUnits.CELSIUS);
561                     if (convertedCommand != null) {
562                         temperature = normalizeCelsius(convertedCommand.toBigDecimal());
563                     } else {
564                         logger.warn("Unable to convert unit from '{}' to '{}'. Skipping command.",
565                                 quantityCommand.getUnit(), SIUnits.CELSIUS);
566                     }
567                 } else if (command instanceof IncreaseDecreaseType) {
568                     temperature = currentDevice.getHkr().getTsoll();
569                     if (IncreaseDecreaseType.INCREASE.equals(command)) {
570                         temperature.add(BigDecimal.ONE);
571                     } else {
572                         temperature.subtract(BigDecimal.ONE);
573                     }
574                 } else if (command instanceof OnOffType) {
575                     temperature = OnOffType.ON.equals(command) ? TEMP_FRITZ_ON : TEMP_FRITZ_OFF;
576                 }
577                 if (temperature != null) {
578                     fritzBox.setSetTemp(ain, fromCelsius(temperature));
579                     HeatingModel heatingModel = currentDevice.getHkr();
580                     heatingModel.setTsoll(temperature);
581                     updateState(CHANNEL_RADIATOR_MODE, new StringType(heatingModel.getRadiatorMode()));
582                 }
583                 break;
584             case CHANNEL_RADIATOR_MODE:
585                 BigDecimal targetTemperature = null;
586                 if (command instanceof StringType) {
587                     switch (command.toString()) {
588                         case MODE_ON:
589                             targetTemperature = TEMP_FRITZ_ON;
590                             break;
591                         case MODE_OFF:
592                             targetTemperature = TEMP_FRITZ_OFF;
593                             break;
594                         case MODE_COMFORT:
595                             targetTemperature = currentDevice.getHkr().getKomfort();
596                             break;
597                         case MODE_ECO:
598                             targetTemperature = currentDevice.getHkr().getAbsenk();
599                             break;
600                         case MODE_BOOST:
601                             targetTemperature = TEMP_FRITZ_MAX;
602                             break;
603                         case MODE_UNKNOWN:
604                         case MODE_WINDOW_OPEN:
605                             logger.debug("Command '{}' is a read-only command for channel {}.", command, channelId);
606                             break;
607                     }
608                     if (targetTemperature != null) {
609                         fritzBox.setSetTemp(ain, targetTemperature);
610                         currentDevice.getHkr().setTsoll(targetTemperature);
611                         updateState(CHANNEL_SETTEMP, new QuantityType<>(toCelsius(targetTemperature), SIUnits.CELSIUS));
612                     }
613                 }
614                 break;
615             case CHANNEL_ROLLERSHUTTER:
616                 if (command instanceof StopMoveType rollershutterCommand) {
617                     if (StopMoveType.STOP.equals(rollershutterCommand)) {
618                         fritzBox.setBlind(ain, BlindCommand.STOP);
619                     } else {
620                         logger.debug("Received unknown rollershutter StopMove command MOVE");
621                     }
622                 } else if (command instanceof UpDownType rollershutterCommand) {
623                     if (UpDownType.UP.equals(rollershutterCommand)) {
624                         fritzBox.setBlind(ain, BlindCommand.OPEN);
625                     } else {
626                         fritzBox.setBlind(ain, BlindCommand.CLOSE);
627                     }
628                 } else if (command instanceof PercentType percentCommand) {
629                     BigDecimal levelPercentage = percentCommand.toBigDecimal();
630                     fritzBox.setLevelPercentage(ain, levelPercentage);
631                 } else {
632                     logger.debug("Received unknown rollershutter command type '{}'", command.toString());
633                 }
634                 break;
635             default:
636                 logger.debug("Received unknown channel {}", channelId);
637                 break;
638         }
639     }
640
641     /**
642      * Handles a command for a given action.
643      *
644      * @param action
645      * @param duration
646      */
647     protected void handleAction(String action, long duration) {
648         FritzAhaWebInterface fritzBox = getWebInterface();
649         if (fritzBox == null) {
650             logger.debug("Cannot handle action '{}' because connection is missing", action);
651             return;
652         }
653         String ain = getIdentifier();
654         if (ain == null) {
655             logger.debug("Cannot handle action '{}' because AIN is missing", action);
656             return;
657         }
658         if (duration < 0 || 86400 < duration) {
659             throw new IllegalArgumentException("Duration must not be less than zero or greater than 86400");
660         }
661         switch (action) {
662             case MODE_BOOST:
663                 fritzBox.setBoostMode(ain,
664                         duration > 0 ? ZonedDateTime.now().plusSeconds(duration).toEpochSecond() : 0);
665                 break;
666             case MODE_WINDOW_OPEN:
667                 fritzBox.setWindowOpenMode(ain,
668                         duration > 0 ? ZonedDateTime.now().plusSeconds(duration).toEpochSecond() : 0);
669                 break;
670             default:
671                 logger.debug("Received unknown action '{}'", action);
672                 break;
673         }
674     }
675
676     /**
677      * Provides the web interface object.
678      *
679      * @return The web interface object
680      */
681     private @Nullable FritzAhaWebInterface getWebInterface() {
682         Bridge bridge = getBridge();
683         if (bridge != null) {
684             BridgeHandler handler = bridge.getHandler();
685             if (handler instanceof AVMFritzBaseBridgeHandler bridgeHandler) {
686                 return bridgeHandler.getWebInterface();
687             }
688         }
689         return null;
690     }
691
692     /**
693      * Handles a refresh command.
694      */
695     private void handleRefreshCommand() {
696         Bridge bridge = getBridge();
697         if (bridge != null) {
698             BridgeHandler handler = bridge.getHandler();
699             if (handler instanceof AVMFritzBaseBridgeHandler bridgeHandler) {
700                 bridgeHandler.handleRefreshCommand();
701             }
702         }
703     }
704
705     /**
706      * Returns the AIN.
707      *
708      * @return the AIN
709      */
710     public @Nullable String getIdentifier() {
711         return identifier;
712     }
713 }