]> git.basschouten.com Git - openhab-addons.git/blob
6b99aa06c0cc6edbc68adfdf4df95e6b15b3f85c
[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.bluez.internal.events;
14
15 import org.eclipse.jdt.annotation.NonNullByDefault;
16 import org.eclipse.jdt.annotation.Nullable;
17 import org.openhab.binding.bluetooth.BluetoothAddress;
18
19 /**
20  * The {@link BlueZEvent} class represents an event from dbus due to
21  * changes in the properties of a bluetooth device.
22  *
23  * @author Benjamin Lafois - Initial Contribution
24  *
25  */
26 @NonNullByDefault
27 public abstract class BlueZEvent {
28
29     private String dbusPath;
30
31     private @Nullable BluetoothAddress device;
32     private @Nullable String adapterName;
33
34     public BlueZEvent(String dbusPath) {
35         this.dbusPath = dbusPath;
36
37         // the rest of the code should be equivalent to parsing with the following regex:
38         // "/org/bluez/(?<adapterName>[^/]+)(/dev_(?<deviceMac>[^/]+).*)?"
39         if (!dbusPath.startsWith("/org/bluez/")) {
40             return;
41         }
42         int start = dbusPath.indexOf('/', 11);
43         if (start == -1) {
44             this.adapterName = dbusPath.substring(11);
45             return;
46         } else {
47             this.adapterName = dbusPath.substring(11, start);
48         }
49         start++;
50         int end = dbusPath.indexOf('/', start);
51         String mac;
52         if (end == -1) {
53             mac = dbusPath.substring(start);
54         } else {
55             mac = dbusPath.substring(start, end);
56         }
57         if (!mac.startsWith("dev_")) {
58             return;
59         }
60         mac = mac.substring(4); // trim off the "dev_" prefix
61         if (!mac.isEmpty()) {
62             this.device = new BluetoothAddress(mac.replace('_', ':').toUpperCase());
63         }
64     }
65
66     public String getDbusPath() {
67         return dbusPath;
68     }
69
70     public @Nullable BluetoothAddress getDevice() {
71         return device;
72     }
73
74     public @Nullable String getAdapterName() {
75         return adapterName;
76     }
77
78     public abstract void dispatch(BlueZEventListener listener);
79
80     @Override
81     public String toString() {
82         return getClass().getSimpleName() + ": " + dbusPath;
83     }
84 }