Direct-BT
2.3.1
Direct-BT - Direct Bluetooth Programming.
|
Go to the documentation of this file.
26 package jau.direct_bt;
28 import java.lang.ref.WeakReference;
29 import java.util.ArrayList;
30 import java.util.List;
32 import java.util.concurrent.atomic.AtomicBoolean;
62 private final WeakReference<DBTAdapter> wbr_adapter;
65 private final long ts_creation;
66 volatile long ts_last_discovery;
67 volatile long ts_last_update;
68 volatile short hciConnHandle;
69 private volatile String name_cached;
70 final List<WeakReference<DBTGattService>> serviceCache =
new ArrayList<WeakReference<DBTGattService>>();
72 private final AtomicBoolean isClosing =
new AtomicBoolean(
false);
74 private final AtomicBoolean isConnected =
new AtomicBoolean(
false);
81 public void deviceConnected(
final BTDevice device,
final short handle,
final long timestamp) {
82 if( isConnected.compareAndSet(
false,
true) ) {
87 public void deviceDisconnected(
final BTDevice device,
final HCIStatusCode reason,
final short handle,
final long timestamp) {
88 if( isConnected.compareAndSet(
true,
false) ) {
95 return "AdapterStatusListener[device "+addressAndType.
toString()+
"]";
100 final byte byteAddress[],
101 final byte byteAddressType,
102 final long ts_creation,
final String name)
104 super(nativeInstance, compHash(java.util.Arrays.hashCode(byteAddress), 31+byteAddressType));
105 this.wbr_adapter =
new WeakReference<DBTAdapter>(adptr);
108 throw new IllegalArgumentException(
"Unsupported given native addresstype "+byteAddressType);
110 this.ts_creation = ts_creation;
111 ts_last_discovery = ts_creation;
112 ts_last_update = ts_creation;
125 if( !isClosing.compareAndSet(
false,
true) ) {
133 a.removeDiscoveredDevice(
this);
144 if (obj ==
null || !(obj instanceof
DBTDevice)) {
148 return addressAndType.
equals(other.addressAndType);
171 final String v = getNameImpl();
176 private native String getNameImpl();
190 return find(UUID, 0);
195 private native
void initImpl();
201 return getAdapter().addStatusListenerImpl(
this, l);
206 return getAdapter().removeStatusListenerImpl(l);
217 if( isConnected.get() ) {
222 private native
byte disconnectImpl();
226 if( !isConnected.get() ) {
231 private native
byte connectDefaultImpl();
235 final short conn_interval_min,
final short conn_interval_max,
236 final short conn_latency,
final short timeout) {
237 if( !isConnected.get() ) {
239 if( 0 > le_scan_interval || 0 > le_scan_window || 0 > conn_interval_min ||
240 0 > conn_interval_max || 0 > conn_latency || 0 > timeout ) {
243 return HCIStatusCode.
get( connectLEImpl1(le_scan_interval, le_scan_window, conn_interval_min, conn_interval_max, conn_latency, timeout) );
248 private native
byte connectLEImpl0();
249 private native
byte connectLEImpl1(
final short le_scan_interval,
final short le_scan_window,
250 final short conn_interval_min,
final short conn_interval_max,
251 final short conn_latency,
final short timeout);
257 return new SMPKeyMask(getAvailableSMPKeysImpl(responder));
259 private final native
byte getAvailableSMPKeysImpl(
final boolean responder);
264 getLongTermKeyInfoImpl(responder, stream);
267 private final native
void getLongTermKeyInfoImpl(
final boolean responder,
final byte[] sink);
275 private final native
byte setLongTermKeyInfoImpl(
final byte[] source);
280 getSignatureResolvingKeyInfoImpl(responder, stream);
283 private final native
void getSignatureResolvingKeyInfoImpl(
final boolean responder,
final byte[] sink);
289 private final native
byte unpairImpl();
293 return setConnSecurityLevelImpl(sec_level.
value);
295 private final native
boolean setConnSecurityLevelImpl(
final byte sec_level);
301 private final native
byte getConnSecurityLevelImpl();
305 return setConnIOCapabilityImpl(io_cap.
value);
307 private final native
boolean setConnIOCapabilityImpl(
final byte io_cap);
313 private final native
byte getConnIOCapabilityImpl();
317 return setConnSecurityImpl(sec_level.
value, io_cap.
value);
319 private final native
boolean setConnSecurityImpl(
final byte sec_level,
final byte io_cap);
340 return setConnSecurityAutoImpl( iocap_auto.
value );
342 private final native
boolean setConnSecurityAutoImpl(
final byte io_cap);
351 private native
byte setPairingPasskeyImpl(
final int passkey)
throws BTException;
357 private native
byte setPairingPasskeyNegativeImpl() throws
BTException;
363 private native
byte setPairingNumericComparisonImpl(
final boolean equal);
369 private native
byte getPairingModeImpl();
375 private native
byte getPairingStateImpl();
381 return "Device" +
"\u271D" +
"[address"+addressAndType+
", '"+name_cached+
382 "', connected["+isConnected.get()+
", 0x"+Integer.toHexString(hciConnHandle)+
"]]";
384 return toStringImpl();
386 private native String toStringImpl();
397 if(
DBTAdapter.PRINT_DEVICE_LISTS || DEBUG ) {
403 private native
boolean removeImpl() throws
BTException;
406 public final
boolean isValid() {
return super.isValid() ; }
412 final List<BTGattService> services = getServicesImpl();
413 updateServiceCache(services);
415 }
catch (
final Throwable t) {
416 System.err.println(
"DBTDevice.getServices(): Caught "+t.getMessage()+
" on thread "+Thread.currentThread().toString()+
" on "+
toString());
423 private native List<BTGattService> getServicesImpl();
428 return pingGATTImpl();
429 }
catch (
final Throwable t) {
430 System.err.println(
"DBTDevice.pingGATT(): Caught "+t.getMessage()+
" on thread "+Thread.currentThread().toString()+
" on "+
toString());
437 private native
boolean pingGATTImpl();
476 private void clearServiceCache() {
477 synchronized(serviceCache) {
478 for(
int i = serviceCache.size() - 1; i >= 0; i-- ) {
479 serviceCache.get(i).clear();
480 serviceCache.remove(i);
484 private void updateServiceCache(
final List<BTGattService> services) {
485 synchronized(serviceCache) {
487 if(
null != services ) {
488 for(
final BTGattService service : services) {
489 serviceCache.add(
new WeakReference<DBTGattService>( (DBTGattService)service ) );
495 boolean checkServiceCache(
final boolean getServices) {
496 synchronized(serviceCache) {
497 if( serviceCache.isEmpty() ) {
500 if( serviceCache.isEmpty() ) {
536 DBTObject findInCache(
final String uuid,
final BTType type) {
537 final boolean anyType = BTType.NONE == type;
538 final boolean serviceType = BTType.GATT_SERVICE == type;
539 final boolean charType = BTType.GATT_CHARACTERISTIC== type;
540 final boolean descType = BTType.GATT_DESCRIPTOR == type;
542 if( !anyType && !serviceType && !charType && !descType ) {
545 synchronized(serviceCache) {
546 if( !checkServiceCache(
true) ) {
550 if(
null == uuid && ( anyType || serviceType ) ) {
552 while( !serviceCache.isEmpty() ) {
553 final DBTGattService service = serviceCache.get(0).get();
554 if(
null == service ) {
555 serviceCache.remove(0);
562 for(
int srvIdx = serviceCache.size() - 1; srvIdx >= 0; srvIdx-- ) {
563 final DBTGattService service = serviceCache.get(srvIdx).get();
564 if(
null == service ) {
565 serviceCache.remove(srvIdx);
568 if( ( anyType || serviceType ) && service.getUUID().equals(uuid) ) {
571 if( anyType || charType || descType ) {
572 final DBTObject dbtObj = service.findInCache(uuid, type);
573 if(
null != dbtObj ) {
final boolean equals(final Object obj)
ENC_ONLY
Encryption and no authentication (no MITM).
DBTObject(final long nativeInstance, final int hashValue)
BTGattService find(final String UUID, final long timeoutMS)
Find a BluetoothGattService.
final boolean isValid()
Returns whether the device is valid, i.e.
HCIStatusCode setPairingPasskey(final int passkey)
Method sets the given passkey entry, see PairingMode#PASSKEY_ENTRY_ini.
final boolean setConnSecurityAuto(final SMPIOCapability iocap_auto)
Set automatic security negotiation of BTSecurityLevel and SMPIOCapability pairing mode.
native boolean removeCharListener(final BTGattCharListener l)
Remove the given BTGattCharListener from the listener list.
Bluetooth Security Level.
NO_INPUT_NO_OUTPUT
No input not output, value 3.
boolean addCharListener(final BTGattCharListener listener)
Add the given BTGattCharListener to the listener list if not already present.
static void fprintf_td(final PrintStream out, final String format, final Object ... args)
Convenient PrintStream#printf(String, Object...) invocation, prepending the elapsedTimeMillis() times...
final long getLastUpdateTimestamp()
Returns the timestamp in monotonic milliseconds when this device instance underlying data has been up...
final HCIStatusCode connect()
boolean removeStatusListener(final AdapterStatusListener l)
Remove the given AdapterStatusListener from the list.
DBTAdapter getAdapter()
Returns the adapter on which this device was discovered or connected.
Author: Sven Gothel sgothel@jausoft.com Copyright (c) 2020 Gothel Software e.K.
final long getCreationTimestamp()
Returns the timestamp in monotonic milliseconds when this device instance has been created,...
Bluetooth secure pairing mode.
CONNECTION_ALREADY_EXISTS
static final int byte_size
Size of the byte stream representation in bytes (28)
BDAddressAndType getAddressAndType()
Returns the unique device EUI48 address and BDAddressType type.
final boolean setConnSecurityBest(final BTSecurityLevel sec_level, final SMPIOCapability io_cap)
Convenience method to determine the best practice BTSecurityLevel and SMPIOCapability based on the gi...
PairingMode getPairingMode()
Returns the current PairingMode used by the device.
A packed 48 bit EUI-48 identifier, formerly known as MAC-48 or simply network device MAC address (Med...
native int removeAllAssociatedCharListener(final BTGattChar associatedCharacteristic)
Remove all BTGattCharListener from the list, which are associated to the given BTGattChar.
List< BTGattService > getServices()
Returns a list of BluetoothGattServices available on this device.
SMP Long Term Key Info, used for platform agnostic persistence.
native short getRSSI()
Returns the Received Signal Strength Indicator of the device.
SMP Key Type for Distribution, indicates keys distributed in the Transport Specific Key Distribution ...
final SMPIOCapability getConnIOCapability()
Return the SMPIOCapability value, determined when the connection is established.
Provides access to Bluetooth GATT characteristic.
native short getTxPower()
Returns the transmission power level (0 means unknown).
final boolean addStatusListener(final AdapterStatusListener l)
Add the given AdapterStatusListener to the list if not already present, listening only for events mat...
Bit mask of 'Extended Inquiry Response' (EIR) data fields, indicating a set of related data.
HCIStatusCode setPairingPasskeyNegative()
Method replies with a negative passkey response, i.e.
static final int byte_size
Size of the byte stream representation in bytes.
UNSET
Denoting unset value, i.e.
final SMPSignatureResolvingKeyInfo getSignatureResolvingKeyInfo(final boolean responder)
Returns a copy of the Signature Resolving Key (LTK) info, valid after connection and SMP pairing has ...
static HCIStatusCode get(final String name)
Maps the specified name to a constant of HCIStatusCode.
SMP Pairing Process state definition.
final HCIStatusCode setLongTermKeyInfo(final SMPLongTermKeyInfo ltk)
Sets the long term ket (LTK) info of this device to reuse pre-paired encryption.
Unique Bluetooth EUI48 address and BDAddressType tuple.
static BTSecurityLevel get(final String name)
Maps the specified name to a constant of BTSecurityLevel.
String getName()
Returns the remote friendly name of this device.
BTType getBluetoothType()
Returns the BluetoothType of this object.
final native boolean isConnSecurityAutoEnabled()
Returns true if automatic security negotiation has been enabled via setConnSecurityAuto(SMPIOCapabili...
final HCIStatusCode disconnect()
final HCIStatusCode unpair()
Unpairs this device from the adapter while staying connected.
final boolean setConnIOCapability(final SMPIOCapability io_cap)
Sets the given SMPIOCapability used to connect to this device on the upcoming connection.
SMPPairingState getPairingState()
Returns the current SMPPairingState.
UNSET
Security Level not set, value 0.
BT Core Spec v5.2: Vol 1, Part F Controller Error Codes: 1.3 List of Error Codes.
final boolean setConnSecurity(final BTSecurityLevel sec_level, final SMPIOCapability io_cap)
Sets the given BTSecurityLevel and SMPIOCapability used to connect to this device on the upcoming con...
void close()
Release the native memory associated with this object The object should not be used following a call ...
static SMPPairingState get(final String name)
Maps the specified name to a constant of SMPPairingState.
static PairingMode get(final String name)
Maps the specified name to a constant of PairingMode.
CONNECTION_TERMINATED_BY_LOCAL_HOST
Provides access to Bluetooth GATT characteristic.
static SMPIOCapability get(final String name)
Maps the specified name to a constant of SMPIOCapability.
final SMPKeyMask getAvailableSMPKeys(final boolean responder)
Returns the available SMPKeyMask.KeyType SMPKeyMask for the responder (LL slave) or initiator (LL mas...
Provides access to Bluetooth adapters.
Provides access to Bluetooth GATT descriptor.
static final boolean DEBUG
final SMPLongTermKeyInfo getLongTermKeyInfo(final boolean responder)
Returns a copy of the long term key (LTK) info, valid after connection and SMP pairing has been compl...
native int removeAllCharListener()
Remove all BTGattCharListener from the list.
final long getLastDiscoveryTimestamp()
Returns the timestamp in monotonic milliseconds when this device instance has discovered or connected...
final BTSecurityLevel getConnSecurityLevel()
Return the BTSecurityLevel, determined when the connection is established.
HCIStatusCode setPairingNumericComparison(final boolean equal)
Method sets the numeric comparison result, see PairingMode#NUMERIC_COMPARE_ini.
final boolean setConnSecurityLevel(final BTSecurityLevel sec_level)
Set the BTSecurityLevel used to connect to this device on the upcoming connection.
native Map< Short, byte[]> getManufacturerData()
Returns a map containing manufacturer specific advertisement data.
BTGattService find(final String UUID)
Find a BluetoothGattService.
native void deleteImpl(long nativeInstance)
Deletes the native instance.Called via delete() and at this point this java reference has been remove...
Bluetooth address type constants.
boolean equals(final Object obj)
final BTGattChar getAssociatedChar()
Returns the weakly associated BTGattChar to this listener instance.
final void printDeviceLists()
Print the internally maintained BTDevice lists to stderr:
BTGattChar event listener for notification and indication events.
SMP Signature Resolving Key Info, used for platform agnostic persistence.
BTAdapter status listener for BTDevice discovery events: Added, updated and removed; as well as for c...
static BDAddressType get(final String name)
Maps the specified name to a constant of BDAddressType.
BDADDR_UNDEFINED
Undefined.
HCIStatusCode connectLE(final short le_scan_interval, final short le_scan_window, final short conn_interval_min, final short conn_interval_max, final short conn_latency, final short timeout)
Establish a HCI BDADDR_LE_PUBLIC or BDADDR_LE_RANDOM connection to this device.
final boolean getConnected()
Returns the connected state of the device.
boolean pingGATT()
Issues a GATT ping to the device, validating whether it is still reachable.
final short getConnectionHandle()
Return the HCI connection handle to the LE or BREDR peer, zero if not connected.
final void getStream(final byte[] sink, int pos)
Method transfers all bytes representing this instance into the given destination array at the given p...
boolean removeStatusListener(final AdapterStatusListener l)
Remove the given AdapterStatusListener from the list.