]> git.basschouten.com Git - openhab-addons.git/blob
07ae623cc7bf43342b47d0b6c65ef7f177ccfe51
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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.nikobus.internal.utils;
14
15 import java.util.concurrent.Future;
16
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jdt.annotation.Nullable;
19
20 /**
21  * The {@link Utils} class defines commonly used utility functions.
22  *
23  * @author Boris Krivonog - Initial contribution
24  */
25 @NonNullByDefault
26 public class Utils {
27     public static void cancel(@Nullable Future<?> future) {
28         if (future != null) {
29             future.cancel(true);
30         }
31     }
32
33     /**
34      * Convert bus address to push button's address as seen in Nikobus
35      * PC software.
36      *
37      * @param addressString
38      *            String representing a bus Push Button's address.
39      * @return Push button's address as seen in Nikobus PC software.
40      */
41     public static String convertToHumanReadableNikobusAddress(String addressString) {
42         try {
43             int address = Integer.parseInt(addressString, 16);
44             int nikobusAddress = 0;
45
46             for (int i = 0; i < 21; ++i) {
47                 nikobusAddress = (nikobusAddress << 1) | ((address >> i) & 1);
48             }
49
50             nikobusAddress = (nikobusAddress << 1);
51             int button = (address >> 21) & 0x07;
52
53             return leftPadWithZeros(Integer.toHexString(nikobusAddress), 6) + ":" + mapButton(button);
54
55         } catch (NumberFormatException e) {
56             return "[" + addressString + "]";
57         }
58     }
59
60     private static String mapButton(int buttonIndex) {
61         switch (buttonIndex) {
62             case 0:
63                 return "1";
64             case 1:
65                 return "5";
66             case 2:
67                 return "2";
68             case 3:
69                 return "6";
70             case 4:
71                 return "3";
72             case 5:
73                 return "7";
74             case 6:
75                 return "4";
76             case 7:
77                 return "8";
78             default:
79                 return "?";
80         }
81     }
82
83     public static String leftPadWithZeros(String text, int size) {
84         StringBuilder builder = new StringBuilder(text);
85         while (builder.length() < size) {
86             builder.insert(0, '0');
87         }
88         return builder.toString();
89     }
90 }