]> git.basschouten.com Git - openhab-addons.git/blob
3170d6357dcdbc52991ee55974f7be94396a1464
[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.bluegiga.handler;
14
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;
20 import java.util.Map;
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;
32
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;
98
99 /**
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.
103  * <p>
104  * The handler provides the serial interface to the dongle via the BlueGiga BG-API library.
105  * <p>
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.
110  *
111  * @author Chris Jackson - Initial contribution
112  * @author Kai Kreuzer - Made handler implement BlueGigaHandlerListener
113  * @author Pauli Anttila - Many improvements
114  */
115 @NonNullByDefault
116 public class BlueGigaBridgeHandler extends AbstractBluetoothBridgeHandler<BlueGigaBluetoothDevice>
117         implements BlueGigaEventListener, BlueGigaHandlerListener {
118
119     private final Logger logger = LoggerFactory.getLogger(BlueGigaBridgeHandler.class);
120
121     private final int COMMAND_TIMEOUT_MS = 5000;
122     private final int INITIALIZATION_INTERVAL_SEC = 60;
123
124     private final SerialPortManager serialPortManager;
125
126     private final ScheduledExecutorService executor = ThreadPoolManager.getScheduledPool("BlueGiga");
127
128     private BlueGigaConfiguration configuration = new BlueGigaConfiguration();
129
130     // The serial port input stream.
131     private Optional<InputStream> inputStream = Optional.empty();
132
133     // The serial port output stream.
134     private Optional<OutputStream> outputStream = Optional.empty();
135
136     // The BlueGiga API handler
137     private CompletableFuture<BlueGigaSerialHandler> serialHandler = CompletableFuture
138             .failedFuture(new IllegalStateException("Uninitialized"));
139
140     // The BlueGiga transaction manager
141     @NonNullByDefault({})
142     private CompletableFuture<BlueGigaTransactionManager> transactionManager = CompletableFuture
143             .failedFuture(new IllegalStateException("Uninitialized"));
144
145     // The maximum number of connections this interface supports
146     private int maxConnections = 0;
147
148     // Our BT address
149     private @Nullable BluetoothAddress address;
150
151     // Map of open connections
152     private final Map<Integer, BluetoothAddress> connections = new ConcurrentHashMap<>();
153
154     private volatile boolean initComplete = false;
155
156     private CompletableFuture<SerialPort> serialPortFuture = CompletableFuture
157             .failedFuture(new IllegalStateException("Uninitialized"));
158
159     private @Nullable ScheduledFuture<?> removeInactiveDevicesTask;
160     private @Nullable ScheduledFuture<?> discoveryTask;
161     private @Nullable ScheduledFuture<?> initTask;
162
163     private @Nullable Future<?> passiveScanIdleTimer;
164
165     public BlueGigaBridgeHandler(Bridge bridge, SerialPortManager serialPortManager) {
166         super(bridge);
167         this.serialPortManager = serialPortManager;
168     }
169
170     @Override
171     public void initialize() {
172         super.initialize();
173         updateStatus(ThingStatus.UNKNOWN);
174         if (initTask == null) {
175             initTask = scheduler.scheduleWithFixedDelay(this::checkInit, 0, 10, TimeUnit.SECONDS);
176         }
177     }
178
179     protected void checkInit() {
180         boolean init = false;
181         try {
182             if (!serialHandler.get().isAlive()) {
183                 logger.debug("BLE serial handler seems to be dead, reinitilize");
184                 stop();
185                 init = true;
186             }
187         } catch (InterruptedException e) {
188             return;
189         } catch (ExecutionException e) {
190             init = true;
191         }
192
193         if (init) {
194             logger.debug("Initialize BlueGiga");
195             start();
196         }
197     }
198
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);
207
208                 String serialPortName = configuration.port;
209                 int baudRate = 115200;
210
211                 logger.debug("Connecting to serial port '{}'", serialPortName);
212                 try {
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);
217                     }
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);
221
222                     sp.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_OUT);
223                     sp.enableReceiveThreshold(1);
224                     sp.enableReceiveTimeout(2000);
225
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);
229
230                     logger.info("Connected to serial port '{}'.", serialPortName);
231
232                     try {
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);
238                     }
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) -> {
242                         if (th != null) {
243                             // we need to shut down the port now.
244                             closeSerialPort(sp);
245                         }
246                     });
247                     return sp;
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);
259                 }
260             }, executor);
261
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);
269                 return th;
270             });
271             transactionManager.thenRun(() -> {
272                 try {
273                     // Stop any procedures that are running
274                     bgEndProcedure();
275
276                     // Set mode to non-discoverable etc.
277                     bgSetMode();
278
279                     // Get maximum parallel connections
280                     maxConnections = readMaxConnections().getMaxconn();
281
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);
287                     }
288
289                     // Get our Bluetooth address
290                     address = new BluetoothAddress(readAddress().getAddress());
291
292                     updateThingProperties();
293
294                     initComplete = true;
295                     updateStatus(ThingStatus.ONLINE);
296                     startScheduledTasks();
297                 } catch (BlueGigaException e) {
298                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
299                             "Initialization of BlueGiga controller failed");
300                 }
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.
304                     return null;
305                 }
306                 logger.warn("Error initializing bluegiga", th);
307                 return null;
308             });
309
310         } else {
311             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR);
312         }
313     }
314
315     @Override
316     public void dispose() {
317         if (initTask != null) {
318             initTask.cancel(true);
319             initTask = null;
320         }
321         stop();
322         super.dispose();
323     }
324
325     private void stop() {
326         logger.info("Stop BlueGiga");
327         transactionManager.thenAccept(tman -> {
328             tman.removeEventListener(this);
329             tman.close();
330         });
331         serialHandler.thenAccept(sh -> {
332             sh.removeHandlerListener(this);
333             sh.close();
334         });
335         address = null;
336         initComplete = false;
337         connections.clear();
338
339         serialPortFuture.thenAccept(this::closeSerialPort);
340         serialPortFuture.cancel(false);
341         stopScheduledTasks();
342     }
343
344     private void schedulePassiveScan() {
345         cancelScheduledPassiveScan();
346         passiveScanIdleTimer = executor.schedule(() -> {
347             if (!activeScanEnabled) {
348                 logger.debug("Activate passive scan");
349                 bgEndProcedure();
350                 bgStartScanning(false, configuration.passiveScanInterval, configuration.passiveScanWindow);
351             } else {
352                 logger.debug("Ignore passive scan activation as active scan is active");
353             }
354         }, configuration.passiveScanIdleTime, TimeUnit.MILLISECONDS);
355     }
356
357     private void cancelScheduledPassiveScan() {
358         if (passiveScanIdleTimer != null) {
359             passiveScanIdleTimer.cancel(true);
360         }
361     }
362
363     private void startScheduledTasks() {
364         schedulePassiveScan();
365         discoveryTask = scheduler.scheduleWithFixedDelay(this::refreshDiscoveredDevices, 0, 10, TimeUnit.SECONDS);
366     }
367
368     private void stopScheduledTasks() {
369         cancelScheduledPassiveScan();
370         if (removeInactiveDevicesTask != null) {
371             removeInactiveDevicesTask.cancel(true);
372             removeInactiveDevicesTask = null;
373         }
374         if (discoveryTask != null) {
375             discoveryTask.cancel(true);
376             discoveryTask = null;
377         }
378     }
379
380     private BlueGigaGetConnectionsResponse readMaxConnections() throws BlueGigaException {
381         return sendCommandWithoutChecks(new BlueGigaGetConnectionsCommand(), BlueGigaGetConnectionsResponse.class);
382     }
383
384     private BlueGigaAddressGetResponse readAddress() throws BlueGigaException {
385         return sendCommandWithoutChecks(new BlueGigaAddressGetCommand(), BlueGigaAddressGetResponse.class);
386     }
387
388     private BlueGigaGetInfoResponse readInfo() throws BlueGigaException {
389         return sendCommandWithoutChecks(new BlueGigaGetInfoCommand(), BlueGigaGetInfoResponse.class);
390     }
391
392     private void updateThingProperties() throws BlueGigaException {
393         BlueGigaGetInfoResponse infoResponse = readInfo();
394
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);
403     }
404
405     private void closeSerialPort(SerialPort sp) {
406         sp.removeEventListener();
407         try {
408             sp.disableReceiveTimeout();
409         } catch (Exception e) {
410             // Ignore all as RXTX seems to send arbitrary exceptions when BlueGiga module is detached
411         } finally {
412             outputStream.ifPresent(output -> {
413                 try {
414                     output.close();
415                 } catch (IOException e) {
416                 }
417             });
418             inputStream.ifPresent(input -> {
419                 try {
420                     input.close();
421                 } catch (IOException e) {
422                 }
423             });
424             sp.close();
425             logger.debug("Closed serial port.");
426             inputStream = Optional.empty();
427             outputStream = Optional.empty();
428         }
429     }
430
431     @Override
432     public void scanStart() {
433         super.scanStart();
434         logger.debug("Start active scan");
435         // Stop the passive scan
436         cancelScheduledPassiveScan();
437         bgEndProcedure();
438
439         // Start an active scan
440         bgStartScanning(true, configuration.activeScanInterval, configuration.activeScanWindow);
441     }
442
443     @Override
444     public void scanStop() {
445         super.scanStop();
446         logger.debug("Stop active scan");
447
448         // Stop the active scan
449         bgEndProcedure();
450
451         // Start a passive scan after idle delay
452         schedulePassiveScan();
453     }
454
455     @Override
456     public @Nullable BluetoothAddress getAddress() {
457         BluetoothAddress addr = address;
458         if (addr != null) {
459             return addr;
460         } else {
461             throw new IllegalStateException("Adapter has not been initialized yet!");
462         }
463     }
464
465     @Override
466     protected BlueGigaBluetoothDevice createDevice(BluetoothAddress address) {
467         return new BlueGigaBluetoothDevice(this, address, BluetoothAddressType.UNKNOWN);
468     }
469
470     /**
471      * Connects to a device.
472      * <p>
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.
475      *
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
479      */
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)) {
483             return false;
484         }
485
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);
491             return false;
492         }
493
494         logger.debug("BlueGiga Connect: address {}.", address);
495
496         // @formatter:off
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)
504                 .build();
505         // @formatter:on
506         try {
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,
510                     e.getMessage());
511             return false;
512         }
513     }
514
515     /**
516      * Close a connection using {@link BlueGigaDisconnectCommand}
517      *
518      * @param connectionHandle
519      * @return
520      */
521     public boolean bgDisconnect(int connectionHandle) {
522         logger.debug("BlueGiga Disconnect: connection {}", connectionHandle);
523         BlueGigaDisconnectCommand command = new BlueGigaDisconnectCommand.CommandBuilder()
524                 .withConnection(connectionHandle).build();
525
526         try {
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,
530                     e.getMessage());
531             return false;
532         }
533     }
534
535     /**
536      * Start a read of all primary services using {@link BlueGigaReadByGroupTypeCommand}
537      *
538      * @param connectionHandle
539      * @return true if successful
540      */
541     public boolean bgFindPrimaryServices(int connectionHandle) {
542         logger.debug("BlueGiga FindPrimary: connection {}", connectionHandle);
543         // @formatter:off
544         BlueGigaReadByGroupTypeCommand command = new BlueGigaReadByGroupTypeCommand.CommandBuilder()
545                 .withConnection(connectionHandle)
546                 .withStart(1)
547                 .withEnd(65535)
548                 .withUuid(UUID.fromString("00002800-0000-1000-8000-00805F9B34FB"))
549                 .build();
550         // @formatter:on
551         try {
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,
556                     e.getMessage());
557             return false;
558         }
559     }
560
561     /**
562      * Start a read of all characteristics using {@link BlueGigaFindInformationCommand}
563      *
564      * @param connectionHandle
565      * @return true if successful
566      */
567     public boolean bgFindCharacteristics(int connectionHandle) {
568         logger.debug("BlueGiga Find: connection {}", connectionHandle);
569         // @formatter:off
570         BlueGigaFindInformationCommand command = new BlueGigaFindInformationCommand.CommandBuilder()
571                 .withConnection(connectionHandle)
572                 .withStart(1)
573                 .withEnd(65535)
574                 .build();
575         // @formatter:on
576         try {
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,
581                     e.getMessage());
582             return false;
583         }
584     }
585
586     public boolean bgReadCharacteristicDeclarations(int connectionHandle) {
587         logger.debug("BlueGiga Find: connection {}", connectionHandle);
588         // @formatter:off
589         BlueGigaReadByTypeCommand command = new BlueGigaReadByTypeCommand.CommandBuilder()
590                 .withConnection(connectionHandle)
591                 .withStart(1)
592                 .withEnd(65535)
593                 .withUUID(BluetoothBindingConstants.ATTR_CHARACTERISTIC_DECLARATION)
594                 .build();
595         // @formatter:on
596         try {
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,
600                     e.getMessage());
601             return false;
602         }
603     }
604
605     /**
606      * Read a characteristic using {@link BlueGigaReadByHandleCommand}
607      *
608      * @param connectionHandle
609      * @param handle
610      * @return true if successful
611      */
612     public boolean bgReadCharacteristic(int connectionHandle, int handle) {
613         logger.debug("BlueGiga Read: connection {}, handle {}", connectionHandle, handle);
614         // @formatter:off
615         BlueGigaReadByHandleCommand command = new BlueGigaReadByHandleCommand.CommandBuilder()
616                 .withConnection(connectionHandle)
617                 .withChrHandle(handle)
618                 .build();
619         // @formatter:on
620         try {
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,
624                     e.getMessage());
625             return false;
626         }
627     }
628
629     /**
630      * Write a characteristic using {@link BlueGigaAttributeWriteCommand}
631      *
632      * @param connectionHandle
633      * @param handle
634      * @param value
635      * @return true if successful
636      */
637     public boolean bgWriteCharacteristic(int connectionHandle, int handle, int[] value) {
638         logger.debug("BlueGiga Write: connection {}, handle {}", connectionHandle, handle);
639         // @formatter:off
640         BlueGigaAttributeWriteCommand command = new BlueGigaAttributeWriteCommand.CommandBuilder()
641                 .withConnection(connectionHandle)
642                 .withAttHandle(handle)
643                 .withData(value)
644                 .build();
645         // @formatter:on
646         try {
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,
651                     e.getMessage());
652             return false;
653         }
654     }
655
656     /*
657      * The following methods are private methods for handling the BlueGiga protocol
658      */
659     private boolean bgEndProcedure() {
660         try {
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.");
665             return false;
666         }
667     }
668
669     private boolean bgSetMode() {
670         try {
671             // @formatter:off
672             BlueGigaSetModeCommand command = new BlueGigaSetModeCommand.CommandBuilder()
673                     .withConnect(GapConnectableMode.GAP_NON_CONNECTABLE)
674                     .withDiscover(GapDiscoverableMode.GAP_NON_DISCOVERABLE)
675                     .build();
676             // @formatter:on
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());
681             return false;
682         }
683     }
684
685     /**
686      * Starts scanning on the dongle
687      *
688      * @param active true for active scanning
689      */
690     private boolean bgStartScanning(boolean active, int interval, int window) {
691         try {
692             // @formatter:off
693             BlueGigaSetScanParametersCommand scanCommand = new BlueGigaSetScanParametersCommand.CommandBuilder()
694                     .withActiveScanning(active)
695                     .withScanInterval(interval)
696                     .withScanWindow(window)
697                     .build();
698             // @formatter:on
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");
706                     return true;
707                 }
708             }
709         } catch (BlueGigaException e) {
710             logger.debug("Error occured when sending start scan command, reason: {}", e.getMessage());
711         }
712         logger.debug("Scan start failed.");
713         return false;
714     }
715
716     /**
717      * Send command only if initialization phase is successfully done
718      */
719     private <T extends BlueGigaResponse> T sendCommand(BlueGigaCommand command, Class<T> expectedResponse,
720             boolean schedulePassiveScan) throws BlueGigaException {
721         if (!initComplete) {
722             throw new BlueGigaException("BlueGiga not initialized");
723         }
724
725         if (schedulePassiveScan) {
726             cancelScheduledPassiveScan();
727         }
728         try {
729             return sendCommandWithoutChecks(command, expectedResponse);
730         } finally {
731             if (schedulePassiveScan) {
732                 schedulePassiveScan();
733             }
734         }
735     }
736
737     /**
738      * Forcefully send command without any checks
739      */
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);
745         } else {
746             throw new BlueGigaException("Transaction manager missing");
747         }
748     }
749
750     /**
751      * Add an event listener for the BlueGiga events
752      *
753      * @param listener the {@link BlueGigaEventListener} to add
754      */
755     public void addEventListener(BlueGigaEventListener listener) {
756         transactionManager.thenAccept(manager -> {
757             manager.addEventListener(listener);
758         });
759     }
760
761     /**
762      * Remove an event listener for the BlueGiga events
763      *
764      * @param listener the {@link BlueGigaEventListener} to remove
765      */
766     public void removeEventListener(BlueGigaEventListener listener) {
767         transactionManager.thenAccept(manager -> {
768             manager.removeEventListener(listener);
769         });
770     }
771
772     @Override
773     public void bluegigaEventReceived(@Nullable BlueGigaResponse event) {
774         if (event instanceof BlueGigaScanResponseEvent) {
775             if (initComplete) {
776                 BlueGigaScanResponseEvent scanEvent = (BlueGigaScanResponseEvent) event;
777
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);
784             } else {
785                 logger.trace("Ignore BlueGigaScanResponseEvent as initialization is not complete");
786             }
787             return;
788         }
789
790         if (event instanceof BlueGigaConnectionStatusEvent) {
791             BlueGigaConnectionStatusEvent connectionEvent = (BlueGigaConnectionStatusEvent) event;
792             connections.put(connectionEvent.getConnection(), new BluetoothAddress(connectionEvent.getAddress()));
793         }
794
795         if (event instanceof BlueGigaDisconnectedEvent) {
796             BlueGigaDisconnectedEvent disconnectedEvent = (BlueGigaDisconnectedEvent) event;
797             connections.remove(disconnectedEvent.getConnection());
798         }
799     }
800
801     @Override
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());
805     }
806 }