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.bluetooth;
15 import java.time.ZonedDateTime;
16 import java.util.ArrayList;
17 import java.util.List;
18 import java.util.concurrent.locks.ReentrantLock;
20 import javax.measure.quantity.Power;
22 import org.apache.commons.lang.StringUtils;
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.openhab.binding.bluetooth.BluetoothDevice.ConnectionState;
26 import org.openhab.binding.bluetooth.notification.BluetoothConnectionStatusNotification;
27 import org.openhab.binding.bluetooth.notification.BluetoothScanNotification;
28 import org.openhab.core.library.types.QuantityType;
29 import org.openhab.core.library.types.StringType;
30 import org.openhab.core.library.unit.SmartHomeUnits;
31 import org.openhab.core.thing.Bridge;
32 import org.openhab.core.thing.Channel;
33 import org.openhab.core.thing.ChannelUID;
34 import org.openhab.core.thing.Thing;
35 import org.openhab.core.thing.ThingStatus;
36 import org.openhab.core.thing.ThingStatusDetail;
37 import org.openhab.core.thing.binding.BaseThingHandler;
38 import org.openhab.core.thing.binding.BridgeHandler;
39 import org.openhab.core.thing.binding.builder.ChannelBuilder;
40 import org.openhab.core.thing.binding.builder.ThingBuilder;
41 import org.openhab.core.types.Command;
42 import org.openhab.core.types.RefreshType;
43 import org.openhab.core.types.UnDefType;
46 * This is a handler for generic Bluetooth devices in beacon-mode (i.e. not connected), which at the same time can be
47 * used as a base implementation for more specific thing handlers.
49 * @author Kai Kreuzer - Initial contribution and API
52 public class BeaconBluetoothHandler extends BaseThingHandler implements BluetoothDeviceListener {
54 @NonNullByDefault({} /* non-null if initialized */)
55 protected BluetoothAdapter adapter;
57 @NonNullByDefault({} /* non-null if initialized */)
58 protected BluetoothAddress address;
60 @NonNullByDefault({} /* non-null if initialized */)
61 protected BluetoothDevice device;
63 protected final ReentrantLock deviceLock;
65 private @Nullable ZonedDateTime lastActivityTime;
67 public BeaconBluetoothHandler(Thing thing) {
69 deviceLock = new ReentrantLock();
73 public void initialize() {
75 address = new BluetoothAddress(getConfig().get(BluetoothBindingConstants.CONFIGURATION_ADDRESS).toString());
76 } catch (IllegalArgumentException e) {
77 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getLocalizedMessage());
81 Bridge bridge = getBridge();
83 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Not associated with any bridge");
87 BridgeHandler bridgeHandler = bridge.getHandler();
88 if (!(bridgeHandler instanceof BluetoothAdapter)) {
89 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
90 "Associated with an unsupported bridge");
94 adapter = (BluetoothAdapter) bridgeHandler;
98 device = adapter.getDevice(address);
99 device.addListener(this);
104 ThingBuilder builder = editThing();
105 for (Channel channel : createDynamicChannels()) {
106 // we only want to add each channel, not replace all of them
107 builder.withChannel(channel);
109 updateThing(builder.build());
111 updateStatus(ThingStatus.UNKNOWN);
114 private Channel buildChannel(String channelType, String itemType) {
115 return ChannelBuilder.create(new ChannelUID(getThing().getUID(), channelType), itemType).build();
118 protected List<Channel> createDynamicChannels() {
119 List<Channel> channels = new ArrayList<>();
120 channels.add(buildChannel(BluetoothBindingConstants.CHANNEL_TYPE_RSSI, "Number:Power"));
121 if (device instanceof DelegateBluetoothDevice) {
122 channels.add(buildChannel(BluetoothBindingConstants.CHANNEL_TYPE_ADAPTER, "String"));
123 channels.add(buildChannel(BluetoothBindingConstants.CHANNEL_TYPE_ADAPTER_LOCATION, "String"));
129 public void dispose() {
132 if (device != null) {
133 device.removeListener(this);
143 public void handleCommand(ChannelUID channelUID, Command command) {
144 if (command == RefreshType.REFRESH) {
145 switch (channelUID.getId()) {
146 case BluetoothBindingConstants.CHANNEL_TYPE_RSSI:
149 case BluetoothBindingConstants.CHANNEL_TYPE_ADAPTER:
152 case BluetoothBindingConstants.CHANNEL_TYPE_ADAPTER_LOCATION:
153 updateAdapterLocation();
160 * Updates the RSSI channel and the Thing status according to the new received rssi value
162 protected void updateRSSI() {
163 if (device != null) {
164 updateRSSI(device.getRssi());
168 private void updateRSSI(@Nullable Integer rssi) {
169 if (rssi != null && rssi != 0) {
170 QuantityType<Power> quantity = new QuantityType<>(rssi, SmartHomeUnits.DECIBEL_MILLIWATTS);
171 updateState(BluetoothBindingConstants.CHANNEL_TYPE_RSSI, quantity);
172 updateStatusBasedOnRssi(true);
174 updateState(BluetoothBindingConstants.CHANNEL_TYPE_RSSI, UnDefType.NULL);
175 updateStatusBasedOnRssi(false);
179 protected void updateAdapter() {
180 if (device != null) {
181 BluetoothAdapter adapter = device.getAdapter();
182 updateState(BluetoothBindingConstants.CHANNEL_TYPE_ADAPTER, new StringType(adapter.getUID().getId()));
186 protected void updateAdapterLocation() {
187 if (device != null) {
188 BluetoothAdapter adapter = device.getAdapter();
189 String location = adapter.getLocation();
190 if (location != null || StringUtils.isBlank(location)) {
191 updateState(BluetoothBindingConstants.CHANNEL_TYPE_ADAPTER_LOCATION, new StringType(location));
193 updateState(BluetoothBindingConstants.CHANNEL_TYPE_ADAPTER_LOCATION, UnDefType.NULL);
199 * This method sets the Thing status based on whether or not we can receive a signal from it.
200 * This is the best logic for beacons, but connected devices might want to deactivate this by overriding the method.
202 * @param receivedSignal true, if the device is in reach
204 protected void updateStatusBasedOnRssi(boolean receivedSignal) {
205 if (receivedSignal) {
206 updateStatus(ThingStatus.ONLINE);
208 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
212 private void onActivity() {
213 this.lastActivityTime = ZonedDateTime.now();
217 public void onScanRecordReceived(BluetoothScanNotification scanNotification) {
219 int rssi = scanNotification.getRssi();
220 if (rssi != Integer.MIN_VALUE) {
226 public void onConnectionStateChange(BluetoothConnectionStatusNotification connectionNotification) {
227 // a disconnection doesn't count as activity
228 if (connectionNotification.getConnectionState() != ConnectionState.DISCONNECTED) {
234 public void onServicesDiscovered() {
239 public void onCharacteristicReadComplete(BluetoothCharacteristic characteristic, BluetoothCompletionStatus status) {
240 if (status == BluetoothCompletionStatus.SUCCESS) {
246 public void onCharacteristicWriteComplete(BluetoothCharacteristic characteristic,
247 BluetoothCompletionStatus status) {
248 if (status == BluetoothCompletionStatus.SUCCESS) {
254 public void onCharacteristicUpdate(BluetoothCharacteristic characteristic) {
259 public void onDescriptorUpdate(BluetoothDescriptor bluetoothDescriptor) {
264 public void onAdapterChanged(BluetoothAdapter adapter) {
266 updateAdapterLocation();