2 * Copyright (c) 2010-2022 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.danfossairunit.internal.handler;
15 import static org.openhab.binding.danfossairunit.internal.DanfossAirUnitBindingConstants.*;
17 import java.io.IOException;
18 import java.net.InetAddress;
19 import java.net.UnknownHostException;
20 import java.util.HashMap;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.TimeUnit;
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.openhab.binding.danfossairunit.internal.Channel;
28 import org.openhab.binding.danfossairunit.internal.ChannelGroup;
29 import org.openhab.binding.danfossairunit.internal.DanfossAirUnit;
30 import org.openhab.binding.danfossairunit.internal.DanfossAirUnitCommunicationController;
31 import org.openhab.binding.danfossairunit.internal.DanfossAirUnitConfiguration;
32 import org.openhab.binding.danfossairunit.internal.DanfossAirUnitWriteAccessor;
33 import org.openhab.binding.danfossairunit.internal.UnexpectedResponseValueException;
34 import org.openhab.binding.danfossairunit.internal.ValueCache;
35 import org.openhab.core.thing.ChannelGroupUID;
36 import org.openhab.core.thing.ChannelUID;
37 import org.openhab.core.thing.Thing;
38 import org.openhab.core.thing.ThingStatus;
39 import org.openhab.core.thing.ThingStatusDetail;
40 import org.openhab.core.thing.binding.BaseThingHandler;
41 import org.openhab.core.types.Command;
42 import org.openhab.core.types.RefreshType;
43 import org.openhab.core.types.State;
44 import org.openhab.core.types.UnDefType;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
49 * The {@link DanfossAirUnitHandler} is responsible for handling commands, which are
50 * sent to one of the channels.
52 * @author Ralf Duckstein - Initial contribution
53 * @author Robert Bach - heavy refactorings
54 * @author Jacob Laursen - Refactoring, bugfixes and enhancements
57 public class DanfossAirUnitHandler extends BaseThingHandler {
59 private static final int TCP_PORT = 30046;
60 private static final int POLLING_INTERVAL_SECONDS = 5;
61 private final Logger logger = LoggerFactory.getLogger(DanfossAirUnitHandler.class);
62 private @NonNullByDefault({}) DanfossAirUnitConfiguration config;
63 private @Nullable ValueCache valueCache;
64 private @Nullable ScheduledFuture<?> pollingJob;
65 private @Nullable DanfossAirUnitCommunicationController communicationController;
66 private @Nullable DanfossAirUnit airUnit;
67 private boolean propertiesInitializedSuccessfully = false;
69 public DanfossAirUnitHandler(Thing thing) {
74 public void handleCommand(ChannelUID channelUID, Command command) {
75 if (command instanceof RefreshType) {
79 DanfossAirUnit localAirUnit = this.airUnit;
80 if (localAirUnit != null) {
81 Channel channel = Channel.getByName(channelUID.getIdWithoutGroup());
82 DanfossAirUnitWriteAccessor writeAccessor = channel.getWriteAccessor();
83 if (writeAccessor != null) {
84 updateState(channelUID, writeAccessor.access(localAirUnit, command));
87 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.NONE,
88 "@text/offline.connection-not-initialized");
91 } catch (IllegalArgumentException e) {
92 logger.debug("Ignoring unknown channel id: {}", channelUID.getIdWithoutGroup(), e);
93 } catch (IOException ioe) {
94 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, ioe.getMessage());
100 public void initialize() {
101 updateStatus(ThingStatus.UNKNOWN);
102 config = getConfigAs(DanfossAirUnitConfiguration.class);
103 valueCache = new ValueCache(config.updateUnchangedValuesEveryMillis);
104 removeDeprecatedChannels();
106 var localCommunicationController = new DanfossAirUnitCommunicationController(
107 InetAddress.getByName(config.host), TCP_PORT);
108 this.communicationController = localCommunicationController;
109 this.airUnit = new DanfossAirUnit(localCommunicationController);
111 } catch (UnknownHostException e) {
112 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
113 "@text/offline.communication-error.unknown-host [\"" + config.host + "\"]");
118 private void removeDeprecatedChannels() {
119 ChannelGroupUID mainChannelGroupUid = new ChannelGroupUID(thing.getUID(), ChannelGroup.MAIN.getGroupName());
120 ChannelUID manualFanSpeedChannelUid = new ChannelUID(mainChannelGroupUid,
121 Channel.CHANNEL_MANUAL_FAN_SPEED.getChannelName());
122 if (this.isLinked(manualFanSpeedChannelUid)) {
123 ChannelUID manualFanStepChannelUid = new ChannelUID(mainChannelGroupUid,
124 Channel.CHANNEL_MANUAL_FAN_STEP.getChannelName());
125 logger.warn("Channel '{}' is deprecated, please use '{}' instead.", manualFanSpeedChannelUid,
126 manualFanStepChannelUid);
128 logger.debug("Removing deprecated unlinked channel '{}'.", manualFanSpeedChannelUid);
129 updateThing(editThing().withoutChannel(manualFanSpeedChannelUid).build());
133 private void updateAllChannels() {
134 if (!initializeProperties()) {
138 DanfossAirUnit localAirUnit = this.airUnit;
139 if (localAirUnit == null) {
143 logger.debug("Updating DanfossHRV data '{}'", getThing().getUID());
145 for (Channel channel : Channel.values()) {
146 if (Thread.interrupted()) {
147 logger.debug("Polling thread interrupted...");
151 updateState(channel.getGroup().getGroupName(), channel.getChannelName(),
152 channel.getReadAccessor().access(localAirUnit));
153 if (getThing().getStatus() != ThingStatus.ONLINE) {
154 updateStatus(ThingStatus.ONLINE);
156 } catch (UnexpectedResponseValueException e) {
157 updateState(channel.getGroup().getGroupName(), channel.getChannelName(), UnDefType.UNDEF);
159 "Cannot update channel {}: an unexpected or invalid response has been received from the air unit: {}",
160 channel.getChannelName(), e.getMessage());
161 if (getThing().getStatus() != ThingStatus.ONLINE) {
162 updateStatus(ThingStatus.ONLINE);
164 } catch (IOException e) {
165 updateState(channel.getGroup().getGroupName(), channel.getChannelName(), UnDefType.UNDEF);
166 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, e.getMessage());
167 logger.debug("Cannot update channel {}: an error occurred retrieving the value: {}",
168 channel.getChannelName(), e.getMessage());
173 private synchronized boolean initializeProperties() {
174 if (propertiesInitializedSuccessfully) {
178 DanfossAirUnit localAirUnit = this.airUnit;
179 if (localAirUnit == null) {
183 logger.debug("Initializing DanfossHRV properties '{}'", getThing().getUID());
186 Map<String, String> properties = new HashMap<>(2);
187 properties.put(PROPERTY_UNIT_NAME, localAirUnit.getUnitName());
188 properties.put(PROPERTY_SERIAL, localAirUnit.getUnitSerialNumber());
189 updateProperties(properties);
190 propertiesInitializedSuccessfully = true;
191 updateStatus(ThingStatus.ONLINE);
192 } catch (IOException e) {
193 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, e.getMessage());
194 logger.debug("Cannot initialize properties: an error occurred: {}", e.getMessage());
197 return propertiesInitializedSuccessfully;
201 public void dispose() {
202 logger.debug("Disposing Danfoss HRV handler '{}'", getThing().getUID());
208 DanfossAirUnitCommunicationController localCommunicationController = this.communicationController;
209 if (localCommunicationController != null) {
210 localCommunicationController.disconnect();
212 this.communicationController = null;
215 private synchronized void startPolling() {
216 this.pollingJob = scheduler.scheduleWithFixedDelay(this::updateAllChannels, POLLING_INTERVAL_SECONDS,
217 config.refreshInterval, TimeUnit.SECONDS);
220 private synchronized void stopPolling() {
221 ScheduledFuture<?> localPollingJob = this.pollingJob;
222 if (localPollingJob != null) {
223 localPollingJob.cancel(true);
225 this.pollingJob = null;
228 private void updateState(String groupId, String channelId, State state) {
229 ValueCache cache = valueCache;
234 if (cache.updateValue(channelId, state)) {
235 updateState(new ChannelUID(thing.getUID(), groupId, channelId), state);