2 * Copyright (c) 2010-2023 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.bluegiga.handler;
15 import java.io.BufferedInputStream;
16 import java.io.BufferedOutputStream;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.io.OutputStream;
21 import java.util.Optional;
22 import java.util.UUID;
23 import java.util.concurrent.CancellationException;
24 import java.util.concurrent.CompletableFuture;
25 import java.util.concurrent.CompletionException;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ExecutionException;
28 import java.util.concurrent.Future;
29 import java.util.concurrent.ScheduledExecutorService;
30 import java.util.concurrent.ScheduledFuture;
31 import java.util.concurrent.TimeUnit;
33 import org.eclipse.jdt.annotation.NonNullByDefault;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.openhab.binding.bluetooth.AbstractBluetoothBridgeHandler;
36 import org.openhab.binding.bluetooth.BluetoothAddress;
37 import org.openhab.binding.bluetooth.BluetoothBindingConstants;
38 import org.openhab.binding.bluetooth.bluegiga.BlueGigaAdapterConstants;
39 import org.openhab.binding.bluetooth.bluegiga.BlueGigaBluetoothDevice;
40 import org.openhab.binding.bluetooth.bluegiga.internal.BlueGigaCommand;
41 import org.openhab.binding.bluetooth.bluegiga.internal.BlueGigaConfiguration;
42 import org.openhab.binding.bluetooth.bluegiga.internal.BlueGigaEventListener;
43 import org.openhab.binding.bluetooth.bluegiga.internal.BlueGigaException;
44 import org.openhab.binding.bluetooth.bluegiga.internal.BlueGigaHandlerListener;
45 import org.openhab.binding.bluetooth.bluegiga.internal.BlueGigaResponse;
46 import org.openhab.binding.bluetooth.bluegiga.internal.BlueGigaSerialHandler;
47 import org.openhab.binding.bluetooth.bluegiga.internal.BlueGigaTransactionManager;
48 import org.openhab.binding.bluetooth.bluegiga.internal.command.attributeclient.BlueGigaAttributeWriteCommand;
49 import org.openhab.binding.bluetooth.bluegiga.internal.command.attributeclient.BlueGigaAttributeWriteResponse;
50 import org.openhab.binding.bluetooth.bluegiga.internal.command.attributeclient.BlueGigaFindInformationCommand;
51 import org.openhab.binding.bluetooth.bluegiga.internal.command.attributeclient.BlueGigaFindInformationResponse;
52 import org.openhab.binding.bluetooth.bluegiga.internal.command.attributeclient.BlueGigaReadByGroupTypeCommand;
53 import org.openhab.binding.bluetooth.bluegiga.internal.command.attributeclient.BlueGigaReadByGroupTypeResponse;
54 import org.openhab.binding.bluetooth.bluegiga.internal.command.attributeclient.BlueGigaReadByHandleCommand;
55 import org.openhab.binding.bluetooth.bluegiga.internal.command.attributeclient.BlueGigaReadByHandleResponse;
56 import org.openhab.binding.bluetooth.bluegiga.internal.command.attributeclient.BlueGigaReadByTypeCommand;
57 import org.openhab.binding.bluetooth.bluegiga.internal.command.attributeclient.BlueGigaReadByTypeResponse;
58 import org.openhab.binding.bluetooth.bluegiga.internal.command.connection.BlueGigaConnectionStatusEvent;
59 import org.openhab.binding.bluetooth.bluegiga.internal.command.connection.BlueGigaDisconnectCommand;
60 import org.openhab.binding.bluetooth.bluegiga.internal.command.connection.BlueGigaDisconnectResponse;
61 import org.openhab.binding.bluetooth.bluegiga.internal.command.connection.BlueGigaDisconnectedEvent;
62 import org.openhab.binding.bluetooth.bluegiga.internal.command.gap.BlueGigaConnectDirectCommand;
63 import org.openhab.binding.bluetooth.bluegiga.internal.command.gap.BlueGigaConnectDirectResponse;
64 import org.openhab.binding.bluetooth.bluegiga.internal.command.gap.BlueGigaDiscoverCommand;
65 import org.openhab.binding.bluetooth.bluegiga.internal.command.gap.BlueGigaDiscoverResponse;
66 import org.openhab.binding.bluetooth.bluegiga.internal.command.gap.BlueGigaEndProcedureCommand;
67 import org.openhab.binding.bluetooth.bluegiga.internal.command.gap.BlueGigaEndProcedureResponse;
68 import org.openhab.binding.bluetooth.bluegiga.internal.command.gap.BlueGigaScanResponseEvent;
69 import org.openhab.binding.bluetooth.bluegiga.internal.command.gap.BlueGigaSetModeCommand;
70 import org.openhab.binding.bluetooth.bluegiga.internal.command.gap.BlueGigaSetModeResponse;
71 import org.openhab.binding.bluetooth.bluegiga.internal.command.gap.BlueGigaSetScanParametersCommand;
72 import org.openhab.binding.bluetooth.bluegiga.internal.command.gap.BlueGigaSetScanParametersResponse;
73 import org.openhab.binding.bluetooth.bluegiga.internal.command.system.BlueGigaAddressGetCommand;
74 import org.openhab.binding.bluetooth.bluegiga.internal.command.system.BlueGigaAddressGetResponse;
75 import org.openhab.binding.bluetooth.bluegiga.internal.command.system.BlueGigaGetConnectionsCommand;
76 import org.openhab.binding.bluetooth.bluegiga.internal.command.system.BlueGigaGetConnectionsResponse;
77 import org.openhab.binding.bluetooth.bluegiga.internal.command.system.BlueGigaGetInfoCommand;
78 import org.openhab.binding.bluetooth.bluegiga.internal.command.system.BlueGigaGetInfoResponse;
79 import org.openhab.binding.bluetooth.bluegiga.internal.enumeration.BgApiResponse;
80 import org.openhab.binding.bluetooth.bluegiga.internal.enumeration.BluetoothAddressType;
81 import org.openhab.binding.bluetooth.bluegiga.internal.enumeration.GapConnectableMode;
82 import org.openhab.binding.bluetooth.bluegiga.internal.enumeration.GapDiscoverMode;
83 import org.openhab.binding.bluetooth.bluegiga.internal.enumeration.GapDiscoverableMode;
84 import org.openhab.binding.bluetooth.util.RetryException;
85 import org.openhab.binding.bluetooth.util.RetryFuture;
86 import org.openhab.core.common.ThreadPoolManager;
87 import org.openhab.core.io.transport.serial.PortInUseException;
88 import org.openhab.core.io.transport.serial.SerialPort;
89 import org.openhab.core.io.transport.serial.SerialPortIdentifier;
90 import org.openhab.core.io.transport.serial.SerialPortManager;
91 import org.openhab.core.io.transport.serial.UnsupportedCommOperationException;
92 import org.openhab.core.thing.Bridge;
93 import org.openhab.core.thing.Thing;
94 import org.openhab.core.thing.ThingStatus;
95 import org.openhab.core.thing.ThingStatusDetail;
96 import org.slf4j.Logger;
97 import org.slf4j.LoggerFactory;
100 * The {@link BlueGigaBridgeHandler} is responsible for interfacing to the BlueGiga Bluetooth adapter.
101 * It provides a private interface for {@link BlueGigaBluetoothDevice}s to access the dongle and provides top
102 * level adaptor functionality for scanning and arbitration.
104 * The handler provides the serial interface to the dongle via the BlueGiga BG-API library.
106 * In the BlueGiga dongle, we leave scanning enabled most of the time. Normally, it's just passive scanning, and active
107 * scanning is enabled when we want to include new devices. Passive scanning is enough for us to receive beacons etc
108 * that are transmitted periodically, and active scanning will get more information which may be useful when we are
109 * including new devices.
111 * @author Chris Jackson - Initial contribution
112 * @author Kai Kreuzer - Made handler implement BlueGigaHandlerListener
113 * @author Pauli Anttila - Many improvements
116 public class BlueGigaBridgeHandler extends AbstractBluetoothBridgeHandler<BlueGigaBluetoothDevice>
117 implements BlueGigaEventListener, BlueGigaHandlerListener {
119 private final Logger logger = LoggerFactory.getLogger(BlueGigaBridgeHandler.class);
121 private final int COMMAND_TIMEOUT_MS = 5000;
122 private final int INITIALIZATION_INTERVAL_SEC = 60;
124 private final SerialPortManager serialPortManager;
126 private final ScheduledExecutorService executor = ThreadPoolManager.getScheduledPool("BlueGiga");
128 private BlueGigaConfiguration configuration = new BlueGigaConfiguration();
130 // The serial port input stream.
131 private Optional<InputStream> inputStream = Optional.empty();
133 // The serial port output stream.
134 private Optional<OutputStream> outputStream = Optional.empty();
136 // The BlueGiga API handler
137 private CompletableFuture<BlueGigaSerialHandler> serialHandler = CompletableFuture
138 .failedFuture(new IllegalStateException("Uninitialized"));
140 // The BlueGiga transaction manager
141 @NonNullByDefault({})
142 private CompletableFuture<BlueGigaTransactionManager> transactionManager = CompletableFuture
143 .failedFuture(new IllegalStateException("Uninitialized"));
145 // The maximum number of connections this interface supports
146 private int maxConnections = 0;
149 private @Nullable BluetoothAddress address;
151 // Map of open connections
152 private final Map<Integer, BluetoothAddress> connections = new ConcurrentHashMap<>();
154 private volatile boolean initComplete = false;
156 private CompletableFuture<SerialPort> serialPortFuture = CompletableFuture
157 .failedFuture(new IllegalStateException("Uninitialized"));
159 private @Nullable ScheduledFuture<?> removeInactiveDevicesTask;
160 private @Nullable ScheduledFuture<?> discoveryTask;
161 private @Nullable ScheduledFuture<?> initTask;
163 private @Nullable Future<?> passiveScanIdleTimer;
165 public BlueGigaBridgeHandler(Bridge bridge, SerialPortManager serialPortManager) {
167 this.serialPortManager = serialPortManager;
171 public void initialize() {
173 updateStatus(ThingStatus.UNKNOWN);
174 if (initTask == null) {
175 initTask = scheduler.scheduleWithFixedDelay(this::checkInit, 0, 10, TimeUnit.SECONDS);
179 protected void checkInit() {
180 boolean init = false;
182 if (!serialHandler.get().isAlive()) {
183 logger.debug("BLE serial handler seems to be dead, reinitilize");
187 } catch (InterruptedException e) {
189 } catch (ExecutionException e) {
194 logger.debug("Initialize BlueGiga");
199 private void start() {
200 Optional<BlueGigaConfiguration> cfg = Optional.of(getConfigAs(BlueGigaConfiguration.class));
201 if (cfg.isPresent()) {
202 initComplete = false;
203 configuration = cfg.get();
204 serialPortFuture = RetryFuture.callWithRetry(() -> {
205 var localFuture = serialPortFuture;
206 logger.debug("Using configuration: {}", configuration);
208 String serialPortName = configuration.port;
209 int baudRate = 115200;
211 logger.debug("Connecting to serial port '{}'", serialPortName);
213 SerialPortIdentifier portIdentifier = serialPortManager.getIdentifier(serialPortName);
214 if (portIdentifier == null) {
215 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Port does not exist");
216 throw new RetryException(INITIALIZATION_INTERVAL_SEC, TimeUnit.SECONDS);
218 SerialPort sp = portIdentifier.open("org.openhab.binding.bluetooth.bluegiga", 2000);
219 sp.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
220 SerialPort.PARITY_NONE);
222 sp.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_OUT);
223 sp.enableReceiveThreshold(1);
224 sp.enableReceiveTimeout(2000);
226 // RXTX serial port library causes high CPU load
227 // Start event listener, which will just sleep and slow down event loop
228 sp.notifyOnDataAvailable(true);
230 logger.info("Connected to serial port '{}'.", serialPortName);
233 inputStream = Optional.of(new BufferedInputStream(sp.getInputStream()));
234 outputStream = Optional.of(new BufferedOutputStream(sp.getOutputStream()));
235 } catch (IOException e) {
236 logger.error("Error getting serial streams", e);
237 throw new RetryException(INITIALIZATION_INTERVAL_SEC, TimeUnit.SECONDS);
239 // if this future has been cancelled while this was running, then we
240 // need to make sure that we close this port
241 localFuture.whenComplete((port, th) -> {
243 // we need to shut down the port now.
248 } catch (PortInUseException e) {
249 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
250 "Serial Error: Port in use");
251 throw new RetryException(INITIALIZATION_INTERVAL_SEC, TimeUnit.SECONDS);
252 } catch (UnsupportedCommOperationException e) {
253 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
254 "Serial Error: Unsupported operation");
255 throw new RetryException(INITIALIZATION_INTERVAL_SEC, TimeUnit.SECONDS);
256 } catch (RuntimeException ex) {
257 logger.debug("Start failed", ex);
258 throw new RetryException(INITIALIZATION_INTERVAL_SEC, TimeUnit.SECONDS);
262 serialHandler = serialPortFuture
263 .thenApply(sp -> new BlueGigaSerialHandler(getThing().getUID().getAsString(), inputStream.get(),
264 outputStream.get()));
265 transactionManager = serialHandler.thenApply(sh -> {
266 BlueGigaTransactionManager th = new BlueGigaTransactionManager(sh, executor);
267 sh.addHandlerListener(this);
268 th.addEventListener(this);
271 transactionManager.thenRun(() -> {
273 // Stop any procedures that are running
276 // Set mode to non-discoverable etc.
279 // Get maximum parallel connections
280 maxConnections = readMaxConnections().getMaxconn();
282 // Close all connections so we start from a known position
283 for (int connection = 0; connection < maxConnections; connection++) {
284 sendCommandWithoutChecks(
285 new BlueGigaDisconnectCommand.CommandBuilder().withConnection(connection).build(),
286 BlueGigaDisconnectResponse.class);
289 // Get our Bluetooth address
290 address = new BluetoothAddress(readAddress().getAddress());
292 updateThingProperties();
295 updateStatus(ThingStatus.ONLINE);
296 startScheduledTasks();
297 } catch (BlueGigaException e) {
298 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
299 "Initialization of BlueGiga controller failed");
301 }).exceptionally(th -> {
302 if (th instanceof CompletionException && th.getCause() instanceof CancellationException) {
303 // cancellation is a normal reason for failure, so no need to print it.
306 logger.warn("Error initializing bluegiga", th);
311 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR);
316 public void dispose() {
317 if (initTask != null) {
318 initTask.cancel(true);
325 private void stop() {
326 logger.info("Stop BlueGiga");
327 transactionManager.thenAccept(tman -> {
328 tman.removeEventListener(this);
331 serialHandler.thenAccept(sh -> {
332 sh.removeHandlerListener(this);
336 initComplete = false;
339 serialPortFuture.thenAccept(this::closeSerialPort);
340 serialPortFuture.cancel(false);
341 stopScheduledTasks();
344 private void schedulePassiveScan() {
345 cancelScheduledPassiveScan();
346 passiveScanIdleTimer = executor.schedule(() -> {
347 if (!activeScanEnabled) {
348 logger.debug("Activate passive scan");
350 bgStartScanning(false, configuration.passiveScanInterval, configuration.passiveScanWindow);
352 logger.debug("Ignore passive scan activation as active scan is active");
354 }, configuration.passiveScanIdleTime, TimeUnit.MILLISECONDS);
357 private void cancelScheduledPassiveScan() {
358 if (passiveScanIdleTimer != null) {
359 passiveScanIdleTimer.cancel(true);
363 private void startScheduledTasks() {
364 schedulePassiveScan();
365 discoveryTask = scheduler.scheduleWithFixedDelay(this::refreshDiscoveredDevices, 0, 10, TimeUnit.SECONDS);
368 private void stopScheduledTasks() {
369 cancelScheduledPassiveScan();
370 if (removeInactiveDevicesTask != null) {
371 removeInactiveDevicesTask.cancel(true);
372 removeInactiveDevicesTask = null;
374 if (discoveryTask != null) {
375 discoveryTask.cancel(true);
376 discoveryTask = null;
380 private BlueGigaGetConnectionsResponse readMaxConnections() throws BlueGigaException {
381 return sendCommandWithoutChecks(new BlueGigaGetConnectionsCommand(), BlueGigaGetConnectionsResponse.class);
384 private BlueGigaAddressGetResponse readAddress() throws BlueGigaException {
385 return sendCommandWithoutChecks(new BlueGigaAddressGetCommand(), BlueGigaAddressGetResponse.class);
388 private BlueGigaGetInfoResponse readInfo() throws BlueGigaException {
389 return sendCommandWithoutChecks(new BlueGigaGetInfoCommand(), BlueGigaGetInfoResponse.class);
392 private void updateThingProperties() throws BlueGigaException {
393 BlueGigaGetInfoResponse infoResponse = readInfo();
395 Map<String, String> properties = editProperties();
396 properties.put(BluetoothBindingConstants.PROPERTY_MAXCONNECTIONS, Integer.toString(maxConnections));
397 properties.put(Thing.PROPERTY_FIRMWARE_VERSION,
398 String.format("%d.%d", infoResponse.getMajor(), infoResponse.getMinor()));
399 properties.put(Thing.PROPERTY_HARDWARE_VERSION, Integer.toString(infoResponse.getHardware()));
400 properties.put(BlueGigaAdapterConstants.PROPERTY_PROTOCOL, Integer.toString(infoResponse.getProtocolVersion()));
401 properties.put(BlueGigaAdapterConstants.PROPERTY_LINKLAYER, Integer.toString(infoResponse.getLlVersion()));
402 updateProperties(properties);
405 private void closeSerialPort(SerialPort sp) {
406 sp.removeEventListener();
408 sp.disableReceiveTimeout();
409 } catch (Exception e) {
410 // Ignore all as RXTX seems to send arbitrary exceptions when BlueGiga module is detached
412 outputStream.ifPresent(output -> {
415 } catch (IOException e) {
418 inputStream.ifPresent(input -> {
421 } catch (IOException e) {
425 logger.debug("Closed serial port.");
426 inputStream = Optional.empty();
427 outputStream = Optional.empty();
432 public void scanStart() {
434 logger.debug("Start active scan");
435 // Stop the passive scan
436 cancelScheduledPassiveScan();
439 // Start an active scan
440 bgStartScanning(true, configuration.activeScanInterval, configuration.activeScanWindow);
444 public void scanStop() {
446 logger.debug("Stop active scan");
448 // Stop the active scan
451 // Start a passive scan after idle delay
452 schedulePassiveScan();
456 public @Nullable BluetoothAddress getAddress() {
457 BluetoothAddress addr = address;
461 throw new IllegalStateException("Adapter has not been initialized yet!");
466 protected BlueGigaBluetoothDevice createDevice(BluetoothAddress address) {
467 return new BlueGigaBluetoothDevice(this, address, BluetoothAddressType.UNKNOWN);
471 * Connects to a device.
473 * If the device is already connected, or the attempt to connect failed, then we return false. If we have reached
474 * the maximum number of connections supported by this dongle, then we return false.
476 * @param address the device {@link BluetoothAddress} to connect to
477 * @param addressType the {@link BluetoothAddressType} of the device
478 * @return true if the connection was started
480 public boolean bgConnect(BluetoothAddress address, BluetoothAddressType addressType) {
481 // Check the connection to make sure we're not already connected to this device
482 if (connections.containsValue(address)) {
486 // FIXME: When getting here, I always found all connections to be already taken and thus the code never
487 // proceeded. Relaxing this condition did not do any obvious harm, but now guaranteed that the services are
488 // queried from the device.
489 if (connections.size() == maxConnections + 1) {
490 logger.debug("BlueGiga: Attempt to connect to {} but no connections available.", address);
494 logger.debug("BlueGiga Connect: address {}.", address);
497 BlueGigaConnectDirectCommand command = new BlueGigaConnectDirectCommand.CommandBuilder()
498 .withAddress(address.toString())
499 .withAddrType(addressType)
500 .withConnIntervalMin(configuration.connIntervalMin)
501 .withConnIntervalMax(configuration.connIntervalMax)
502 .withLatency(configuration.connLatency)
503 .withTimeout(configuration.connTimeout)
507 return sendCommand(command, BlueGigaConnectDirectResponse.class, true).getResult() == BgApiResponse.SUCCESS;
508 } catch (BlueGigaException e) {
509 logger.debug("Error occured when sending connect command to device {}, reason: {}.", address,
516 * Close a connection using {@link BlueGigaDisconnectCommand}
518 * @param connectionHandle
521 public boolean bgDisconnect(int connectionHandle) {
522 logger.debug("BlueGiga Disconnect: connection {}", connectionHandle);
523 BlueGigaDisconnectCommand command = new BlueGigaDisconnectCommand.CommandBuilder()
524 .withConnection(connectionHandle).build();
527 return sendCommand(command, BlueGigaDisconnectResponse.class, true).getResult() == BgApiResponse.SUCCESS;
528 } catch (BlueGigaException e) {
529 logger.debug("Error occured when sending disconnect command to device {}, reason: {}.", address,
536 * Start a read of all primary services using {@link BlueGigaReadByGroupTypeCommand}
538 * @param connectionHandle
539 * @return true if successful
541 public boolean bgFindPrimaryServices(int connectionHandle) {
542 logger.debug("BlueGiga FindPrimary: connection {}", connectionHandle);
544 BlueGigaReadByGroupTypeCommand command = new BlueGigaReadByGroupTypeCommand.CommandBuilder()
545 .withConnection(connectionHandle)
548 .withUuid(UUID.fromString("00002800-0000-1000-8000-00805F9B34FB"))
552 return sendCommand(command, BlueGigaReadByGroupTypeResponse.class, true)
553 .getResult() == BgApiResponse.SUCCESS;
554 } catch (BlueGigaException e) {
555 logger.debug("Error occured when sending read primary services command to device {}, reason: {}.", address,
562 * Start a read of all characteristics using {@link BlueGigaFindInformationCommand}
564 * @param connectionHandle
565 * @return true if successful
567 public boolean bgFindCharacteristics(int connectionHandle) {
568 logger.debug("BlueGiga Find: connection {}", connectionHandle);
570 BlueGigaFindInformationCommand command = new BlueGigaFindInformationCommand.CommandBuilder()
571 .withConnection(connectionHandle)
577 return sendCommand(command, BlueGigaFindInformationResponse.class, true)
578 .getResult() == BgApiResponse.SUCCESS;
579 } catch (BlueGigaException e) {
580 logger.debug("Error occured when sending read characteristics command to device {}, reason: {}.", address,
586 public boolean bgReadCharacteristicDeclarations(int connectionHandle) {
587 logger.debug("BlueGiga Find: connection {}", connectionHandle);
589 BlueGigaReadByTypeCommand command = new BlueGigaReadByTypeCommand.CommandBuilder()
590 .withConnection(connectionHandle)
593 .withUUID(BluetoothBindingConstants.ATTR_CHARACTERISTIC_DECLARATION)
597 return sendCommand(command, BlueGigaReadByTypeResponse.class, true).getResult() == BgApiResponse.SUCCESS;
598 } catch (BlueGigaException e) {
599 logger.debug("Error occured when sending read characteristics command to device {}, reason: {}.", address,
606 * Read a characteristic using {@link BlueGigaReadByHandleCommand}
608 * @param connectionHandle
610 * @return true if successful
612 public boolean bgReadCharacteristic(int connectionHandle, int handle) {
613 logger.debug("BlueGiga Read: connection {}, handle {}", connectionHandle, handle);
615 BlueGigaReadByHandleCommand command = new BlueGigaReadByHandleCommand.CommandBuilder()
616 .withConnection(connectionHandle)
617 .withChrHandle(handle)
621 return sendCommand(command, BlueGigaReadByHandleResponse.class, true).getResult() == BgApiResponse.SUCCESS;
622 } catch (BlueGigaException e) {
623 logger.debug("Error occured when sending read characteristics command to device {}, reason: {}.", address,
630 * Write a characteristic using {@link BlueGigaAttributeWriteCommand}
632 * @param connectionHandle
635 * @return true if successful
637 public boolean bgWriteCharacteristic(int connectionHandle, int handle, int[] value) {
638 logger.debug("BlueGiga Write: connection {}, handle {}", connectionHandle, handle);
640 BlueGigaAttributeWriteCommand command = new BlueGigaAttributeWriteCommand.CommandBuilder()
641 .withConnection(connectionHandle)
642 .withAttHandle(handle)
647 return sendCommand(command, BlueGigaAttributeWriteResponse.class, true)
648 .getResult() == BgApiResponse.SUCCESS;
649 } catch (BlueGigaException e) {
650 logger.debug("Error occured when sending write characteristics command to device {}, reason: {}.", address,
657 * The following methods are private methods for handling the BlueGiga protocol
659 private boolean bgEndProcedure() {
661 return sendCommandWithoutChecks(new BlueGigaEndProcedureCommand(), BlueGigaEndProcedureResponse.class)
662 .getResult() == BgApiResponse.SUCCESS;
663 } catch (BlueGigaException e) {
664 logger.debug("Error occured when sending end procedure command.");
669 private boolean bgSetMode() {
672 BlueGigaSetModeCommand command = new BlueGigaSetModeCommand.CommandBuilder()
673 .withConnect(GapConnectableMode.GAP_NON_CONNECTABLE)
674 .withDiscover(GapDiscoverableMode.GAP_NON_DISCOVERABLE)
677 return sendCommandWithoutChecks(command, BlueGigaSetModeResponse.class)
678 .getResult() == BgApiResponse.SUCCESS;
679 } catch (BlueGigaException e) {
680 logger.debug("Error occured when sending set mode command, reason: {}", e.getMessage());
686 * Starts scanning on the dongle
688 * @param active true for active scanning
690 private boolean bgStartScanning(boolean active, int interval, int window) {
693 BlueGigaSetScanParametersCommand scanCommand = new BlueGigaSetScanParametersCommand.CommandBuilder()
694 .withActiveScanning(active)
695 .withScanInterval(interval)
696 .withScanWindow(window)
699 if (sendCommand(scanCommand, BlueGigaSetScanParametersResponse.class, false)
700 .getResult() == BgApiResponse.SUCCESS) {
701 BlueGigaDiscoverCommand discoverCommand = new BlueGigaDiscoverCommand.CommandBuilder()
702 .withMode(GapDiscoverMode.GAP_DISCOVER_OBSERVATION).build();
703 if (sendCommand(discoverCommand, BlueGigaDiscoverResponse.class, false)
704 .getResult() == BgApiResponse.SUCCESS) {
705 logger.debug("{} scanning successfully started.", active ? "Active" : "Passive");
709 } catch (BlueGigaException e) {
710 logger.debug("Error occured when sending start scan command, reason: {}", e.getMessage());
712 logger.debug("Scan start failed.");
717 * Send command only if initialization phase is successfully done
719 private <T extends BlueGigaResponse> T sendCommand(BlueGigaCommand command, Class<T> expectedResponse,
720 boolean schedulePassiveScan) throws BlueGigaException {
722 throw new BlueGigaException("BlueGiga not initialized");
725 if (schedulePassiveScan) {
726 cancelScheduledPassiveScan();
729 return sendCommandWithoutChecks(command, expectedResponse);
731 if (schedulePassiveScan) {
732 schedulePassiveScan();
738 * Forcefully send command without any checks
740 private <T extends BlueGigaResponse> T sendCommandWithoutChecks(BlueGigaCommand command, Class<T> expectedResponse)
741 throws BlueGigaException {
742 BlueGigaTransactionManager manager = transactionManager.getNow(null);
743 if (manager != null) {
744 return manager.sendTransaction(command, expectedResponse, COMMAND_TIMEOUT_MS);
746 throw new BlueGigaException("Transaction manager missing");
751 * Add an event listener for the BlueGiga events
753 * @param listener the {@link BlueGigaEventListener} to add
755 public void addEventListener(BlueGigaEventListener listener) {
756 transactionManager.thenAccept(manager -> {
757 manager.addEventListener(listener);
762 * Remove an event listener for the BlueGiga events
764 * @param listener the {@link BlueGigaEventListener} to remove
766 public void removeEventListener(BlueGigaEventListener listener) {
767 transactionManager.thenAccept(manager -> {
768 manager.removeEventListener(listener);
773 public void bluegigaEventReceived(@Nullable BlueGigaResponse event) {
774 if (event instanceof BlueGigaScanResponseEvent) {
776 BlueGigaScanResponseEvent scanEvent = (BlueGigaScanResponseEvent) event;
778 // We use the scan event to add any devices we hear to the devices list
779 // The device gets created, and then manages itself for discovery etc.
780 BluetoothAddress sender = new BluetoothAddress(scanEvent.getSender());
781 BlueGigaBluetoothDevice device = getDevice(sender);
782 device.setAddressType(scanEvent.getAddressType());
783 deviceDiscovered(device);
785 logger.trace("Ignore BlueGigaScanResponseEvent as initialization is not complete");
790 if (event instanceof BlueGigaConnectionStatusEvent) {
791 BlueGigaConnectionStatusEvent connectionEvent = (BlueGigaConnectionStatusEvent) event;
792 connections.put(connectionEvent.getConnection(), new BluetoothAddress(connectionEvent.getAddress()));
795 if (event instanceof BlueGigaDisconnectedEvent) {
796 BlueGigaDisconnectedEvent disconnectedEvent = (BlueGigaDisconnectedEvent) event;
797 connections.remove(disconnectedEvent.getConnection());
802 public void bluegigaClosed(Exception reason) {
803 logger.debug("BlueGiga connection closed, request reinitialization, reason: {}", reason.getMessage());
804 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, reason.getMessage());