2 * Copyright (c) 2010-2020 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.PowerMeterModel;
36 import org.openhab.binding.avmfritz.internal.dto.SwitchModel;
37 import org.openhab.binding.avmfritz.internal.dto.TemperatureModel;
38 import org.openhab.binding.avmfritz.internal.hardware.FritzAhaStatusListener;
39 import org.openhab.binding.avmfritz.internal.hardware.FritzAhaWebInterface;
40 import org.openhab.core.config.core.Configuration;
41 import org.openhab.core.library.types.DateTimeType;
42 import org.openhab.core.library.types.DecimalType;
43 import org.openhab.core.library.types.IncreaseDecreaseType;
44 import org.openhab.core.library.types.OnOffType;
45 import org.openhab.core.library.types.OpenClosedType;
46 import org.openhab.core.library.types.QuantityType;
47 import org.openhab.core.library.types.StringType;
48 import org.openhab.core.library.unit.SIUnits;
49 import org.openhab.core.library.unit.Units;
50 import org.openhab.core.thing.Bridge;
51 import org.openhab.core.thing.Channel;
52 import org.openhab.core.thing.ChannelUID;
53 import org.openhab.core.thing.DefaultSystemChannelTypeProvider;
54 import org.openhab.core.thing.Thing;
55 import org.openhab.core.thing.ThingStatus;
56 import org.openhab.core.thing.ThingStatusDetail;
57 import org.openhab.core.thing.ThingUID;
58 import org.openhab.core.thing.binding.BaseThingHandler;
59 import org.openhab.core.thing.binding.BridgeHandler;
60 import org.openhab.core.thing.binding.ThingHandlerCallback;
61 import org.openhab.core.thing.type.ChannelTypeUID;
62 import org.openhab.core.types.Command;
63 import org.openhab.core.types.RefreshType;
64 import org.openhab.core.types.State;
65 import org.openhab.core.types.UnDefType;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
70 * Abstract handler for a FRITZ! thing. Handles commands, which are sent to one of the channels.
72 * @author Robert Bausdorf - Initial contribution
73 * @author Christoph Weitkamp - Added support for AVM FRITZ!DECT 300 and Comet DECT
74 * @author Christoph Weitkamp - Added support for groups
77 public abstract class AVMFritzBaseThingHandler extends BaseThingHandler implements FritzAhaStatusListener {
79 private final Logger logger = LoggerFactory.getLogger(AVMFritzBaseThingHandler.class);
82 * keeps track of the current state for handling of increase/decrease
84 private @Nullable AVMFritzBaseModel state;
85 private @Nullable String identifier;
90 * @param thing Thing object representing a FRITZ! device
92 public AVMFritzBaseThingHandler(Thing thing) {
97 public void initialize() {
98 final AVMFritzDeviceConfiguration config = getConfigAs(AVMFritzDeviceConfiguration.class);
99 final String newIdentifier = config.ain;
100 if (newIdentifier == null || newIdentifier.isBlank()) {
101 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
102 "The 'ain' parameter must be configured.");
104 this.identifier = newIdentifier;
105 updateStatus(ThingStatus.UNKNOWN);
110 public void onDeviceAdded(AVMFritzBaseModel device) {
115 public void onDeviceUpdated(ThingUID thingUID, AVMFritzBaseModel device) {
116 if (thing.getUID().equals(thingUID)) {
117 logger.debug("Update thing '{}' with device model: {}", thingUID, device);
118 if (device.getPresent() == 1) {
119 updateStatus(ThingStatus.ONLINE);
121 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "Device not present");
125 updateProperties(device, editProperties());
127 if (device.isPowermeter()) {
128 updatePowermeter(device.getPowermeter());
130 if (device.isSwitchableOutlet()) {
131 updateSwitchableOutlet(device.getSwitch());
133 if (device.isHeatingThermostat()) {
134 updateHeatingThermostat(device.getHkr());
136 if (device instanceof DeviceModel) {
137 DeviceModel deviceModel = (DeviceModel) device;
138 if (deviceModel.isTempSensor()) {
139 updateTemperatureSensor(deviceModel.getTemperature());
141 if (deviceModel.isHANFUNAlarmSensor()) {
142 updateHANFUNAlarmSensor(deviceModel.getAlert());
148 private void updateHANFUNAlarmSensor(@Nullable AlertModel alertModel) {
149 if (alertModel != null) {
150 updateThingChannelState(CHANNEL_CONTACT_STATE,
151 AlertModel.ON.equals(alertModel.getState()) ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
155 private void updateTemperatureSensor(@Nullable TemperatureModel temperatureModel) {
156 if (temperatureModel != null) {
157 updateThingChannelState(CHANNEL_TEMPERATURE,
158 new QuantityType<>(temperatureModel.getCelsius(), SIUnits.CELSIUS));
159 updateThingChannelConfiguration(CHANNEL_TEMPERATURE, CONFIG_CHANNEL_TEMP_OFFSET,
160 temperatureModel.getOffset());
164 private void updateHeatingThermostat(@Nullable HeatingModel heatingModel) {
165 if (heatingModel != null) {
166 updateThingChannelState(CHANNEL_MODE, new StringType(heatingModel.getMode()));
167 updateThingChannelState(CHANNEL_LOCKED,
168 BigDecimal.ZERO.equals(heatingModel.getLock()) ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
169 updateThingChannelState(CHANNEL_DEVICE_LOCKED,
170 BigDecimal.ZERO.equals(heatingModel.getDevicelock()) ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
171 updateThingChannelState(CHANNEL_ACTUALTEMP,
172 new QuantityType<>(toCelsius(heatingModel.getTist()), SIUnits.CELSIUS));
173 updateThingChannelState(CHANNEL_SETTEMP,
174 new QuantityType<>(toCelsius(heatingModel.getTsoll()), SIUnits.CELSIUS));
175 updateThingChannelState(CHANNEL_ECOTEMP,
176 new QuantityType<>(toCelsius(heatingModel.getAbsenk()), SIUnits.CELSIUS));
177 updateThingChannelState(CHANNEL_COMFORTTEMP,
178 new QuantityType<>(toCelsius(heatingModel.getKomfort()), SIUnits.CELSIUS));
179 updateThingChannelState(CHANNEL_RADIATOR_MODE, new StringType(heatingModel.getRadiatorMode()));
180 NextChangeModel nextChange = heatingModel.getNextchange();
181 if (nextChange != null) {
182 int endPeriod = nextChange.getEndperiod();
183 updateThingChannelState(CHANNEL_NEXT_CHANGE, endPeriod == 0 ? UnDefType.UNDEF
185 ZonedDateTime.ofInstant(Instant.ofEpochSecond(endPeriod), ZoneId.systemDefault())));
186 BigDecimal nextTemperature = nextChange.getTchange();
187 updateThingChannelState(CHANNEL_NEXTTEMP, TEMP_FRITZ_UNDEFINED.equals(nextTemperature) ? UnDefType.UNDEF
188 : new QuantityType<>(toCelsius(nextTemperature), SIUnits.CELSIUS));
190 updateBattery(heatingModel);
194 protected void updateBattery(BatteryModel batteryModel) {
195 BigDecimal batteryLevel = batteryModel.getBattery();
196 updateThingChannelState(CHANNEL_BATTERY,
197 batteryLevel == null ? UnDefType.UNDEF : new DecimalType(batteryLevel));
198 BigDecimal lowBattery = batteryModel.getBatterylow();
199 if (lowBattery == null) {
200 updateThingChannelState(CHANNEL_BATTERY_LOW, UnDefType.UNDEF);
202 updateThingChannelState(CHANNEL_BATTERY_LOW,
203 BatteryModel.BATTERY_ON.equals(lowBattery) ? OnOffType.ON : OnOffType.OFF);
207 private void updateSwitchableOutlet(@Nullable SwitchModel switchModel) {
208 if (switchModel != null) {
209 updateThingChannelState(CHANNEL_MODE, new StringType(switchModel.getMode()));
210 updateThingChannelState(CHANNEL_LOCKED,
211 BigDecimal.ZERO.equals(switchModel.getLock()) ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
212 updateThingChannelState(CHANNEL_DEVICE_LOCKED,
213 BigDecimal.ZERO.equals(switchModel.getDevicelock()) ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
214 BigDecimal state = switchModel.getState();
216 updateThingChannelState(CHANNEL_OUTLET, UnDefType.UNDEF);
218 updateThingChannelState(CHANNEL_OUTLET, SwitchModel.ON.equals(state) ? OnOffType.ON : OnOffType.OFF);
223 private void updatePowermeter(@Nullable PowerMeterModel powerMeterModel) {
224 if (powerMeterModel != null) {
225 updateThingChannelState(CHANNEL_ENERGY, new QuantityType<>(powerMeterModel.getEnergy(), Units.WATT_HOUR));
226 updateThingChannelState(CHANNEL_POWER, new QuantityType<>(powerMeterModel.getPower(), Units.WATT));
227 updateThingChannelState(CHANNEL_VOLTAGE, new QuantityType<>(powerMeterModel.getVoltage(), Units.VOLT));
232 * Updates thing properties.
234 * @param device the {@link AVMFritzBaseModel}
235 * @param editProperties map of existing properties
237 protected void updateProperties(AVMFritzBaseModel device, Map<String, String> editProperties) {
238 editProperties.put(Thing.PROPERTY_FIRMWARE_VERSION, device.getFirmwareVersion());
239 updateProperties(editProperties);
243 * Updates thing channels and creates dynamic channels if missing.
245 * @param channelId ID of the channel to be updated.
246 * @param state State to be set.
248 protected void updateThingChannelState(String channelId, State state) {
249 Channel channel = thing.getChannel(channelId);
250 if (channel != null) {
251 updateState(channel.getUID(), state);
253 logger.debug("Channel '{}' in thing '{}' does not exist, recreating thing.", channelId, thing.getUID());
254 createChannel(channelId);
259 * Creates new channels for the thing.
261 * @param channelId ID of the channel to be created.
263 private void createChannel(String channelId) {
264 ThingHandlerCallback callback = getCallback();
265 if (callback != null) {
266 ChannelUID channelUID = new ChannelUID(thing.getUID(), channelId);
267 ChannelTypeUID channelTypeUID = CHANNEL_BATTERY.equals(channelId)
268 ? DefaultSystemChannelTypeProvider.SYSTEM_CHANNEL_BATTERY_LEVEL.getUID()
269 : new ChannelTypeUID(BINDING_ID, channelId);
270 Channel channel = callback.createChannelBuilder(channelUID, channelTypeUID).build();
271 updateThing(editThing().withoutChannel(channelUID).withChannel(channel).build());
276 * Updates thing channel configurations.
278 * @param channelId ID of the channel which configuration to be updated.
279 * @param configId ID of the configuration to be updated.
280 * @param value Value to be set.
282 private void updateThingChannelConfiguration(String channelId, String configId, Object value) {
283 Channel channel = thing.getChannel(channelId);
284 if (channel != null) {
285 Configuration editConfig = channel.getConfiguration();
286 editConfig.put(configId, value);
291 public void onDeviceGone(ThingUID thingUID) {
292 if (thing.getUID().equals(thingUID)) {
293 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.GONE, "Device not present in response");
298 public void handleCommand(ChannelUID channelUID, Command command) {
299 String channelId = channelUID.getIdWithoutGroup();
300 logger.debug("Handle command '{}' for channel {}", command, channelId);
301 if (command == RefreshType.REFRESH) {
302 handleRefreshCommand();
305 FritzAhaWebInterface fritzBox = getWebInterface();
306 if (fritzBox == null) {
307 logger.debug("Cannot handle command '{}' because connection is missing", command);
310 String ain = getIdentifier();
312 logger.debug("Cannot handle command '{}' because AIN is missing", command);
318 case CHANNEL_DEVICE_LOCKED:
319 case CHANNEL_TEMPERATURE:
322 case CHANNEL_VOLTAGE:
323 case CHANNEL_ACTUALTEMP:
324 case CHANNEL_ECOTEMP:
325 case CHANNEL_COMFORTTEMP:
326 case CHANNEL_NEXT_CHANGE:
327 case CHANNEL_NEXTTEMP:
328 case CHANNEL_BATTERY:
329 case CHANNEL_BATTERY_LOW:
330 case CHANNEL_CONTACT_STATE:
331 case CHANNEL_LAST_CHANGE:
332 logger.debug("Channel {} is a read-only channel and cannot handle command '{}'", channelId, command);
335 if (command instanceof OnOffType) {
336 fritzBox.setSwitch(ain, OnOffType.ON.equals(command));
338 state.getSwitch().setState(OnOffType.ON.equals(command) ? SwitchModel.ON : SwitchModel.OFF);
342 case CHANNEL_SETTEMP:
343 BigDecimal temperature = null;
344 if (command instanceof DecimalType) {
345 temperature = normalizeCelsius(((DecimalType) command).toBigDecimal());
346 } else if (command instanceof QuantityType) {
347 temperature = normalizeCelsius(
348 ((QuantityType<Temperature>) command).toUnit(SIUnits.CELSIUS).toBigDecimal());
349 } else if (command instanceof IncreaseDecreaseType) {
350 temperature = state.getHkr().getTsoll();
351 if (IncreaseDecreaseType.INCREASE.equals(command)) {
352 temperature.add(BigDecimal.ONE);
354 temperature.subtract(BigDecimal.ONE);
356 } else if (command instanceof OnOffType) {
357 temperature = OnOffType.ON.equals(command) ? TEMP_FRITZ_ON : TEMP_FRITZ_OFF;
359 if (temperature != null) {
360 fritzBox.setSetTemp(ain, fromCelsius(temperature));
361 HeatingModel heatingModel = state.getHkr();
362 heatingModel.setTsoll(temperature);
363 updateState(CHANNEL_RADIATOR_MODE, new StringType(heatingModel.getRadiatorMode()));
366 case CHANNEL_RADIATOR_MODE:
367 BigDecimal targetTemperature = null;
368 if (command instanceof StringType) {
369 switch (command.toString()) {
371 targetTemperature = TEMP_FRITZ_ON;
374 targetTemperature = TEMP_FRITZ_OFF;
377 targetTemperature = state.getHkr().getKomfort();
380 targetTemperature = state.getHkr().getAbsenk();
383 targetTemperature = TEMP_FRITZ_MAX;
386 case MODE_WINDOW_OPEN:
387 logger.debug("Command '{}' is a read-only command for channel {}.", command, channelId);
390 if (targetTemperature != null) {
391 fritzBox.setSetTemp(ain, targetTemperature);
392 state.getHkr().setTsoll(targetTemperature);
393 updateState(CHANNEL_SETTEMP, new QuantityType<>(toCelsius(targetTemperature), SIUnits.CELSIUS));
398 logger.debug("Received unknown channel {}", channelId);
404 * Handles a command for a given action.
409 protected void handleAction(String action, long duration) {
410 FritzAhaWebInterface fritzBox = getWebInterface();
411 if (fritzBox == null) {
412 logger.debug("Cannot handle action '{}' because connection is missing", action);
415 String ain = getIdentifier();
417 logger.debug("Cannot handle action '{}' because AIN is missing", action);
420 if (duration < 0 || 86400 < duration) {
421 throw new IllegalArgumentException("Duration must not be less than zero or greater than 86400");
425 fritzBox.setBoostMode(ain,
426 duration > 0 ? ZonedDateTime.now().plusSeconds(duration).toEpochSecond() : 0);
428 case MODE_WINDOW_OPEN:
429 fritzBox.setWindowOpenMode(ain,
430 duration > 0 ? ZonedDateTime.now().plusSeconds(duration).toEpochSecond() : 0);
433 logger.debug("Received unknown action '{}'", action);
439 * Provides the web interface object.
441 * @return The web interface object
443 private @Nullable FritzAhaWebInterface getWebInterface() {
444 Bridge bridge = getBridge();
445 if (bridge != null) {
446 BridgeHandler handler = bridge.getHandler();
447 if (handler instanceof AVMFritzBaseBridgeHandler) {
448 return ((AVMFritzBaseBridgeHandler) handler).getWebInterface();
455 * Handles a refresh command.
457 private void handleRefreshCommand() {
458 Bridge bridge = getBridge();
459 if (bridge != null) {
460 BridgeHandler handler = bridge.getHandler();
461 if (handler instanceof AVMFritzBaseBridgeHandler) {
462 ((AVMFritzBaseBridgeHandler) handler).handleRefreshCommand();
472 public @Nullable String getIdentifier() {