2 * Copyright (c) 2010-2020 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.io.transport.modbus;
15 import java.util.Arrays;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.openhab.core.util.HexUtils;
21 * Immutable {@link ModbusRegisterArray} implementation
23 * @author Sami Salonen - Initial contribution
26 public class ModbusRegisterArray {
28 private final byte[] bytes;
30 public ModbusRegisterArray(byte... bytes) {
31 if (bytes.length % 2 != 0) {
32 throw new IllegalArgumentException();
34 this.bytes = Arrays.copyOf(bytes, bytes.length);
38 * Construct plain <code>ModbusRegisterArray</code> array from register values
40 * @param registerValues register values, each <code>int</code> corresponding to one register
43 public ModbusRegisterArray(int... registerValues) {
44 bytes = new byte[registerValues.length * 2];
45 for (int registerIndex = 0; registerIndex < registerValues.length; registerIndex++) {
46 int register = registerValues[registerIndex] & 0xffff;
48 bytes[registerIndex * 2] = (byte) (register >> 8);
50 bytes[registerIndex * 2 + 1] = (byte) register;
55 * Get register index i as unsigned integer
57 * @param i register index
58 * @return register value interpreted as unsigned integer (big-endian byte ordering)
60 public int getRegister(int i) {
61 int hi = bytes[i * 2] & 0xff;
62 int lo = bytes[i * 2 + 1] & 0xff;
63 return ((hi << 8) | lo) & 0xffff;
67 * Return bytes representing the registers
70 * Index 0: hi-byte of 1st register
71 * Index 1: low-byte of 1st register
72 * Index 3: hi-byte of 2nd register
73 * Index 4: low-byte of 2nd register
76 * @return set of bytes
78 public byte[] getBytes() {
83 * Get number of registers stored in this instance
88 return bytes.length / 2;
92 public String toString() {
93 if (bytes.length == 0) {
94 return "ModbusRegisterArray(<empty>)";
96 return new StringBuilder(bytes.length).append("ModbusRegisterArray(").append(toHexString()).append(')')
101 * Get register data as a hex string
103 * For example, 04 45 00 00
105 * @return string representing the bytes of the register array
107 public String toHexString() {
111 return HexUtils.bytesToHex(getBytes());