]> git.basschouten.com Git - openhab-addons.git/blob
7ac433530ef10c14b06ccefd736863b1414c69e9
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.smaenergymeter.internal.handler;
14
15 import java.nio.ByteBuffer;
16 import java.util.Arrays;
17
18 /**
19  * The {@link FieldDTO} class holds the data for a single field (i.e. the power purchased).
20  *
21  * @author Osman Basha - Initial contribution
22  */
23 public class FieldDTO {
24
25     private final int address;
26     private final int length;
27     private final int divisor;
28     private float value;
29
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");
34         }
35         this.length = length;
36         this.divisor = divisor;
37     }
38
39     public float getValue() {
40         return value;
41     }
42
43     public void updateValue(byte[] bytes) {
44         if (length == 4) {
45             value = (float) bytesToUInt16(Arrays.copyOfRange(bytes, address, address + 4)) / divisor;
46         } else {
47             value = (float) bytesToUInt32(Arrays.copyOfRange(bytes, address, address + 8)) / divisor;
48         }
49     }
50
51     private int bytesToUInt16(byte[] bytes) {
52         ByteBuffer buffer = ByteBuffer.wrap(bytes);
53         return buffer.getInt();
54     }
55
56     private long bytesToUInt32(byte[] bytes) {
57         ByteBuffer buffer = ByteBuffer.wrap(bytes);
58         return buffer.getLong();
59     }
60 }