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 org.eclipse.jdt.annotation.NonNullByDefault;
17 import net.wimpi.modbus.procimg.SimpleInputRegister;
20 * Basic {@link ModbusRegister} implementation
22 * @author Sami Salonen - Initial contribution
25 public class ModbusRegister {
27 private final SimpleInputRegister wrapped;
30 * Constructs a new instance for bytes
32 * @param b1 the first (hi) byte of the word.
33 * @param b2 the second (low) byte of the word.
35 public ModbusRegister(byte b1, byte b2) {
36 wrapped = new SimpleInputRegister(b1, b2);
40 * Construct register for at
42 * @param val value representing register data. The <code>int</code> will be downcasted to <code>short</code>.
44 public ModbusRegister(int val) {
45 wrapped = new SimpleInputRegister(val);
49 * Get raw data represented by this register. Since register is 16 bits, array of length 2 will be returned.
51 * @return byte array of length 2, high byte first.
53 public byte[] getBytes() {
54 return wrapped.toBytes();
58 * Returns the value of this register as integer representing 16 bit data parsed as signed integer.
60 * @return the register content as unsigned integer
62 public int getValue() {
63 return wrapped.getValue();
67 * Returns the value of this register as integer representing 16 bit data parsed as unsigned integer.
69 * @return the register content as unsigned integer
71 public int toUnsignedShort() {
72 return wrapped.toUnsignedShort();
76 public String toString() {
77 StringBuffer buffer = new StringBuffer("ModbusRegisterImpl(");
78 buffer.append("uint16=").append(toUnsignedShort()).append(", hex=");
79 return appendHexString(buffer).append(')').toString();
83 * Returns the register value as hex string
87 * @return string representing the register data
89 public String toHexString() {
90 StringBuffer buffer = new StringBuffer(5);
91 return appendHexString(buffer).toString();
95 * Appends the register value as hex string to the given StringBuffer
98 public StringBuffer appendHexString(StringBuffer buffer) {
99 byte[] bytes = getBytes();
100 for (int i = 0; i < 2; i++) {
102 String byteHex = Long.toHexString(b & 0xff);
103 if ((b & 0xff) < 0x10) {
106 buffer.append(byteHex);