2 * Copyright (c) 2010-2021 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.avmfritz.internal.handler;
15 import static org.openhab.binding.avmfritz.internal.AVMFritzBindingConstants.*;
16 import static org.openhab.binding.avmfritz.internal.dto.HeatingModel.*;
18 import java.math.BigDecimal;
19 import java.time.Instant;
20 import java.time.ZoneId;
21 import java.time.ZonedDateTime;
24 import javax.measure.quantity.Temperature;
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.avmfritz.internal.config.AVMFritzDeviceConfiguration;
29 import org.openhab.binding.avmfritz.internal.dto.AVMFritzBaseModel;
30 import org.openhab.binding.avmfritz.internal.dto.AlertModel;
31 import org.openhab.binding.avmfritz.internal.dto.BatteryModel;
32 import org.openhab.binding.avmfritz.internal.dto.DeviceModel;
33 import org.openhab.binding.avmfritz.internal.dto.HeatingModel;
34 import org.openhab.binding.avmfritz.internal.dto.HeatingModel.NextChangeModel;
35 import org.openhab.binding.avmfritz.internal.dto.HumidityModel;
36 import org.openhab.binding.avmfritz.internal.dto.PowerMeterModel;
37 import org.openhab.binding.avmfritz.internal.dto.SwitchModel;
38 import org.openhab.binding.avmfritz.internal.dto.TemperatureModel;
39 import org.openhab.binding.avmfritz.internal.hardware.FritzAhaStatusListener;
40 import org.openhab.binding.avmfritz.internal.hardware.FritzAhaWebInterface;
41 import org.openhab.core.config.core.Configuration;
42 import org.openhab.core.library.types.DateTimeType;
43 import org.openhab.core.library.types.DecimalType;
44 import org.openhab.core.library.types.IncreaseDecreaseType;
45 import org.openhab.core.library.types.OnOffType;
46 import org.openhab.core.library.types.OpenClosedType;
47 import org.openhab.core.library.types.QuantityType;
48 import org.openhab.core.library.types.StringType;
49 import org.openhab.core.library.unit.SIUnits;
50 import org.openhab.core.library.unit.Units;
51 import org.openhab.core.thing.Bridge;
52 import org.openhab.core.thing.Channel;
53 import org.openhab.core.thing.ChannelUID;
54 import org.openhab.core.thing.DefaultSystemChannelTypeProvider;
55 import org.openhab.core.thing.Thing;
56 import org.openhab.core.thing.ThingStatus;
57 import org.openhab.core.thing.ThingStatusDetail;
58 import org.openhab.core.thing.ThingUID;
59 import org.openhab.core.thing.binding.BaseThingHandler;
60 import org.openhab.core.thing.binding.BridgeHandler;
61 import org.openhab.core.thing.binding.ThingHandlerCallback;
62 import org.openhab.core.thing.type.ChannelTypeUID;
63 import org.openhab.core.types.Command;
64 import org.openhab.core.types.RefreshType;
65 import org.openhab.core.types.State;
66 import org.openhab.core.types.UnDefType;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
71 * Abstract handler for a FRITZ! thing. Handles commands, which are sent to one of the channels.
73 * @author Robert Bausdorf - Initial contribution
74 * @author Christoph Weitkamp - Added support for AVM FRITZ!DECT 300 and Comet DECT
75 * @author Christoph Weitkamp - Added support for groups
78 public abstract class AVMFritzBaseThingHandler extends BaseThingHandler implements FritzAhaStatusListener {
80 private final Logger logger = LoggerFactory.getLogger(AVMFritzBaseThingHandler.class);
83 * keeps track of the current state for handling of increase/decrease
85 private @Nullable AVMFritzBaseModel state;
86 private @Nullable String identifier;
91 * @param thing Thing object representing a FRITZ! device
93 public AVMFritzBaseThingHandler(Thing thing) {
98 public void initialize() {
99 final AVMFritzDeviceConfiguration config = getConfigAs(AVMFritzDeviceConfiguration.class);
100 final String newIdentifier = config.ain;
101 if (newIdentifier == null || newIdentifier.isBlank()) {
102 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
103 "The 'ain' parameter must be configured.");
105 this.identifier = newIdentifier;
106 updateStatus(ThingStatus.UNKNOWN);
111 public void onDeviceAdded(AVMFritzBaseModel device) {
116 public void onDeviceUpdated(ThingUID thingUID, AVMFritzBaseModel device) {
117 if (thing.getUID().equals(thingUID)) {
118 logger.debug("Update thing '{}' with device model: {}", thingUID, device);
119 if (device.getPresent() == 1) {
120 updateStatus(ThingStatus.ONLINE);
122 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "Device not present");
126 updateProperties(device, editProperties());
128 if (device.isPowermeter()) {
129 updatePowermeter(device.getPowermeter());
131 if (device.isSwitchableOutlet()) {
132 updateSwitchableOutlet(device.getSwitch());
134 if (device.isHeatingThermostat()) {
135 updateHeatingThermostat(device.getHkr());
137 if (device instanceof DeviceModel) {
138 DeviceModel deviceModel = (DeviceModel) device;
139 if (deviceModel.isTempSensor()) {
140 updateTemperatureSensor(deviceModel.getTemperature());
142 if (deviceModel.isHumiditySensor()) {
143 updateHumiditySensor(deviceModel.getHumidity());
145 if (deviceModel.isHANFUNAlarmSensor()) {
146 updateHANFUNAlarmSensor(deviceModel.getAlert());
152 private void updateHANFUNAlarmSensor(@Nullable AlertModel alertModel) {
153 if (alertModel != null) {
154 updateThingChannelState(CHANNEL_CONTACT_STATE,
155 AlertModel.ON.equals(alertModel.getState()) ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
159 private void updateTemperatureSensor(@Nullable TemperatureModel temperatureModel) {
160 if (temperatureModel != null) {
161 updateThingChannelState(CHANNEL_TEMPERATURE,
162 new QuantityType<>(temperatureModel.getCelsius(), SIUnits.CELSIUS));
163 updateThingChannelConfiguration(CHANNEL_TEMPERATURE, CONFIG_CHANNEL_TEMP_OFFSET,
164 temperatureModel.getOffset());
168 protected void updateHumiditySensor(@Nullable HumidityModel humidityModel) {
169 if (humidityModel != null) {
170 updateThingChannelState(CHANNEL_HUMIDITY,
171 new QuantityType<>(humidityModel.getRelativeHumidity(), Units.PERCENT));
175 private void updateHeatingThermostat(@Nullable HeatingModel heatingModel) {
176 if (heatingModel != null) {
177 updateThingChannelState(CHANNEL_MODE, new StringType(heatingModel.getMode()));
178 updateThingChannelState(CHANNEL_LOCKED,
179 BigDecimal.ZERO.equals(heatingModel.getLock()) ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
180 updateThingChannelState(CHANNEL_DEVICE_LOCKED,
181 BigDecimal.ZERO.equals(heatingModel.getDevicelock()) ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
182 updateThingChannelState(CHANNEL_ACTUALTEMP,
183 new QuantityType<>(toCelsius(heatingModel.getTist()), SIUnits.CELSIUS));
184 updateThingChannelState(CHANNEL_SETTEMP,
185 new QuantityType<>(toCelsius(heatingModel.getTsoll()), SIUnits.CELSIUS));
186 updateThingChannelState(CHANNEL_ECOTEMP,
187 new QuantityType<>(toCelsius(heatingModel.getAbsenk()), SIUnits.CELSIUS));
188 updateThingChannelState(CHANNEL_COMFORTTEMP,
189 new QuantityType<>(toCelsius(heatingModel.getKomfort()), SIUnits.CELSIUS));
190 updateThingChannelState(CHANNEL_RADIATOR_MODE, new StringType(heatingModel.getRadiatorMode()));
191 NextChangeModel nextChange = heatingModel.getNextchange();
192 if (nextChange != null) {
193 int endPeriod = nextChange.getEndperiod();
194 updateThingChannelState(CHANNEL_NEXT_CHANGE, endPeriod == 0 ? UnDefType.UNDEF
196 ZonedDateTime.ofInstant(Instant.ofEpochSecond(endPeriod), ZoneId.systemDefault())));
197 BigDecimal nextTemperature = nextChange.getTchange();
198 updateThingChannelState(CHANNEL_NEXTTEMP, TEMP_FRITZ_UNDEFINED.equals(nextTemperature) ? UnDefType.UNDEF
199 : new QuantityType<>(toCelsius(nextTemperature), SIUnits.CELSIUS));
201 updateBattery(heatingModel);
205 protected void updateBattery(BatteryModel batteryModel) {
206 BigDecimal batteryLevel = batteryModel.getBattery();
207 updateThingChannelState(CHANNEL_BATTERY,
208 batteryLevel == null ? UnDefType.UNDEF : new DecimalType(batteryLevel));
209 BigDecimal lowBattery = batteryModel.getBatterylow();
210 if (lowBattery == null) {
211 updateThingChannelState(CHANNEL_BATTERY_LOW, UnDefType.UNDEF);
213 updateThingChannelState(CHANNEL_BATTERY_LOW,
214 BatteryModel.BATTERY_ON.equals(lowBattery) ? OnOffType.ON : OnOffType.OFF);
218 private void updateSwitchableOutlet(@Nullable SwitchModel switchModel) {
219 if (switchModel != null) {
220 updateThingChannelState(CHANNEL_MODE, new StringType(switchModel.getMode()));
221 updateThingChannelState(CHANNEL_LOCKED,
222 BigDecimal.ZERO.equals(switchModel.getLock()) ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
223 updateThingChannelState(CHANNEL_DEVICE_LOCKED,
224 BigDecimal.ZERO.equals(switchModel.getDevicelock()) ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
225 BigDecimal state = switchModel.getState();
227 updateThingChannelState(CHANNEL_OUTLET, UnDefType.UNDEF);
229 updateThingChannelState(CHANNEL_OUTLET, SwitchModel.ON.equals(state) ? OnOffType.ON : OnOffType.OFF);
234 private void updatePowermeter(@Nullable PowerMeterModel powerMeterModel) {
235 if (powerMeterModel != null) {
236 updateThingChannelState(CHANNEL_ENERGY, new QuantityType<>(powerMeterModel.getEnergy(), Units.WATT_HOUR));
237 updateThingChannelState(CHANNEL_POWER, new QuantityType<>(powerMeterModel.getPower(), Units.WATT));
238 updateThingChannelState(CHANNEL_VOLTAGE, new QuantityType<>(powerMeterModel.getVoltage(), Units.VOLT));
243 * Updates thing properties.
245 * @param device the {@link AVMFritzBaseModel}
246 * @param editProperties map of existing properties
248 protected void updateProperties(AVMFritzBaseModel device, Map<String, String> editProperties) {
249 editProperties.put(Thing.PROPERTY_FIRMWARE_VERSION, device.getFirmwareVersion());
250 updateProperties(editProperties);
254 * Updates thing channels and creates dynamic channels if missing.
256 * @param channelId ID of the channel to be updated.
257 * @param state State to be set.
259 protected void updateThingChannelState(String channelId, State state) {
260 Channel channel = thing.getChannel(channelId);
261 if (channel != null) {
262 updateState(channel.getUID(), state);
264 logger.debug("Channel '{}' in thing '{}' does not exist, recreating thing.", channelId, thing.getUID());
265 createChannel(channelId);
270 * Creates a {@link ChannelTypeUID} from the given channel id.
272 * @param channelId ID of the channel type UID to be created.
273 * @return the channel type UID
275 private ChannelTypeUID createChannelTypeUID(String channelId) {
276 int pos = channelId.indexOf(ChannelUID.CHANNEL_GROUP_SEPARATOR);
277 String id = pos > -1 ? channelId.substring(pos + 1) : channelId;
278 return CHANNEL_BATTERY.equals(id) ? DefaultSystemChannelTypeProvider.SYSTEM_CHANNEL_BATTERY_LEVEL.getUID()
279 : new ChannelTypeUID(BINDING_ID, id);
283 * Creates new channels for the thing.
285 * @param channelId ID of the channel to be created.
287 private void createChannel(String channelId) {
288 ThingHandlerCallback callback = getCallback();
289 if (callback != null) {
290 ChannelUID channelUID = new ChannelUID(thing.getUID(), channelId);
291 ChannelTypeUID channelTypeUID = createChannelTypeUID(channelId);
292 Channel channel = callback.createChannelBuilder(channelUID, channelTypeUID).build();
293 updateThing(editThing().withoutChannel(channelUID).withChannel(channel).build());
298 * Updates thing channel configurations.
300 * @param channelId ID of the channel which configuration to be updated.
301 * @param configId ID of the configuration to be updated.
302 * @param value Value to be set.
304 private void updateThingChannelConfiguration(String channelId, String configId, Object value) {
305 Channel channel = thing.getChannel(channelId);
306 if (channel != null) {
307 Configuration editConfig = channel.getConfiguration();
308 editConfig.put(configId, value);
313 public void onDeviceGone(ThingUID thingUID) {
314 if (thing.getUID().equals(thingUID)) {
315 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.GONE, "Device not present in response");
320 public void handleCommand(ChannelUID channelUID, Command command) {
321 String channelId = channelUID.getIdWithoutGroup();
322 logger.debug("Handle command '{}' for channel {}", command, channelId);
323 if (command == RefreshType.REFRESH) {
324 handleRefreshCommand();
327 FritzAhaWebInterface fritzBox = getWebInterface();
328 if (fritzBox == null) {
329 logger.debug("Cannot handle command '{}' because connection is missing", command);
332 String ain = getIdentifier();
334 logger.debug("Cannot handle command '{}' because AIN is missing", command);
340 case CHANNEL_DEVICE_LOCKED:
341 case CHANNEL_TEMPERATURE:
342 case CHANNEL_HUMIDITY:
345 case CHANNEL_VOLTAGE:
346 case CHANNEL_ACTUALTEMP:
347 case CHANNEL_ECOTEMP:
348 case CHANNEL_COMFORTTEMP:
349 case CHANNEL_NEXT_CHANGE:
350 case CHANNEL_NEXTTEMP:
351 case CHANNEL_BATTERY:
352 case CHANNEL_BATTERY_LOW:
353 case CHANNEL_CONTACT_STATE:
354 case CHANNEL_LAST_CHANGE:
355 logger.debug("Channel {} is a read-only channel and cannot handle command '{}'", channelId, command);
358 if (command instanceof OnOffType) {
359 fritzBox.setSwitch(ain, OnOffType.ON.equals(command));
361 state.getSwitch().setState(OnOffType.ON.equals(command) ? SwitchModel.ON : SwitchModel.OFF);
365 case CHANNEL_SETTEMP:
366 BigDecimal temperature = null;
367 if (command instanceof DecimalType) {
368 temperature = normalizeCelsius(((DecimalType) command).toBigDecimal());
369 } else if (command instanceof QuantityType) {
370 @SuppressWarnings("unchecked")
371 QuantityType<Temperature> convertedCommand = ((QuantityType<Temperature>) command)
372 .toUnit(SIUnits.CELSIUS);
373 if (convertedCommand != null) {
374 temperature = normalizeCelsius(convertedCommand.toBigDecimal());
376 logger.warn("Unable to convert unit from '{}' to '{}'. Skipping command.",
377 ((QuantityType<?>) command).getUnit(), SIUnits.CELSIUS);
379 } else if (command instanceof IncreaseDecreaseType) {
380 temperature = state.getHkr().getTsoll();
381 if (IncreaseDecreaseType.INCREASE.equals(command)) {
382 temperature.add(BigDecimal.ONE);
384 temperature.subtract(BigDecimal.ONE);
386 } else if (command instanceof OnOffType) {
387 temperature = OnOffType.ON.equals(command) ? TEMP_FRITZ_ON : TEMP_FRITZ_OFF;
389 if (temperature != null) {
390 fritzBox.setSetTemp(ain, fromCelsius(temperature));
391 HeatingModel heatingModel = state.getHkr();
392 heatingModel.setTsoll(temperature);
393 updateState(CHANNEL_RADIATOR_MODE, new StringType(heatingModel.getRadiatorMode()));
396 case CHANNEL_RADIATOR_MODE:
397 BigDecimal targetTemperature = null;
398 if (command instanceof StringType) {
399 switch (command.toString()) {
401 targetTemperature = TEMP_FRITZ_ON;
404 targetTemperature = TEMP_FRITZ_OFF;
407 targetTemperature = state.getHkr().getKomfort();
410 targetTemperature = state.getHkr().getAbsenk();
413 targetTemperature = TEMP_FRITZ_MAX;
416 case MODE_WINDOW_OPEN:
417 logger.debug("Command '{}' is a read-only command for channel {}.", command, channelId);
420 if (targetTemperature != null) {
421 fritzBox.setSetTemp(ain, targetTemperature);
422 state.getHkr().setTsoll(targetTemperature);
423 updateState(CHANNEL_SETTEMP, new QuantityType<>(toCelsius(targetTemperature), SIUnits.CELSIUS));
428 logger.debug("Received unknown channel {}", channelId);
434 * Handles a command for a given action.
439 protected void handleAction(String action, long duration) {
440 FritzAhaWebInterface fritzBox = getWebInterface();
441 if (fritzBox == null) {
442 logger.debug("Cannot handle action '{}' because connection is missing", action);
445 String ain = getIdentifier();
447 logger.debug("Cannot handle action '{}' because AIN is missing", action);
450 if (duration < 0 || 86400 < duration) {
451 throw new IllegalArgumentException("Duration must not be less than zero or greater than 86400");
455 fritzBox.setBoostMode(ain,
456 duration > 0 ? ZonedDateTime.now().plusSeconds(duration).toEpochSecond() : 0);
458 case MODE_WINDOW_OPEN:
459 fritzBox.setWindowOpenMode(ain,
460 duration > 0 ? ZonedDateTime.now().plusSeconds(duration).toEpochSecond() : 0);
463 logger.debug("Received unknown action '{}'", action);
469 * Provides the web interface object.
471 * @return The web interface object
473 private @Nullable FritzAhaWebInterface getWebInterface() {
474 Bridge bridge = getBridge();
475 if (bridge != null) {
476 BridgeHandler handler = bridge.getHandler();
477 if (handler instanceof AVMFritzBaseBridgeHandler) {
478 return ((AVMFritzBaseBridgeHandler) handler).getWebInterface();
485 * Handles a refresh command.
487 private void handleRefreshCommand() {
488 Bridge bridge = getBridge();
489 if (bridge != null) {
490 BridgeHandler handler = bridge.getHandler();
491 if (handler instanceof AVMFritzBaseBridgeHandler) {
492 ((AVMFritzBaseBridgeHandler) handler).handleRefreshCommand();
502 public @Nullable String getIdentifier() {