]> git.basschouten.com Git - openhab-addons.git/blob
fdded21139842ca66fc1b840203320636db53d6a
[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.lifx.internal.fields;
14
15 import java.nio.ByteBuffer;
16 import java.util.LinkedList;
17 import java.util.List;
18 import java.util.Objects;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.openhab.core.util.HexUtils;
23
24 /**
25  * @author Tim Buckley - Initial contribution
26  * @author Karel Goderis - Initial contribution
27  */
28 @NonNullByDefault
29 public class MACAddress {
30
31     public static final MACAddress BROADCAST_ADDRESS = new MACAddress("000000000000");
32
33     private ByteBuffer bytes;
34     private String hex = "";
35
36     public ByteBuffer getBytes() {
37         return bytes;
38     }
39
40     public String getHex() {
41         return hex;
42     }
43
44     public MACAddress(ByteBuffer bytes) {
45         this.bytes = bytes;
46
47         createHex();
48     }
49
50     public MACAddress(String string) {
51         byte[] byteArray = HexUtils.hexToBytes(string);
52         this.bytes = ByteBuffer.wrap(byteArray);
53         this.hex = HexUtils.bytesToHex(byteArray, ":");
54     }
55
56     public MACAddress() {
57         this(ByteBuffer.allocate(6));
58     }
59
60     private void createHex() {
61         bytes.rewind();
62
63         List<String> byteStrings = new LinkedList<>();
64         while (bytes.hasRemaining()) {
65             byteStrings.add(String.format("%02X", bytes.get()));
66         }
67
68         hex = String.join(":", byteStrings);
69
70         bytes.rewind();
71     }
72
73     public String getAsLabel() {
74         bytes.rewind();
75
76         StringBuilder hex = new StringBuilder();
77         while (bytes.hasRemaining()) {
78             hex.append(String.format("%02X", bytes.get()));
79         }
80
81         bytes.rewind();
82
83         return hex.toString();
84     }
85
86     @Override
87     public int hashCode() {
88         int hash = 7;
89         hash = 97 * hash + Objects.hashCode(this.hex);
90         return hash;
91     }
92
93     @Override
94     public boolean equals(@Nullable Object obj) {
95         if (obj == null) {
96             return false;
97         }
98
99         if (getClass() != obj.getClass()) {
100             return false;
101         }
102
103         final MACAddress other = (MACAddress) obj;
104         return this.hex.equalsIgnoreCase(other.hex);
105     }
106 }