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.nikohomecontrol.internal.handler;
15 import static org.openhab.binding.nikohomecontrol.internal.NikoHomeControlBindingConstants.*;
16 import static org.openhab.core.library.unit.Units.KILOWATT_HOUR;
17 import static org.openhab.core.types.RefreshType.REFRESH;
19 import java.time.LocalDateTime;
20 import java.time.ZoneOffset;
21 import java.time.ZonedDateTime;
22 import java.time.format.DateTimeFormatter;
23 import java.util.HashMap;
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.nikohomecontrol.internal.protocol.NhcMeter;
29 import org.openhab.binding.nikohomecontrol.internal.protocol.NhcMeterEvent;
30 import org.openhab.binding.nikohomecontrol.internal.protocol.NikoHomeControlCommunication;
31 import org.openhab.binding.nikohomecontrol.internal.protocol.NikoHomeControlConstants.MeterType;
32 import org.openhab.binding.nikohomecontrol.internal.protocol.nhc1.NhcMeter1;
33 import org.openhab.binding.nikohomecontrol.internal.protocol.nhc2.NhcMeter2;
34 import org.openhab.core.library.types.DateTimeType;
35 import org.openhab.core.library.types.QuantityType;
36 import org.openhab.core.library.unit.SIUnits;
37 import org.openhab.core.library.unit.Units;
38 import org.openhab.core.thing.Bridge;
39 import org.openhab.core.thing.ChannelUID;
40 import org.openhab.core.thing.Thing;
41 import org.openhab.core.thing.ThingStatus;
42 import org.openhab.core.thing.ThingStatusDetail;
43 import org.openhab.core.types.Command;
44 import org.openhab.core.types.UnDefType;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
49 * The {@link NikoHomeControlMeterHandler} is responsible for handling commands, which are
50 * sent to one of the channels.
52 * @author Mark Herwege - Initial Contribution
55 public class NikoHomeControlMeterHandler extends NikoHomeControlBaseHandler implements NhcMeterEvent {
57 private final Logger logger = LoggerFactory.getLogger(NikoHomeControlMeterHandler.class);
59 private static final DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
61 private volatile @Nullable NhcMeter nhcMeter;
63 public NikoHomeControlMeterHandler(Thing thing) {
68 void handleCommandSelection(ChannelUID channelUID, Command command) {
69 NhcMeter nhcMeter = this.nhcMeter;
70 if (nhcMeter == null) {
71 logger.debug("meter with ID {} not initialized", deviceId);
75 if (REFRESH.equals(command)) {
76 switch (channelUID.getId()) {
78 meterPowerEvent(nhcMeter.getPower());
83 case CHANNEL_ENERGY_DAY:
85 case CHANNEL_WATER_DAY:
86 case CHANNEL_ENERGY_LAST:
87 case CHANNEL_GAS_LAST:
88 case CHANNEL_WATER_LAST:
89 LocalDateTime lastReadingUTC = nhcMeter.getLastReading();
90 if (lastReadingUTC != null) {
91 meterReadingEvent(nhcMeter.getReading(), nhcMeter.getDayReading(), lastReadingUTC);
95 logger.debug("unexpected command for channel {}", channelUID.getId());
101 public void initialize() {
104 NikoHomeControlMeterConfig config = getConfig().as(NikoHomeControlMeterConfig.class);
105 deviceId = config.meterId;
107 NikoHomeControlBridgeHandler bridgeHandler = getBridgeHandler();
108 if (bridgeHandler == null) {
109 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
110 "@text/offline.configuration-error.invalid-bridge-handler");
114 updateStatus(ThingStatus.UNKNOWN);
116 Bridge bridge = getBridge();
117 if ((bridge != null) && ThingStatus.ONLINE.equals(bridge.getStatus())) {
118 // We need to do this in a separate thread because we may have to wait for the
119 // communication to become active
120 commStartThread = scheduler.submit(this::startCommunication);
125 synchronized void startCommunication() {
126 NikoHomeControlCommunication nhcComm = getCommunication(getBridgeHandler());
128 if (nhcComm == null) {
132 if (!nhcComm.communicationActive()) {
133 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
134 "@text/offline.communication-error");
138 NhcMeter nhcMeter = nhcComm.getMeters().get(deviceId);
139 if (nhcMeter == null) {
140 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
141 "@text/offline.configuration-error.deviceId");
145 MeterType meterType = nhcMeter.getType();
146 if (!(MeterType.ENERGY_LIVE.equals(meterType) || MeterType.ENERGY.equals(meterType)
147 || MeterType.GAS.equals(meterType) || MeterType.WATER.equals(meterType))) {
148 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
149 "@text/offline.configuration-error.meterType");
153 nhcMeter.setEventHandler(this);
155 updateProperties(nhcMeter);
157 String location = nhcMeter.getLocation();
158 if (thing.getLocation() == null) {
159 thing.setLocation(location);
162 this.nhcMeter = nhcMeter;
170 NikoHomeControlCommunication nhcComm = getCommunication(getBridgeHandler());
171 if (nhcComm != null) {
172 nhcComm.startMeter(deviceId, getConfig().as(NikoHomeControlMeterConfig.class).refresh);
173 // Subscribing to power readings starts an intensive data flow, therefore only do it when there is an item
174 // linked to the channel
175 if (isLinked(CHANNEL_POWER)) {
176 nhcComm.startMeterLive(deviceId);
182 public void dispose() {
183 NikoHomeControlCommunication nhcComm = getCommunication(getBridgeHandler());
184 if (nhcComm != null) {
185 nhcComm.stopMeterLive(deviceId);
186 nhcComm.stopMeter(deviceId);
187 NhcMeter meter = nhcComm.getMeters().get(deviceId);
189 meter.unsetEventHandler();
196 private void updateProperties(NhcMeter nhcMeter) {
197 Map<String, String> properties = new HashMap<>();
199 if (nhcMeter instanceof NhcMeter1) {
200 NhcMeter1 meter = (NhcMeter1) nhcMeter;
201 properties.put("type", meter.getMeterType());
202 LocalDateTime referenceDate = meter.getReferenceDate();
203 if (referenceDate != null) {
204 properties.put("startdateUTC", referenceDate.format(DATE_TIME_FORMAT));
206 } else if (nhcMeter instanceof NhcMeter2) {
207 NhcMeter2 meter = (NhcMeter2) nhcMeter;
208 properties.put(PROPERTY_DEVICE_TYPE, meter.getDeviceType());
209 properties.put(PROPERTY_DEVICE_TECHNOLOGY, meter.getDeviceTechnology());
210 properties.put(PROPERTY_DEVICE_MODEL, meter.getDeviceModel());
213 thing.setProperties(properties);
217 public void meterPowerEvent(@Nullable Integer power) {
218 NhcMeter nhcMeter = this.nhcMeter;
219 if (nhcMeter == null) {
220 logger.debug("meter with ID {} not initialized", deviceId);
224 MeterType meterType = nhcMeter.getType();
225 if (meterType != MeterType.ENERGY_LIVE) {
226 logger.debug("meter with ID {} does not support live readings", deviceId);
231 updateState(CHANNEL_POWER, UnDefType.UNDEF);
233 boolean invert = getConfig().as(NikoHomeControlMeterConfig.class).invert;
234 int value = (invert ? -1 : 1) * power;
235 updateState(CHANNEL_POWER, new QuantityType<>(value, Units.WATT));
237 updateStatus(ThingStatus.ONLINE);
241 public void meterReadingEvent(double meterReading, double meterReadingDay, LocalDateTime lastReadingUTC) {
242 NhcMeter nhcMeter = this.nhcMeter;
243 if (nhcMeter == null) {
244 logger.debug("meter with ID {} not initialized", deviceId);
248 NikoHomeControlBridgeHandler bridgeHandler = getBridgeHandler();
249 if (bridgeHandler == null) {
250 logger.debug("Cannot update meter channels, no bridge handler");
253 ZonedDateTime lastReading = lastReadingUTC.atZone(ZoneOffset.UTC)
254 .withZoneSameInstant(bridgeHandler.getTimeZone());
256 boolean invert = getConfig().as(NikoHomeControlMeterConfig.class).invert;
257 double value = (invert ? -1 : 1) * meterReading;
258 double dayValue = (invert ? -1 : 1) * meterReadingDay;
260 MeterType meterType = nhcMeter.getType();
264 updateState(CHANNEL_ENERGY, new QuantityType<>(value, KILOWATT_HOUR));
265 updateState(CHANNEL_ENERGY_DAY, new QuantityType<>(dayValue, KILOWATT_HOUR));
266 updateState(CHANNEL_ENERGY_LAST, new DateTimeType(lastReading));
267 updateStatus(ThingStatus.ONLINE);
270 updateState(CHANNEL_GAS, new QuantityType<>(value, SIUnits.CUBIC_METRE));
271 updateState(CHANNEL_GAS_DAY, new QuantityType<>(dayValue, SIUnits.CUBIC_METRE));
272 updateState(CHANNEL_GAS_LAST, new DateTimeType(lastReading));
273 updateStatus(ThingStatus.ONLINE);
276 updateState(CHANNEL_WATER, new QuantityType<>(value, SIUnits.CUBIC_METRE));
277 updateState(CHANNEL_WATER_DAY, new QuantityType<>(dayValue, SIUnits.CUBIC_METRE));
278 updateState(CHANNEL_WATER_LAST, new DateTimeType(lastReading));
279 updateStatus(ThingStatus.ONLINE);
287 public void channelLinked(ChannelUID channelUID) {
288 // Subscribing to power readings starts an intensive data flow, therefore only do it when there is an item
289 // linked to the channel
290 if (!CHANNEL_POWER.equals(channelUID.getId())) {
293 NikoHomeControlCommunication nhcComm = getCommunication(getBridgeHandler());
294 if (nhcComm != null) {
295 // This can be expensive, therefore do it in a job.
296 scheduler.submit(() -> {
297 if (!nhcComm.communicationActive()) {
298 restartCommunication(nhcComm);
301 if (nhcComm.communicationActive()) {
302 nhcComm.startMeterLive(deviceId);
309 public void channelUnlinked(ChannelUID channelUID) {
310 if (!CHANNEL_POWER.equals(channelUID.getId())) {
313 NikoHomeControlCommunication nhcComm = getCommunication(getBridgeHandler());
314 if (nhcComm != null) {
315 // This can be expensive, therefore do it in a job.
316 scheduler.submit(() -> {
317 if (!nhcComm.communicationActive()) {
318 restartCommunication(nhcComm);
321 if (nhcComm.communicationActive()) {
322 nhcComm.stopMeterLive(deviceId);
323 // as this is momentary power production/consumption, we set it UNDEF as we do not get readings
325 updateState(CHANNEL_POWER, UnDefType.UNDEF);