]> git.basschouten.com Git - openhab-addons.git/blob
a762524dd5479f90bd908e0529e91235cda88bb9
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.danfossairunit.internal.handler;
14
15 import static org.openhab.binding.danfossairunit.internal.DanfossAirUnitBindingConstants.*;
16
17 import java.io.IOException;
18 import java.net.InetAddress;
19 import java.net.UnknownHostException;
20 import java.util.HashMap;
21 import java.util.Map;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.TimeUnit;
24
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;
47
48 /**
49  * The {@link DanfossAirUnitHandler} is responsible for handling commands, which are
50  * sent to one of the channels.
51  *
52  * @author Ralf Duckstein - Initial contribution
53  * @author Robert Bach - heavy refactorings
54  * @author Jacob Laursen - Refactoring, bugfixes and enhancements
55  */
56 @NonNullByDefault
57 public class DanfossAirUnitHandler extends BaseThingHandler {
58
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;
68
69     public DanfossAirUnitHandler(Thing thing) {
70         super(thing);
71     }
72
73     @Override
74     public void handleCommand(ChannelUID channelUID, Command command) {
75         if (command instanceof RefreshType) {
76             updateAllChannels();
77         } else {
78             try {
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));
85                     }
86                 } else {
87                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.NONE,
88                             "@text/offline.connection-not-initialized");
89                     return;
90                 }
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());
95             }
96         }
97     }
98
99     @Override
100     public void initialize() {
101         updateStatus(ThingStatus.UNKNOWN);
102         config = getConfigAs(DanfossAirUnitConfiguration.class);
103         valueCache = new ValueCache(config.updateUnchangedValuesEveryMillis);
104         removeDeprecatedChannels();
105         try {
106             var localCommunicationController = new DanfossAirUnitCommunicationController(
107                     InetAddress.getByName(config.host), TCP_PORT);
108             this.communicationController = localCommunicationController;
109             this.airUnit = new DanfossAirUnit(localCommunicationController);
110             startPolling();
111         } catch (UnknownHostException e) {
112             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
113                     "@text/offline.communication-error.unknown-host [\"" + config.host + "\"]");
114             return;
115         }
116     }
117
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);
127         } else {
128             logger.debug("Removing deprecated unlinked channel '{}'.", manualFanSpeedChannelUid);
129             updateThing(editThing().withoutChannel(manualFanSpeedChannelUid).build());
130         }
131     }
132
133     private void updateAllChannels() {
134         if (!initializeProperties()) {
135             return;
136         }
137
138         DanfossAirUnit localAirUnit = this.airUnit;
139         if (localAirUnit == null) {
140             return;
141         }
142
143         logger.debug("Updating DanfossHRV data '{}'", getThing().getUID());
144
145         for (Channel channel : Channel.values()) {
146             if (Thread.interrupted()) {
147                 logger.debug("Polling thread interrupted...");
148                 return;
149             }
150             try {
151                 updateState(channel.getGroup().getGroupName(), channel.getChannelName(),
152                         channel.getReadAccessor().access(localAirUnit));
153                 if (getThing().getStatus() != ThingStatus.ONLINE) {
154                     updateStatus(ThingStatus.ONLINE);
155                 }
156             } catch (UnexpectedResponseValueException e) {
157                 updateState(channel.getGroup().getGroupName(), channel.getChannelName(), UnDefType.UNDEF);
158                 logger.debug(
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);
163                 }
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());
169             }
170         }
171     }
172
173     private synchronized boolean initializeProperties() {
174         if (propertiesInitializedSuccessfully) {
175             return true;
176         }
177
178         DanfossAirUnit localAirUnit = this.airUnit;
179         if (localAirUnit == null) {
180             return false;
181         }
182
183         logger.debug("Initializing DanfossHRV properties '{}'", getThing().getUID());
184
185         try {
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());
195         }
196
197         return propertiesInitializedSuccessfully;
198     }
199
200     @Override
201     public void dispose() {
202         logger.debug("Disposing Danfoss HRV handler '{}'", getThing().getUID());
203
204         stopPolling();
205
206         this.airUnit = null;
207
208         DanfossAirUnitCommunicationController localCommunicationController = this.communicationController;
209         if (localCommunicationController != null) {
210             localCommunicationController.disconnect();
211         }
212         this.communicationController = null;
213     }
214
215     private synchronized void startPolling() {
216         this.pollingJob = scheduler.scheduleWithFixedDelay(this::updateAllChannels, POLLING_INTERVAL_SECONDS,
217                 config.refreshInterval, TimeUnit.SECONDS);
218     }
219
220     private synchronized void stopPolling() {
221         ScheduledFuture<?> localPollingJob = this.pollingJob;
222         if (localPollingJob != null) {
223             localPollingJob.cancel(true);
224         }
225         this.pollingJob = null;
226     }
227
228     private void updateState(String groupId, String channelId, State state) {
229         ValueCache cache = valueCache;
230         if (cache == null) {
231             return;
232         }
233
234         if (cache.updateValue(channelId, state)) {
235             updateState(new ChannelUID(thing.getUID(), groupId, channelId), state);
236         }
237     }
238 }