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.test;
15 import static org.junit.jupiter.api.Assertions.assertTrue;
17 import java.nio.ByteBuffer;
19 import org.junit.jupiter.api.Test;
20 import org.openhab.io.transport.modbus.ModbusBitUtilities;
24 * Tests for 'special' float values such as infinity and NaN. These are not covered in detail in
25 * {@link BitUtilitiesExtractIndividualMethodsTest} and
26 * {@link BitUtilitiesExtractStateFromRegistersTest}
28 * @author Sami Salonen - Initial contribution
30 public class BitUtilitiesExtractFloat32Test {
33 * Creates a byte array with byteOffset number of zeroes, followed by 32bit of data represented by data
35 * @param data actual data payload
36 * @param byteOffset number of zeros padded
37 * @return byte array of size 4 + byteOffset
39 private static byte[] bytes(int data, int byteOffset) {
40 ByteBuffer buffer = ByteBuffer.allocate(4 + byteOffset);
41 for (int i = 0; i < byteOffset; i++) {
45 return buffer.array();
48 private static void testFloat(float number) {
49 int data = Float.floatToIntBits(number);
50 for (int byteOffset = 0; byteOffset < 5; byteOffset++) {
51 byte[] bytes = bytes(data, byteOffset);
52 float actual = ModbusBitUtilities.extractFloat32(bytes, byteOffset);
53 float expected = Float.intBitsToFloat(data);
54 // Strict comparison of the float values with the exception of NaN
55 assertTrue(Float.isNaN(expected) ? Float.isNaN(actual) : expected == actual,
56 String.format("Testing %f (%s) with offset %d, got %f (%s)", expected, Integer.toBinaryString(data),
57 byteOffset, actual, Integer.toBinaryString(Float.floatToRawIntBits(actual))));
62 public void testExtractFloat32Inf() {
63 testFloat(Float.POSITIVE_INFINITY);
67 public void testExtractFloat32NegInf() {
68 testFloat(Float.NEGATIVE_INFINITY);
72 public void testExtractFloat32NaN() {
77 public void testExtractFloat32Regular() {