]> git.basschouten.com Git - openhab-addons.git/blob
e4a6d7947376141a3f4d8fccd85cad5e9b7de576
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.nikohomecontrol.internal.handler;
14
15 import static org.openhab.binding.nikohomecontrol.internal.NikoHomeControlBindingConstants.CHANNEL_POWER;
16 import static org.openhab.core.types.RefreshType.REFRESH;
17
18 import java.util.HashMap;
19 import java.util.Map;
20
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.openhab.binding.nikohomecontrol.internal.protocol.NhcEnergyMeter;
24 import org.openhab.binding.nikohomecontrol.internal.protocol.NhcEnergyMeterEvent;
25 import org.openhab.binding.nikohomecontrol.internal.protocol.NikoHomeControlCommunication;
26 import org.openhab.binding.nikohomecontrol.internal.protocol.nhc2.NhcEnergyMeter2;
27 import org.openhab.core.library.types.QuantityType;
28 import org.openhab.core.library.unit.Units;
29 import org.openhab.core.thing.Bridge;
30 import org.openhab.core.thing.ChannelUID;
31 import org.openhab.core.thing.Thing;
32 import org.openhab.core.thing.ThingStatus;
33 import org.openhab.core.thing.ThingStatusDetail;
34 import org.openhab.core.thing.binding.BaseThingHandler;
35 import org.openhab.core.types.Command;
36 import org.openhab.core.types.UnDefType;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41  * The {@link NikoHomeControlEnergyMeterHandler} is responsible for handling commands, which are
42  * sent to one of the channels.
43  *
44  * @author Mark Herwege - Initial Contribution
45  */
46 @NonNullByDefault
47 public class NikoHomeControlEnergyMeterHandler extends BaseThingHandler implements NhcEnergyMeterEvent {
48
49     private final Logger logger = LoggerFactory.getLogger(NikoHomeControlEnergyMeterHandler.class);
50
51     private volatile @Nullable NhcEnergyMeter nhcEnergyMeter;
52
53     private String energyMeterId = "";
54
55     public NikoHomeControlEnergyMeterHandler(Thing thing) {
56         super(thing);
57     }
58
59     @Override
60     public void handleCommand(ChannelUID channelUID, Command command) {
61         NhcEnergyMeter nhcEnergyMeter = this.nhcEnergyMeter;
62         if (nhcEnergyMeter == null) {
63             logger.debug("energy meter with ID {} not initialized", energyMeterId);
64             return;
65         }
66
67         if (REFRESH.equals(command)) {
68             energyMeterEvent(nhcEnergyMeter.getPower());
69         }
70     }
71
72     @Override
73     public void initialize() {
74         NikoHomeControlEnergyMeterConfig config = getConfig().as(NikoHomeControlEnergyMeterConfig.class);
75
76         energyMeterId = config.energyMeterId;
77
78         NikoHomeControlCommunication nhcComm = getCommunication();
79         if (nhcComm == null) {
80             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED,
81                     "@text/offline.bridge-unitialized");
82             return;
83         } else {
84             updateStatus(ThingStatus.UNKNOWN);
85         }
86
87         // We need to do this in a separate thread because we may have to wait for the
88         // communication to become active
89         scheduler.submit(() -> {
90             if (!nhcComm.communicationActive()) {
91                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
92                         "@text/offline.communication-error");
93                 return;
94             }
95
96             NhcEnergyMeter nhcEnergyMeter = nhcComm.getEnergyMeters().get(energyMeterId);
97             if (nhcEnergyMeter == null) {
98                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
99                         "@text/offline.configuration-error.energyMeterId");
100                 return;
101             }
102
103             nhcEnergyMeter.setEventHandler(this);
104
105             updateProperties();
106
107             // Subscribing to power readings starts an intensive data flow, therefore only do it when there is an item
108             // linked to the channel
109             if (isLinked(CHANNEL_POWER)) {
110                 nhcComm.startEnergyMeter(energyMeterId);
111             }
112
113             this.nhcEnergyMeter = nhcEnergyMeter;
114
115             logger.debug("energy meter intialized {}", energyMeterId);
116
117             Bridge bridge = getBridge();
118             if ((bridge != null) && (bridge.getStatus() == ThingStatus.ONLINE)) {
119                 updateStatus(ThingStatus.ONLINE);
120             } else {
121                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
122             }
123         });
124     }
125
126     @Override
127     public void dispose() {
128         NikoHomeControlCommunication nhcComm = getCommunication();
129
130         if (nhcComm != null) {
131             nhcComm.stopEnergyMeter(energyMeterId);
132         }
133     }
134
135     private void updateProperties() {
136         Map<String, String> properties = new HashMap<>();
137
138         if (nhcEnergyMeter instanceof NhcEnergyMeter2) {
139             NhcEnergyMeter2 energyMeter = (NhcEnergyMeter2) nhcEnergyMeter;
140             properties.put("model", energyMeter.getModel());
141             properties.put("technology", energyMeter.getTechnology());
142         }
143
144         thing.setProperties(properties);
145     }
146
147     @Override
148     public void energyMeterEvent(@Nullable Integer power) {
149         if (power == null) {
150             updateState(CHANNEL_POWER, UnDefType.UNDEF);
151         } else {
152             updateState(CHANNEL_POWER, new QuantityType<>(power, Units.WATT));
153         }
154         updateStatus(ThingStatus.ONLINE);
155     }
156
157     @Override
158     public void energyMeterInitialized() {
159         Bridge bridge = getBridge();
160         if ((bridge != null) && (bridge.getStatus() == ThingStatus.ONLINE)) {
161             updateStatus(ThingStatus.ONLINE);
162         }
163     }
164
165     @Override
166     public void energyMeterRemoved() {
167         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
168                 "@text/offline.configuration-error.energyMeterRemoved");
169     }
170
171     @Override
172     // Subscribing to power readings starts an intensive data flow, therefore only do it when there is an item linked to
173     // the channel
174     public void channelLinked(ChannelUID channelUID) {
175         NikoHomeControlCommunication nhcComm = getCommunication();
176         if (nhcComm != null) {
177             // This can be expensive, therefore do it in a job.
178             scheduler.submit(() -> {
179                 if (!nhcComm.communicationActive()) {
180                     restartCommunication(nhcComm);
181                 }
182
183                 if (nhcComm.communicationActive()) {
184                     nhcComm.startEnergyMeter(energyMeterId);
185                     updateStatus(ThingStatus.ONLINE);
186                 }
187             });
188         }
189     }
190
191     @Override
192     public void channelUnlinked(ChannelUID channelUID) {
193         NikoHomeControlCommunication nhcComm = getCommunication();
194         if (nhcComm != null) {
195             // This can be expensive, therefore do it in a job.
196             scheduler.submit(() -> {
197                 if (!nhcComm.communicationActive()) {
198                     restartCommunication(nhcComm);
199                 }
200
201                 if (nhcComm.communicationActive()) {
202                     nhcComm.stopEnergyMeter(energyMeterId);
203                     // as this is momentary power production/consumption, we set it UNDEF as we do not get readings
204                     // anymore
205                     updateState(CHANNEL_POWER, UnDefType.UNDEF);
206                     updateStatus(ThingStatus.ONLINE);
207                 }
208             });
209         }
210     }
211
212     private void restartCommunication(NikoHomeControlCommunication nhcComm) {
213         // We lost connection but the connection object is there, so was correctly started.
214         // Try to restart communication.
215         nhcComm.restartCommunication();
216         // If still not active, take thing offline and return.
217         if (!nhcComm.communicationActive()) {
218             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
219                     "@text/offline.communication-error");
220             return;
221         }
222         // Also put the bridge back online
223         NikoHomeControlBridgeHandler nhcBridgeHandler = getBridgeHandler();
224         if (nhcBridgeHandler != null) {
225             nhcBridgeHandler.bridgeOnline();
226         } else {
227             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED,
228                     "@text/offline.bridge-unitialized");
229         }
230     }
231
232     private @Nullable NikoHomeControlCommunication getCommunication() {
233         NikoHomeControlBridgeHandler nhcBridgeHandler = getBridgeHandler();
234         return nhcBridgeHandler != null ? nhcBridgeHandler.getCommunication() : null;
235     }
236
237     private @Nullable NikoHomeControlBridgeHandler getBridgeHandler() {
238         Bridge nhcBridge = getBridge();
239         return nhcBridge != null ? (NikoHomeControlBridgeHandler) nhcBridge.getHandler() : null;
240     }
241 }