]> git.basschouten.com Git - openhab-addons.git/blob
f048dde61ada926281351fe1c12c6d641294103f
[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.modbus.e3dc.internal.dto;
14
15 import java.nio.charset.StandardCharsets;
16 import java.util.BitSet;
17
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.openhab.core.io.transport.modbus.ModbusBitUtilities;
20 import org.openhab.core.io.transport.modbus.ValueBuffer;
21
22 /**
23  * The {@link DataConverter} Helper class to convert bytes from modbus into desired data format
24  *
25  * @author Bernd Weymann - Initial contribution
26  */
27 @NonNullByDefault
28 public class DataConverter {
29
30     /**
31      * Get double value from 2 bytes with correction factor
32      *
33      * @param wrap
34      * @return double
35      */
36     public static double getUDoubleValue(ValueBuffer wrap, double factor) {
37         return round(wrap.getUInt16() * factor, 2);
38     }
39
40     public static String getString(byte[] bArray) {
41         return ModbusBitUtilities.extractStringFromBytes(bArray, 0, bArray.length, StandardCharsets.US_ASCII).trim();
42     }
43
44     public static int toInt(BitSet bitSet) {
45         int intValue = 0;
46         for (int bit = 0; bit < bitSet.length(); bit++) {
47             if (bitSet.get(bit)) {
48                 intValue |= (1 << bit);
49             }
50         }
51         return intValue;
52     }
53
54     public static double round(double value, int places) {
55         if (places < 0) {
56             throw new IllegalArgumentException();
57         }
58
59         long factor = (long) Math.pow(10, places);
60         long tmp = Math.round(value * factor);
61         return (double) tmp / factor;
62     }
63 }