]> git.basschouten.com Git - openhab-addons.git/blob
388a9464f16488682301924110e91704ecd372c0
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.io.transport.modbus.test;
14
15 import static org.junit.jupiter.api.Assertions.assertTrue;
16
17 import java.nio.ByteBuffer;
18
19 import org.junit.jupiter.api.Test;
20 import org.openhab.io.transport.modbus.ModbusBitUtilities;
21
22 /**
23  *
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}
27  *
28  * @author Sami Salonen - Initial contribution
29  */
30 public class BitUtilitiesExtractFloat32Test {
31
32     /**
33      * Creates a byte array with byteOffset number of zeroes, followed by 32bit of data represented by data
34      *
35      * @param data actual data payload
36      * @param byteOffset number of zeros padded
37      * @return byte array of size 4 + byteOffset
38      */
39     private static byte[] bytes(int data, int byteOffset) {
40         ByteBuffer buffer = ByteBuffer.allocate(4 + byteOffset);
41         for (int i = 0; i < byteOffset; i++) {
42             buffer.put((byte) 0);
43         }
44         buffer.putInt(data);
45         return buffer.array();
46     }
47
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))));
58         }
59     }
60
61     @Test
62     public void testExtractFloat32Inf() {
63         testFloat(Float.POSITIVE_INFINITY);
64     }
65
66     @Test
67     public void testExtractFloat32NegInf() {
68         testFloat(Float.NEGATIVE_INFINITY);
69     }
70
71     @Test
72     public void testExtractFloat32NaN() {
73         testFloat(Float.NaN);
74     }
75
76     @Test
77     public void testExtractFloat32Regular() {
78         testFloat(1.3f);
79     }
80 }