2 * Copyright (c) 2010-2024 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.luxtronikheatpump.internal;
15 import java.io.IOException;
16 import java.util.ArrayList;
17 import java.util.HashSet;
18 import java.util.List;
20 import java.util.concurrent.ScheduledFuture;
21 import java.util.concurrent.TimeUnit;
23 import javax.measure.Unit;
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.openhab.binding.luxtronikheatpump.internal.enums.HeatpumpChannel;
28 import org.openhab.binding.luxtronikheatpump.internal.enums.HeatpumpCoolingOperationMode;
29 import org.openhab.binding.luxtronikheatpump.internal.enums.HeatpumpOperationMode;
30 import org.openhab.binding.luxtronikheatpump.internal.exceptions.InvalidChannelException;
31 import org.openhab.binding.luxtronikheatpump.internal.exceptions.InvalidOperationModeException;
32 import org.openhab.core.config.core.Configuration;
33 import org.openhab.core.library.types.DecimalType;
34 import org.openhab.core.library.types.OnOffType;
35 import org.openhab.core.library.types.QuantityType;
36 import org.openhab.core.thing.Channel;
37 import org.openhab.core.thing.ChannelUID;
38 import org.openhab.core.thing.Thing;
39 import org.openhab.core.thing.ThingStatus;
40 import org.openhab.core.thing.ThingStatusDetail;
41 import org.openhab.core.thing.binding.BaseThingHandler;
42 import org.openhab.core.thing.binding.ThingHandlerCallback;
43 import org.openhab.core.thing.binding.builder.ThingBuilder;
44 import org.openhab.core.thing.type.ChannelTypeUID;
45 import org.openhab.core.types.Command;
46 import org.openhab.core.types.RefreshType;
47 import org.openhab.core.types.State;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
52 * The {@link LuxtronikHeatpumpHandler} is responsible for handling commands, which are
53 * sent to one of the channels.
55 * @author Stefan Giehl - Initial contribution
58 public class LuxtronikHeatpumpHandler extends BaseThingHandler {
60 private final Logger logger = LoggerFactory.getLogger(LuxtronikHeatpumpHandler.class);
61 private final Set<ScheduledFuture<?>> scheduledFutures = new HashSet<>();
62 private static final int RETRY_INTERVAL_SEC = 60;
63 private boolean tiggerChannelUpdate = false;
64 private final LuxtronikTranslationProvider translationProvider;
65 private LuxtronikHeatpumpConfiguration config;
67 public LuxtronikHeatpumpHandler(Thing thing, LuxtronikTranslationProvider translationProvider) {
69 this.translationProvider = translationProvider;
70 config = new LuxtronikHeatpumpConfiguration();
74 public void updateState(String channelID, State state) {
75 super.updateState(channelID, state);
79 public void updateProperty(String name, @Nullable String value) {
80 super.updateProperty(name, value);
83 public void setStatusConnectionError() {
84 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
85 "couldn't establish network connection [host '" + config.ipAddress + "']");
88 public void setStatusOnline() {
89 updateStatus(ThingStatus.ONLINE);
93 public void handleCommand(ChannelUID channelUID, Command command) {
94 String channelId = channelUID.getIdWithoutGroup();
95 logger.debug("Handle command '{}' for channel {}", command, channelId);
96 if (command == RefreshType.REFRESH) {
97 // ignore resresh command as channels will be updated automatically
101 HeatpumpChannel channel;
104 channel = HeatpumpChannel.fromString(channelId);
105 } catch (InvalidChannelException e) {
106 logger.debug("Channel '{}' could not be found for thing {}", channelId, thing.getUID());
110 if (!channel.isWritable()) {
111 logger.debug("Channel {} is a read-only channel and cannot handle command '{}'", channelId, command);
115 if (command instanceof QuantityType value) {
116 Unit<?> unit = channel.getUnit();
118 value = value.toUnit(unit);
121 command = new DecimalType(value.floatValue());
124 if (command instanceof OnOffType onOffCommand) {
125 command = onOffCommand == OnOffType.ON ? new DecimalType(1) : DecimalType.ZERO;
128 if (!(command instanceof DecimalType)) {
129 logger.warn("Heatpump operation for item {} must be from type: {}. Received {}", channel.getCommand(),
130 DecimalType.class.getSimpleName(), command.getClass());
134 Integer param = channel.getChannelId();
135 Integer value = null;
138 case CHANNEL_EINST_BWTDI_AKT_MO:
139 case CHANNEL_EINST_BWTDI_AKT_DI:
140 case CHANNEL_EINST_BWTDI_AKT_MI:
141 case CHANNEL_EINST_BWTDI_AKT_DO:
142 case CHANNEL_EINST_BWTDI_AKT_FR:
143 case CHANNEL_EINST_BWTDI_AKT_SA:
144 case CHANNEL_EINST_BWTDI_AKT_SO:
145 case CHANNEL_EINST_BWTDI_AKT_AL:
146 value = ((DecimalType) command).intValue();
148 case CHANNEL_BA_HZ_AKT:
149 case CHANNEL_BA_BW_AKT:
150 value = ((DecimalType) command).intValue();
152 // validate the value is valid
153 HeatpumpOperationMode.fromValue(value);
154 } catch (InvalidOperationModeException e) {
155 logger.warn("Heatpump {} mode recevieved invalid value {}: {}", channel.getCommand(), value,
160 case CHANNEL_EINST_WK_AKT:
161 case CHANNEL_EINST_BWS_AKT:
162 case CHANNEL_EINST_KUCFTL_AKT:
163 case CHANNEL_SOLLWERT_KUCFTL_AKT:
164 case CHANNEL_SOLL_BWS_AKT:
165 case CHANNEL_EINST_HEIZGRENZE_TEMP:
166 float temperature = ((DecimalType) command).floatValue();
167 value = (int) (temperature * 10);
169 case CHANNEL_EINST_BWSTYP_AKT:
170 value = ((DecimalType) command).intValue();
172 // validate the value is valid
173 HeatpumpCoolingOperationMode.fromValue(value);
174 } catch (InvalidOperationModeException e) {
175 logger.warn("Heatpump {} mode recevieved invalid value {}: {}", channel.getCommand(), value,
180 case CHANNEL_EINST_KUHL_ZEIT_EIN_AKT:
181 case CHANNEL_EINST_KUHL_ZEIT_AUS_AKT:
182 float hours = ((DecimalType) command).floatValue();
183 value = (int) (hours * 10);
187 logger.debug("Received unknown channel {}", channelId);
191 if (param != null && value != null) {
192 if (sendParamToHeatpump(param, value)) {
193 logger.debug("Heat pump mode {} set to {}.", channel.getCommand(), value);
195 logger.warn("Failed setting heat pump mode {} to {}", channel.getCommand(), value);
198 logger.warn("No valid value given for Heatpump operation {}", channel.getCommand());
203 public void initialize() {
204 config = getConfigAs(LuxtronikHeatpumpConfiguration.class);
206 if (!config.isValid()) {
207 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
208 "At least one mandatory configuration field is empty");
212 updateStatus(ThingStatus.UNKNOWN);
214 synchronized (scheduledFutures) {
215 ScheduledFuture<?> future = scheduler.scheduleWithFixedDelay(this::internalInitialize, 0,
216 RETRY_INTERVAL_SEC, TimeUnit.SECONDS);
217 scheduledFutures.add(future);
221 private void internalInitialize() {
222 // connect to heatpump and check if values can be fetched
223 HeatpumpConnector connector = new HeatpumpConnector(config.ipAddress, config.port);
227 } catch (IOException e) {
228 setStatusConnectionError();
232 // stop trying to establish a connection for initializing the thing once it was established
235 // When thing is initialized the first time or and update was triggered, set the available channels
236 if (thing.getProperties().isEmpty() || tiggerChannelUpdate) {
237 updateChannels(connector);
245 protected void updateConfiguration(Configuration configuration) {
246 tiggerChannelUpdate = true;
247 super.updateConfiguration(configuration);
251 public void dispose() {
255 private void updateChannels(HeatpumpConnector connector) {
256 Integer[] visibilityValues = connector.getVisibilities();
257 Integer[] heatpumpValues = connector.getValues();
258 Integer[] heatpumpParams = connector.getParams();
260 logger.debug("Updating available channels for thing {}", thing.getUID());
262 final ThingHandlerCallback callback = getCallback();
263 if (callback == null) {
264 logger.debug("ThingHandlerCallback is null. Skipping migration of last_update channel.");
268 ThingBuilder thingBuilder = editThing();
269 List<Channel> channelList = new ArrayList<>();
271 // clear channel list
272 thingBuilder.withoutChannels(thing.getChannels());
274 // create list with available channels
275 for (HeatpumpChannel channel : HeatpumpChannel.values()) {
276 Integer channelId = channel.getChannelId();
277 int length = channel.isWritable() ? heatpumpParams.length : heatpumpValues.length;
278 ChannelUID channelUID = new ChannelUID(thing.getUID(), channel.getCommand());
279 ChannelTypeUID channelTypeUID;
280 if (channel.getCommand().matches("^channel[0-9]+$")) {
281 channelTypeUID = new ChannelTypeUID(LuxtronikHeatpumpBindingConstants.BINDING_ID, "unknown");
283 channelTypeUID = new ChannelTypeUID(LuxtronikHeatpumpBindingConstants.BINDING_ID, channel.getCommand());
285 if ((channelId != null && length <= channelId)
286 || (config.showAllChannels == Boolean.FALSE && !channel.isVisible(visibilityValues))) {
287 logger.debug("Hiding channel {}", channel.getCommand());
289 channelList.add(callback.createChannelBuilder(channelUID, channelTypeUID).build());
293 thingBuilder.withChannels(channelList);
295 updateThing(thingBuilder.build());
298 private void restartJobs() {
301 synchronized (scheduledFutures) {
302 if (getThing().getStatus() == ThingStatus.ONLINE) {
303 // Repeat channel update job every configured seconds
304 Runnable channelUpdaterJob = new ChannelUpdaterJob(this, translationProvider);
305 ScheduledFuture<?> future = scheduler.scheduleWithFixedDelay(channelUpdaterJob, 0, config.refresh,
307 scheduledFutures.add(future);
312 private void stopJobs() {
313 synchronized (scheduledFutures) {
314 for (ScheduledFuture<?> future : scheduledFutures) {
315 if (!future.isDone()) {
319 scheduledFutures.clear();
324 * Set a parameter on the Luxtronik heatpump.
329 private boolean sendParamToHeatpump(int param, int value) {
330 HeatpumpConnector connector = new HeatpumpConnector(config.ipAddress, config.port);
333 return connector.setParam(param, value);
334 } catch (IOException e) {
335 setStatusConnectionError();