2 * Copyright (c) 2010-2023 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.plugwise.internal.protocol;
15 import static java.time.ZoneOffset.UTC;
16 import static org.openhab.binding.plugwise.internal.protocol.field.MessageType.POWER_INFORMATION_RESPONSE;
18 import java.time.Duration;
19 import java.time.ZonedDateTime;
20 import java.util.regex.Matcher;
21 import java.util.regex.Pattern;
23 import org.openhab.binding.plugwise.internal.protocol.field.Energy;
24 import org.openhab.binding.plugwise.internal.protocol.field.MACAddress;
27 * Contains the real-time energy consumption of a relay device (Circle, Circle+, Stealth). This
28 * message is the response of a {@link PowerInformationRequestMessage}.
30 * @author Wouter Born, Karel Goderis - Initial contribution
32 public class PowerInformationResponseMessage extends Message {
34 private static final Pattern PAYLOAD_PATTERN = Pattern.compile("(\\w{16})(\\w{4})(\\w{4})(\\w{8})(\\w{8})(\\w{4})");
35 private static final double NANOSECONDS_CORRECTION_DIVISOR = 0.000046875; // 46875 divided by nanos per second
36 private static final Duration ONE_HOUR = Duration.ofHours(1);
38 private Energy oneSecond;
39 private Energy eightSecond;
40 private Energy oneHourConsumed;
41 private Energy oneHourProduced;
42 private long nanosCorrection;
44 public PowerInformationResponseMessage(int sequenceNumber, String payload) {
45 super(POWER_INFORMATION_RESPONSE, sequenceNumber, payload);
48 public Energy getEightSecond() {
52 public Energy getOneHourConsumed() {
53 return oneHourConsumed;
56 public Energy getOneHourProduced() {
57 return oneHourProduced;
60 public Energy getOneSecond() {
65 protected void parsePayload() {
66 Matcher matcher = PAYLOAD_PATTERN.matcher(payload);
67 if (matcher.matches()) {
68 ZonedDateTime utcNow = ZonedDateTime.now(UTC);
69 macAddress = new MACAddress(matcher.group(1));
70 nanosCorrection = Math.round(Integer.parseInt(matcher.group(6), 16) / NANOSECONDS_CORRECTION_DIVISOR);
71 oneSecond = new Energy(utcNow, (short) Integer.parseInt(matcher.group(2), 16),
72 Duration.ofSeconds(1, nanosCorrection));
73 eightSecond = new Energy(utcNow, (short) Integer.parseInt(matcher.group(3), 16),
74 Duration.ofSeconds(8, nanosCorrection));
75 oneHourConsumed = new Energy(utcNow, Long.parseLong(matcher.group(4), 16), ONE_HOUR);
76 oneHourProduced = new Energy(utcNow, Long.parseLong(matcher.group(5), 16), ONE_HOUR);
78 throw new PlugwisePayloadMismatchException(POWER_INFORMATION_RESPONSE, PAYLOAD_PATTERN, payload);