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.binding.modbus.e3dc.internal.dto;
15 import java.nio.ByteBuffer;
16 import java.nio.charset.StandardCharsets;
17 import java.util.BitSet;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
22 * The {@link DataConverter} Helper class to convert bytes from modbus into desired data format
24 * @author Bernd Weymann - Initial contribution
27 public class DataConverter {
28 private static final long MAX_INT32 = (long) Math.pow(2, Integer.SIZE);
31 * Get unit16 value from 2 bytes
36 public static int getUInt16Value(ByteBuffer wrap) {
37 return Short.toUnsignedInt(wrap.getShort());
41 * Get unit32 value from 4 bytes
46 public static long getLongValue(ByteBuffer wrap) {
47 return Integer.toUnsignedLong(wrap.getInt());
51 * Get double value from 2 bytes with correction factor
56 public static double getUDoubleValue(ByteBuffer wrap, double factor) {
57 return round(getUInt16Value(wrap) * factor, 2);
61 * Conversion done according to E3DC Modbus Specification V1.7
64 * @return decoded long value, Long.MIN_VALUE otherwise
66 public static long getInt32Swap(ByteBuffer wrap) {
67 long a = getUInt16Value(wrap);
68 long b = getUInt16Value(wrap);
72 return (MAX_INT32 - b * 65536 - a) * -1;
76 public static String getString(byte[] bArray) {
77 return new String(bArray, StandardCharsets.US_ASCII).trim();
80 public static int toInt(BitSet bitSet) {
82 for (int bit = 0; bit < bitSet.length(); bit++) {
83 if (bitSet.get(bit)) {
84 intValue |= (1 << bit);
90 public static double round(double value, int places) {
92 throw new IllegalArgumentException();
95 long factor = (long) Math.pow(10, places);
96 value = value * factor;
97 long tmp = Math.round(value);
98 return (double) tmp / factor;