]> git.basschouten.com Git - openhab-addons.git/blob
92fa22c391574d94b61aaee8bc5afd8bd68b3f80
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.*;
16 import static org.openhab.binding.avmfritz.internal.dto.HeatingModel.*;
17
18 import java.math.BigDecimal;
19 import java.time.Instant;
20 import java.time.ZoneId;
21 import java.time.ZonedDateTime;
22 import java.util.Map;
23
24 import javax.measure.quantity.Temperature;
25
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;
68
69 /**
70  * Abstract handler for a FRITZ! thing. Handles commands, which are sent to one of the channels.
71  *
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
75  */
76 @NonNullByDefault
77 public abstract class AVMFritzBaseThingHandler extends BaseThingHandler implements FritzAhaStatusListener {
78
79     private final Logger logger = LoggerFactory.getLogger(AVMFritzBaseThingHandler.class);
80
81     /**
82      * keeps track of the current state for handling of increase/decrease
83      */
84     private @Nullable AVMFritzBaseModel state;
85     private @Nullable String identifier;
86
87     /**
88      * Constructor
89      *
90      * @param thing Thing object representing a FRITZ! device
91      */
92     public AVMFritzBaseThingHandler(Thing thing) {
93         super(thing);
94     }
95
96     @Override
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.");
103         } else {
104             this.identifier = newIdentifier;
105             updateStatus(ThingStatus.UNKNOWN);
106         }
107     }
108
109     @Override
110     public void onDeviceAdded(AVMFritzBaseModel device) {
111         // nothing to do
112     }
113
114     @Override
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);
120             } else {
121                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "Device not present");
122             }
123             state = device;
124
125             updateProperties(device, editProperties());
126
127             if (device.isPowermeter()) {
128                 updatePowermeter(device.getPowermeter());
129             }
130             if (device.isSwitchableOutlet()) {
131                 updateSwitchableOutlet(device.getSwitch());
132             }
133             if (device.isHeatingThermostat()) {
134                 updateHeatingThermostat(device.getHkr());
135             }
136             if (device instanceof DeviceModel) {
137                 DeviceModel deviceModel = (DeviceModel) device;
138                 if (deviceModel.isTempSensor()) {
139                     updateTemperatureSensor(deviceModel.getTemperature());
140                 }
141                 if (deviceModel.isHANFUNAlarmSensor()) {
142                     updateHANFUNAlarmSensor(deviceModel.getAlert());
143                 }
144             }
145         }
146     }
147
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);
152         }
153     }
154
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());
161         }
162     }
163
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
184                         : new DateTimeType(
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));
189             }
190             updateBattery(heatingModel);
191         }
192     }
193
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);
201         } else {
202             updateThingChannelState(CHANNEL_BATTERY_LOW,
203                     BatteryModel.BATTERY_ON.equals(lowBattery) ? OnOffType.ON : OnOffType.OFF);
204         }
205     }
206
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();
215             if (state == null) {
216                 updateThingChannelState(CHANNEL_OUTLET, UnDefType.UNDEF);
217             } else {
218                 updateThingChannelState(CHANNEL_OUTLET, SwitchModel.ON.equals(state) ? OnOffType.ON : OnOffType.OFF);
219             }
220         }
221     }
222
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));
228         }
229     }
230
231     /**
232      * Updates thing properties.
233      *
234      * @param device the {@link AVMFritzBaseModel}
235      * @param editProperties map of existing properties
236      */
237     protected void updateProperties(AVMFritzBaseModel device, Map<String, String> editProperties) {
238         editProperties.put(Thing.PROPERTY_FIRMWARE_VERSION, device.getFirmwareVersion());
239         updateProperties(editProperties);
240     }
241
242     /**
243      * Updates thing channels and creates dynamic channels if missing.
244      *
245      * @param channelId ID of the channel to be updated.
246      * @param state State to be set.
247      */
248     protected void updateThingChannelState(String channelId, State state) {
249         Channel channel = thing.getChannel(channelId);
250         if (channel != null) {
251             updateState(channel.getUID(), state);
252         } else {
253             logger.debug("Channel '{}' in thing '{}' does not exist, recreating thing.", channelId, thing.getUID());
254             createChannel(channelId);
255         }
256     }
257
258     /**
259      * Creates new channels for the thing.
260      *
261      * @param channelId ID of the channel to be created.
262      */
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());
272         }
273     }
274
275     /**
276      * Updates thing channel configurations.
277      *
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.
281      */
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);
287         }
288     }
289
290     @Override
291     public void onDeviceGone(ThingUID thingUID) {
292         if (thing.getUID().equals(thingUID)) {
293             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.GONE, "Device not present in response");
294         }
295     }
296
297     @Override
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();
303             return;
304         }
305         FritzAhaWebInterface fritzBox = getWebInterface();
306         if (fritzBox == null) {
307             logger.debug("Cannot handle command '{}' because connection is missing", command);
308             return;
309         }
310         String ain = getIdentifier();
311         if (ain == null) {
312             logger.debug("Cannot handle command '{}' because AIN is missing", command);
313             return;
314         }
315         switch (channelId) {
316             case CHANNEL_MODE:
317             case CHANNEL_LOCKED:
318             case CHANNEL_DEVICE_LOCKED:
319             case CHANNEL_TEMPERATURE:
320             case CHANNEL_ENERGY:
321             case CHANNEL_POWER:
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);
333                 break;
334             case CHANNEL_OUTLET:
335                 if (command instanceof OnOffType) {
336                     fritzBox.setSwitch(ain, OnOffType.ON.equals(command));
337                     if (state != null) {
338                         state.getSwitch().setState(OnOffType.ON.equals(command) ? SwitchModel.ON : SwitchModel.OFF);
339                     }
340                 }
341                 break;
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);
353                     } else {
354                         temperature.subtract(BigDecimal.ONE);
355                     }
356                 } else if (command instanceof OnOffType) {
357                     temperature = OnOffType.ON.equals(command) ? TEMP_FRITZ_ON : TEMP_FRITZ_OFF;
358                 }
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()));
364                 }
365                 break;
366             case CHANNEL_RADIATOR_MODE:
367                 BigDecimal targetTemperature = null;
368                 if (command instanceof StringType) {
369                     switch (command.toString()) {
370                         case MODE_ON:
371                             targetTemperature = TEMP_FRITZ_ON;
372                             break;
373                         case MODE_OFF:
374                             targetTemperature = TEMP_FRITZ_OFF;
375                             break;
376                         case MODE_COMFORT:
377                             targetTemperature = state.getHkr().getKomfort();
378                             break;
379                         case MODE_ECO:
380                             targetTemperature = state.getHkr().getAbsenk();
381                             break;
382                         case MODE_BOOST:
383                             targetTemperature = TEMP_FRITZ_MAX;
384                             break;
385                         case MODE_UNKNOWN:
386                         case MODE_WINDOW_OPEN:
387                             logger.debug("Command '{}' is a read-only command for channel {}.", command, channelId);
388                             break;
389                     }
390                     if (targetTemperature != null) {
391                         fritzBox.setSetTemp(ain, targetTemperature);
392                         state.getHkr().setTsoll(targetTemperature);
393                         updateState(CHANNEL_SETTEMP, new QuantityType<>(toCelsius(targetTemperature), SIUnits.CELSIUS));
394                     }
395                 }
396                 break;
397             default:
398                 logger.debug("Received unknown channel {}", channelId);
399                 break;
400         }
401     }
402
403     /**
404      * Handles a command for a given action.
405      *
406      * @param action
407      * @param duration
408      */
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);
413             return;
414         }
415         String ain = getIdentifier();
416         if (ain == null) {
417             logger.debug("Cannot handle action '{}' because AIN is missing", action);
418             return;
419         }
420         if (duration < 0 || 86400 < duration) {
421             throw new IllegalArgumentException("Duration must not be less than zero or greater than 86400");
422         }
423         switch (action) {
424             case MODE_BOOST:
425                 fritzBox.setBoostMode(ain,
426                         duration > 0 ? ZonedDateTime.now().plusSeconds(duration).toEpochSecond() : 0);
427                 break;
428             case MODE_WINDOW_OPEN:
429                 fritzBox.setWindowOpenMode(ain,
430                         duration > 0 ? ZonedDateTime.now().plusSeconds(duration).toEpochSecond() : 0);
431                 break;
432             default:
433                 logger.debug("Received unknown action '{}'", action);
434                 break;
435         }
436     }
437
438     /**
439      * Provides the web interface object.
440      *
441      * @return The web interface object
442      */
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();
449             }
450         }
451         return null;
452     }
453
454     /**
455      * Handles a refresh command.
456      */
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();
463             }
464         }
465     }
466
467     /**
468      * Returns the AIN.
469      *
470      * @return the AIN
471      */
472     public @Nullable String getIdentifier() {
473         return identifier;
474     }
475 }