]> git.basschouten.com Git - openhab-addons.git/blob
5fe5d41091e2c7e6263738591b1dd5928757e921
[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.bluetooth;
14
15 import org.eclipse.jdt.annotation.NonNullByDefault;
16 import org.eclipse.jdt.annotation.Nullable;
17
18 /**
19  * The {@link BluetoothAddress} class defines a bluetooth address
20  *
21  * @author Chris Jackson - Initial contribution
22  */
23 @NonNullByDefault
24 public class BluetoothAddress {
25
26     public static final int BD_ADDRESS_LENGTH = 17;
27
28     private final String address;
29
30     /**
31      * The default constructor
32      *
33      * @param address the device address
34      */
35     public BluetoothAddress(@Nullable String address) {
36         if (address == null || address.length() != BD_ADDRESS_LENGTH) {
37             throw new IllegalArgumentException("BT Address cannot be null and must be in format XX:XX:XX:XX:XX:XX");
38         }
39         for (int i = 0; i < BD_ADDRESS_LENGTH; i++) {
40             char c = address.charAt(i);
41
42             // Check address - 2 bytes should be hex, and then a colon
43             switch (i % 3) {
44                 case 0: // fall through
45                 case 1:
46                     if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
47                         break;
48                     }
49                     throw new IllegalArgumentException("BT Address must contain upper case hex values only");
50                 case 2:
51                     if (c == ':') {
52                         break;
53                     }
54                     throw new IllegalArgumentException("BT Address bytes must be separated with colon");
55             }
56         }
57
58         this.address = address;
59     }
60
61     @Override
62     public int hashCode() {
63         final int prime = 31;
64         int result = 1;
65         result = prime * result + address.hashCode();
66         return result;
67     }
68
69     @Override
70     public boolean equals(@Nullable Object obj) {
71         if (this == obj) {
72             return true;
73         }
74         if (obj == null) {
75             return false;
76         }
77         if (getClass() != obj.getClass()) {
78             return false;
79         }
80         BluetoothAddress other = (BluetoothAddress) obj;
81
82         return address.equals(other.address);
83     }
84
85     @Override
86     public String toString() {
87         return address;
88     }
89 }