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.lifx.internal.fields;
15 import java.io.ByteArrayInputStream;
16 import java.io.IOException;
17 import java.nio.ByteBuffer;
18 import java.util.Arrays;
19 import java.util.LinkedList;
20 import java.util.List;
21 import java.util.Objects;
23 import org.apache.commons.lang.StringUtils;
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
31 * @author Karel Goderis
34 public class MACAddress {
36 public static final MACAddress BROADCAST_ADDRESS = new MACAddress("000000000000", true);
38 private final Logger logger = LoggerFactory.getLogger(MACAddress.class);
40 private ByteBuffer bytes;
41 private String hex = "";
43 public ByteBuffer getBytes() {
47 public String getHex() {
51 public MACAddress(ByteBuffer bytes) {
57 public MACAddress(String string, boolean isHex) {
59 this.bytes = ByteBuffer.wrap(string.getBytes());
62 this.bytes = ByteBuffer.wrap(parseHexBinary(string));
65 formatHex(string, 2, ":");
66 } catch (IOException e) {
67 logger.error("An exception occurred while formatting an HEX string : '{}'", e.getMessage());
72 private byte[] parseHexBinary(String s) {
74 byte[] data = new byte[len / 2];
75 for (int i = 0; i < len; i += 2) {
76 data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
82 this(ByteBuffer.allocate(6));
85 private void createHex() {
88 List<String> byteStrings = new LinkedList<>();
89 while (bytes.hasRemaining()) {
90 byteStrings.add(String.format("%02X", bytes.get()));
93 hex = StringUtils.join(byteStrings, ':');
98 public String getAsLabel() {
101 StringBuilder hex = new StringBuilder();
102 while (bytes.hasRemaining()) {
103 hex.append(String.format("%02X", bytes.get()));
108 return hex.toString();
111 private void formatHex(String original, int length, String separator) throws IOException {
112 ByteArrayInputStream bis = new ByteArrayInputStream(original.getBytes());
113 byte[] buffer = new byte[length];
115 while (bis.read(buffer) > 0) {
116 for (byte b : buffer) {
119 Arrays.fill(buffer, (byte) 0);
123 hex = StringUtils.left(result, result.length() - 1);
127 public int hashCode() {
129 hash = 97 * hash + Objects.hashCode(this.hex);
134 public boolean equals(@Nullable Object obj) {
139 if (getClass() != obj.getClass()) {
143 final MACAddress other = (MACAddress) obj;
144 if (!this.hex.equalsIgnoreCase(other.hex)) {