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.smaenergymeter.internal.handler;
15 import java.nio.ByteBuffer;
16 import java.util.Arrays;
19 * The {@link FieldDTO} class holds the data for a single field (i.e. the power purchased).
21 * @author Osman Basha - Initial contribution
23 public class FieldDTO {
25 private final int address;
26 private final int length;
27 private final int divisor;
30 public FieldDTO(int address, int length, int divisor) {
31 this.address = address;
32 if ((length != 4) && (length != 8)) {
33 throw new IllegalArgumentException("length should be 4 or 8 bytes");
36 this.divisor = divisor;
39 public float getValue() {
43 public void updateValue(byte[] bytes) {
45 value = (float) bytesToUInt16(Arrays.copyOfRange(bytes, address, address + 4)) / divisor;
47 value = (float) bytesToUInt32(Arrays.copyOfRange(bytes, address, address + 8)) / divisor;
51 private int bytesToUInt16(byte[] bytes) {
52 ByteBuffer buffer = ByteBuffer.wrap(bytes);
53 return buffer.getInt();
56 private long bytesToUInt32(byte[] bytes) {
57 ByteBuffer buffer = ByteBuffer.wrap(bytes);
58 return buffer.getLong();