aboutsummaryrefslogtreecommitdiffstats
path: root/java/jau/direct_bt/DBTDevice.java
blob: 5fb0ea9a2d1611ba5eaf2bb2fc737e2734638b02 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
/**
 * Author: Sven Gothel <sgothel@jausoft.com>
 * Copyright (c) 2020 Gothel Software e.K.
 * Copyright (c) 2020 ZAFENA AB
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package jau.direct_bt;

import java.lang.ref.WeakReference;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import org.direct_bt.AdapterStatusListener;
import org.direct_bt.BDAddressAndType;
import org.direct_bt.BDAddressType;
import org.direct_bt.BTSecurityLevel;
import org.direct_bt.BTDevice;
import org.direct_bt.BTException;
import org.direct_bt.BTGattChar;
import org.direct_bt.BTGattService;
import org.direct_bt.BTRole;
import org.direct_bt.EInfoReport;
import org.direct_bt.BTGattCharListener;
import org.direct_bt.HCIStatusCode;
import org.direct_bt.LE_PHYs;
import org.direct_bt.PairingMode;
import org.direct_bt.SMPIOCapability;
import org.direct_bt.SMPIdentityResolvingKey;
import org.direct_bt.SMPKeyBin;
import org.direct_bt.SMPKeyMask;
import org.direct_bt.SMPLinkKey;
import org.direct_bt.SMPLongTermKey;
import org.direct_bt.SMPPairingState;
import org.direct_bt.SMPSignatureResolvingKey;
import org.jau.io.PrintUtil;
import org.jau.net.EUI48;

public class DBTDevice extends DBTObject implements BTDevice
{
    private static final boolean DEBUG = DBTManager.DEBUG;

    /** Device's adapter weak back-reference */
    private final WeakReference<DBTAdapter> wbr_adapter;

    private final BDAddressAndType addressAndType;
    private final long ts_creation;
    volatile long ts_last_discovery;
    volatile long ts_last_update;
    volatile short hciConnHandle;
    private volatile String name_cached;
    /* pp */ final List<WeakReference<DBTGattService>> serviceCache = new ArrayList<WeakReference<DBTGattService>>();
    private final EInfoReport eir_ = new EInfoReport();
    private final EInfoReport eir_ind_ = new EInfoReport();
    private final EInfoReport eir_scan_rsp_ = new EInfoReport();

    private final AtomicBoolean isClosing = new AtomicBoolean(false);

    /* pp */ final AtomicBoolean isConnected = new AtomicBoolean(false);

    /* pp */ DBTDevice(final long nativeInstance, final DBTAdapter adptr,
                       final byte byteAddress[/*6*/],
                       final byte byteAddressType,
                       final long ts_creation, final String name)
    {
        super(nativeInstance, compHash(java.util.Arrays.hashCode(byteAddress), 31+byteAddressType));
        this.wbr_adapter = new WeakReference<DBTAdapter>(adptr);
        this.addressAndType = new BDAddressAndType(new EUI48(byteAddress, ByteOrder.nativeOrder()), BDAddressType.get(byteAddressType));
        if( BDAddressType.BDADDR_UNDEFINED == addressAndType.type ) {
            throw new IllegalArgumentException("Unsupported given native addresstype "+byteAddressType);
        }
        this.ts_creation = ts_creation;
        ts_last_discovery = ts_creation;
        ts_last_update = ts_creation;
        hciConnHandle = 0;
        name_cached = name;
        initImpl();
        // FIXME enableTrustedNotificationsImpl(trustedNotificationsCB);
    }

    @Override
    public void close() {
        if( !isValid() ) {
            return;
        }
        if( !isClosing.compareAndSet(false, true) ) {
            return;
        }
        clearServiceCache();

        final DBTAdapter a = getAdapter();
        if( null != a ) {
            a.removeDiscoveredDevice(this);
        }
        super.close();
    }

    @Override
    public final long getCreationTimestamp() { return ts_creation; }

    @Override
    public final long getLastDiscoveryTimestamp() { return ts_last_discovery; }

    @Override
    public final long getLastUpdateTimestamp() { return ts_last_update; }

    @Override
    public DBTAdapter getAdapter() { return wbr_adapter.get(); }

    @Override
    public final BTRole getRole() {
        return BTRole.get(getRoleImpl());
    }
    private native byte getRoleImpl();

    @Override
    public boolean equals(final Object obj)
    {
        if(this == obj) {
            return true;
        }
        if (obj == null || !(obj instanceof DBTDevice)) {
            return false;
        }
        final DBTDevice other = (DBTDevice)obj;
        return addressAndType.equals(other.addressAndType);
    }

    @Override
    public BDAddressAndType getAddressAndType() { return addressAndType; }

    @Override
    public String getName() {
        if( !isValid() ) {
            return name_cached;
        } else {
            final String v = getNameImpl();
            name_cached = v;
            return v;
        }
    }
    private native String getNameImpl();

    @Override
    public BTGattService findGattService(final String service_uuid) {
        synchronized(serviceCache) {
            if( !checkServiceCache(true) ) {
                return null;
            }
            for(int srvIdx = serviceCache.size() - 1; srvIdx >= 0; srvIdx-- ) {
                final DBTGattService service = serviceCache.get(srvIdx).get();
                if( null == service ) {
                    serviceCache.remove(srvIdx); // remove dead ref
                    continue; // cont w/ next service
                }
                if( service.getUUID().equals(service_uuid) ) {
                    return service;
                }
            }
            return null;
        }
    }

    @Override
    public BTGattChar findGattChar(final String service_uuid, final String char_uuid) {
        final BTGattService s = findGattService(service_uuid);
        if( null == s ) {
            return null;
        }
        return s.findGattChar(char_uuid);
    }

    @Override
    public BTGattChar findGattChar(final String char_uuid) {
        synchronized(serviceCache) {
            if( !checkServiceCache(true) ) {
                return null;
            }
            for(int srvIdx = serviceCache.size() - 1; srvIdx >= 0; srvIdx-- ) {
                final DBTGattService s = serviceCache.get(srvIdx).get();
                if( null == s ) {
                    serviceCache.remove(srvIdx); // remove dead ref
                    continue; // cont w/ next service
                }
                final BTGattChar c = s.findGattChar(char_uuid);
                if( null != c ) {
                    return c;
                }
            }
            return null;
        }
    }

    /* internal */

    private native void initImpl();

    /* DBT method calls: Connection */

    @Override
    public final boolean addStatusListener(final AdapterStatusListener l) {
        return getAdapter().addStatusListenerImpl(this, l);
    }

    @Override
    public boolean removeStatusListener(final AdapterStatusListener l) {
        return getAdapter().removeStatusListenerImpl(l);
    }

    @Override
    public final boolean getConnected() { return isConnected.get(); }

    @Override
    public final short getConnectionHandle() { return hciConnHandle; }

    @Override
    public HCIStatusCode getConnectedLE_PHY(final LE_PHYs[] resTx, final LE_PHYs[] resRx) {
        // pre-init
        resTx[0] = new LE_PHYs(LE_PHYs.PHY.LE_1M);
        resRx[0] = new LE_PHYs(LE_PHYs.PHY.LE_1M);
        final byte[] t = { resTx[0].mask };
        final byte[] r = { resRx[0].mask };
        final HCIStatusCode res = HCIStatusCode.get( getConnectedLE_PHYImpl(t, r) );
        resTx[0] = new LE_PHYs(t[0]);
        resRx[0] = new LE_PHYs(r[0]);
        return res;
    }
    private native byte getConnectedLE_PHYImpl(byte[] resTx, byte[] resRx);

    @Override
    public HCIStatusCode setConnectedLE_PHY(final LE_PHYs Tx, final LE_PHYs Rx) {
        return HCIStatusCode.get( setConnectedLE_PHYImpl(Tx.mask, Rx.mask) );
    }
    private native byte setConnectedLE_PHYImpl(final byte Tx, final byte Rx);

    @Override
    public final LE_PHYs getTxPhys() {
        return new LE_PHYs( getTxPhysImpl() );
    }
    private native byte getTxPhysImpl();

    @Override
    public final LE_PHYs getRxPhys() {
        return new LE_PHYs( getRxPhysImpl() );
    }
    private native byte getRxPhysImpl();

    @Override
    public final HCIStatusCode disconnect() {
        if( isConnected.get() ) {
            return HCIStatusCode.get( disconnectImpl() ); // event callbacks will be generated by implementation
        }
        return HCIStatusCode.CONNECTION_TERMINATED_BY_LOCAL_HOST;
    }
    private native byte disconnectImpl();

    @Override
    public native int getResponderSMPPassKey();

    @Override
    public final String getResponderSMPPassKeyString() {
        return String.format((Locale)null, "%06d", getResponderSMPPassKey());
    }

    @Override
    public final HCIStatusCode connectDefault() {
        if( !isConnected.get() ) {
            return HCIStatusCode.get( connectDefaultImpl() ); // event callbacks will be generated by implementation
        }
        return HCIStatusCode.CONNECTION_ALREADY_EXISTS;
    }
    private native byte connectDefaultImpl();

    @Override
    public 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) {
        if( !isConnected.get() ) {
            // event callbacks will be generated by implementation
            if( 0 > le_scan_interval  || 0 > le_scan_window || 0 > conn_interval_min ||
                0 > conn_interval_max || 0 > conn_latency   || 0 > timeout ) {
                return HCIStatusCode.get( connectLEImpl0() );
            } else {
                return HCIStatusCode.get( connectLEImpl1(le_scan_interval, le_scan_window, conn_interval_min, conn_interval_max, conn_latency, timeout) );
            }
        }
        return HCIStatusCode.CONNECTION_ALREADY_EXISTS;
    }
    private native byte connectLEImpl0();
    private native byte connectLEImpl1(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);

    /* SC SMP */

    @Override
    public final SMPKeyMask getAvailableSMPKeys(final boolean responder) {
        return new SMPKeyMask(getAvailableSMPKeysImpl(responder));
    }
    private final native byte getAvailableSMPKeysImpl(final boolean responder);

    @Override
    public final boolean setSMPKeyBin(final SMPKeyBin bin) {
        if( !isValid() ) {
            if( DEBUG ) {
                PrintUtil.fprintf_td(System.err, "BTDevice::setSMPKeyBin(): Apply SMPKeyBin failed, device invalid: %s, %s",
                    bin.toString(), toString());
            }
            return false;
        }

        if( !bin.getLocalAddrAndType().equals( getAdapter().getAddressAndType() ) ) {
            if( DEBUG ) {
                PrintUtil.println(System.err, "SMPKeyBin::readAndApply: Local address mismatch: Has "+getAdapter().getAddressAndType().toString()+
                    ", read "+bin.getLocalAddrAndType().toString()+": "+bin.toString());
            }
            return false;
        }
        if( !bin.getRemoteAddrAndType().equals( getAddressAndType() ) ) {
            if( DEBUG ) {
                PrintUtil.println(System.err, "SMPKeyBin::readAndApply: Remote address mismatch: Has "+getAddressAndType().toString()+
                        ", read "+bin.getRemoteAddrAndType().toString()+": "+bin.toString());
            }
            return false;
        }

        // Must be a valid SMPKeyBin instance and at least one LTK key if using encryption.
        if( !bin.isValid() || ( BTSecurityLevel.NONE != bin.getSecLevel() && !bin.hasLTKInit() && !bin.hasLTKResp() ) ) {
            if( DEBUG ) {
                PrintUtil.fprintf_td(System.err, "BTDevice::setSMPKeyBin(): Apply SMPKeyBin failed, all invalid or sec level w/o LTK: %s, %s",
                        bin.toString(), toString());
            }
            return false;
        }

        {
            /**
             *
            if( SMPIOCapability::UNSET != pairing_data.ioCap_auto ||
                ( SMPPairingState::COMPLETED != pairing_data.state &&
                  SMPPairingState::NONE != pairing_data.state ) )
            {
                DBG_PRINT("BTDevice::setSMPKeyBin: Failure, pairing in progress: %s", pairing_data.toString(addressAndType, btRole).c_str());
                return false;
            }
            */
            if( getConnected() ) {
                if( DEBUG ) {
                    PrintUtil.println(System.err, "BTDevice::setSMPKeyBin: Failure, device connected: "+toString());
                }
                return false;
            }

            // Allow no encryption at all, i.e. BTSecurityLevel::NONE
            final BTSecurityLevel applySecLevel = BTSecurityLevel.NONE.value == bin.getSecLevel().value ?
                                                  BTSecurityLevel.NONE : BTSecurityLevel.ENC_ONLY;

            if( !setConnSecurity(applySecLevel, SMPIOCapability.NO_INPUT_NO_OUTPUT) ) {
                if( DEBUG ) {
                    PrintUtil.println(System.err, "BTDevice::setSMPKeyBin: Apply SMPKeyBin failed: Device Connected/ing: "+bin.toString()+", "+toString());
                }
                return false;
            }
        }
        if( bin.hasLTKInit() ) {
            setLongTermKey( bin.getLTKInit() );
        }
        if( bin.hasLTKResp() ) {
            setLongTermKey( bin.getLTKResp() );
        }

        if( bin.hasIRKInit() ) {
            setIdentityResolvingKey( bin.getIRKInit() );
        }
        if( bin.hasIRKResp() ) {
            setIdentityResolvingKey( bin.getIRKResp() );
        }

        if( bin.hasCSRKInit() ) {
            setSignatureResolvingKey( bin.getCSRKInit() );
        }
        if( bin.hasCSRKResp() ) {
            setSignatureResolvingKey( bin.getCSRKResp() );
        }

        if( bin.hasLKInit() ) {
            setLinkKey( bin.getLKInit() );
        }
        if( bin.hasLKResp() ) {
            setLinkKey( bin.getLKResp() );
        }
        return true;
    }

    @Override
    public final HCIStatusCode uploadKeys() {
        return HCIStatusCode.get( uploadKeysImpl() );
    }
    private final native byte uploadKeysImpl();

    @Override
    public final HCIStatusCode uploadKeys(final SMPKeyBin bin, final BTSecurityLevel req_min_level) {
        if( bin.isValid() && bin.getSecLevel().value >= req_min_level.value && setSMPKeyBin(bin) ) {
            return uploadKeys();
        } else {
            return HCIStatusCode.INVALID_PARAMS;
        }
    }

    @Override
    public final HCIStatusCode uploadKeys(final String smp_key_bin_path, final BTSecurityLevel req_min_level, final boolean verbose_) {
        return uploadKeys(SMPKeyBin.read(smp_key_bin_path, this, verbose_), req_min_level);
    }


    @Override
    public final SMPLongTermKey getLongTermKey(final boolean responder) {
        final byte[] stream = new byte[SMPLongTermKey.byte_size];
        getLongTermKeyImpl(responder, stream);
        return new SMPLongTermKey(stream, 0);
    }
    private final native void getLongTermKeyImpl(final boolean responder, final byte[] sink);

    @Override
    public final void setLongTermKey(final SMPLongTermKey ltk) {
        final byte[] stream = new byte[SMPLongTermKey.byte_size];
        ltk.put(stream, 0);
        setLongTermKeyImpl(stream);
    }
    private final native void setLongTermKeyImpl(final byte[] source);

    @Override
    public final SMPIdentityResolvingKey getIdentityResolvingKey(final boolean responder) {
        final byte[] stream = new byte[SMPIdentityResolvingKey.byte_size];
        getIdentityResolvingKeyImpl(responder, stream);
        return new SMPIdentityResolvingKey(stream, 0);
    }
    private final native void getIdentityResolvingKeyImpl(final boolean responder, final byte[] sink);

    @Override
    public final void setIdentityResolvingKey(final SMPIdentityResolvingKey irk) {
        final byte[] stream = new byte[SMPIdentityResolvingKey.byte_size];
        irk.put(stream, 0);
        setIdentityResolvingKeyImpl(stream);
    }
    private final native void setIdentityResolvingKeyImpl(final byte[] source);

    @Override
    public final SMPSignatureResolvingKey getSignatureResolvingKey(final boolean responder) {
        final byte[] stream = new byte[SMPSignatureResolvingKey.byte_size];
        getSignatureResolvingKeyImpl(responder, stream);
        return new SMPSignatureResolvingKey(stream, 0);
    }
    private final native void getSignatureResolvingKeyImpl(final boolean responder, final byte[] sink);

    @Override
    public final void setSignatureResolvingKey(final SMPSignatureResolvingKey irk) {
        final byte[] stream = new byte[SMPSignatureResolvingKey.byte_size];
        irk.put(stream, 0);
        setSignatureResolvingKeyImpl(stream);
    }
    private final native void setSignatureResolvingKeyImpl(final byte[] source);

    @Override
    public final SMPLinkKey getLinkKey(final boolean responder) {
        final byte[] stream = new byte[SMPLinkKey.byte_size];
        getLinkKeyImpl(responder, stream);
        return new SMPLinkKey(stream, 0);
    }
    private final native void getLinkKeyImpl(final boolean responder, final byte[] sink);

    @Override
    public final void setLinkKey(final SMPLinkKey lk) {
        final byte[] stream = new byte[SMPLinkKey.byte_size];
        lk.put(stream, 0);
        setLinkKeyImpl(stream);
    }
    private final native void setLinkKeyImpl(final byte[] source);

    @Override
    public final HCIStatusCode unpair() {
        return HCIStatusCode.get( unpairImpl() );
    }
    private final native byte unpairImpl();

    @Override
    public final BTSecurityLevel getConnSecurityLevel() {
        return BTSecurityLevel.get( getConnSecurityLevelImpl() );
    }
    private final native byte getConnSecurityLevelImpl();

    @Override
    public final SMPIOCapability getConnIOCapability() {
        return SMPIOCapability.get( getConnIOCapabilityImpl() );
    }
    private final native byte getConnIOCapabilityImpl();

    @Override
    public final boolean setConnSecurity(final BTSecurityLevel sec_level, final SMPIOCapability io_cap) {
        return setConnSecurityImpl(sec_level.value, io_cap.value);
    }
    private final native boolean setConnSecurityImpl(final byte sec_level, final byte io_cap);

    @Override
    public final boolean setConnSecurityAuto(final SMPIOCapability iocap_auto) {
        return setConnSecurityAutoImpl( iocap_auto.value );
    }
    private final native boolean setConnSecurityAutoImpl(final byte io_cap);

    @Override
    public final native boolean isConnSecurityAutoEnabled();

    @Override
    public HCIStatusCode setPairingPasskey(final int passkey) {
        return HCIStatusCode.get( setPairingPasskeyImpl(passkey) );
    }
    private native byte setPairingPasskeyImpl(final int passkey) throws BTException;

    @Override
    public HCIStatusCode setPairingPasskeyNegative() {
        return HCIStatusCode.get( setPairingPasskeyNegativeImpl() );
    }
    private native byte setPairingPasskeyNegativeImpl() throws BTException;

    @Override
    public HCIStatusCode setPairingNumericComparison(final boolean equal) {
        return HCIStatusCode.get( setPairingNumericComparisonImpl(equal) );
    }
    private native byte setPairingNumericComparisonImpl(final boolean equal);

    @Override
    public PairingMode getPairingMode() {
        return PairingMode.get( getPairingModeImpl() );
    }
    private native byte getPairingModeImpl();

    @Override
    public SMPPairingState getPairingState() {
        return SMPPairingState.get( getPairingStateImpl() );
    }
    private native byte getPairingStateImpl();

    @Override
    public final String toString() {
        if( !isValid() ) {
            // UTF-8 271D = Cross
            return "Device" + "\u271D" + "[address"+addressAndType+", '"+name_cached+
                    "', connected["+isConnected.get()+", 0x"+Integer.toHexString(hciConnHandle)+"]]";
        }
        return toStringImpl();
    }
    private native String toStringImpl();

    /**
     * {@inheritDoc}
     */
    @Override
    public final boolean remove() throws BTException {
        // close: clear java-listener, super.close()
        //        -> DBTNativeDownlink.delete(): deleteNativeJavaObject(..), deleteImpl(..) -> DBTDevice::remove()
        close();
        // return removeImpl();
        if( DBTAdapter.PRINT_DEVICE_LISTS || DEBUG ) {
            PrintUtil.fprintf_td(System.err, "BTDevice::remove: %s", toString());
            getAdapter().printDeviceLists();
        }
        return true;
    }
    private native boolean removeImpl() throws BTException;

    @Override
    public final boolean isValid() { return super.isNativeValid() /* && isValidImpl() */; }
    // private native boolean isValidImpl();

    @Override
    public List<BTGattService> getGattServices() {
        try {
            List<BTGattService> services = getGattServicesImpl();
            if( null == services ) {
                services = new ArrayList<BTGattService>();
            }
            updateServiceCache(services);
            return services;
        } catch (final Throwable t) {
            System.err.println("DBTDevice.getServices(): Caught "+t.getMessage()+" on thread "+Thread.currentThread().toString()+" on "+toString());
            if(DEBUG) {
                t.printStackTrace();
            }
        }
        return new ArrayList<BTGattService>();
    }
    private native List<BTGattService> getGattServicesImpl();

    @Override
    public native boolean sendNotification(final short char_value_handle, final byte[] value);

    @Override
    public native boolean sendIndication(final short char_value_handle, final byte[] value);

    @Override
    public boolean pingGATT() {
        try {
            return pingGATTImpl();
        } catch (final Throwable t) {
            System.err.println("DBTDevice.pingGATT(): Caught "+t.getMessage()+" on thread "+Thread.currentThread().toString()+" on "+toString());
            if(DEBUG) {
                t.printStackTrace();
            }
        }
        return false;
    }
    private native boolean pingGATTImpl();

    /* property accessors: */

    @Override
    public native short getRSSI();

    @Override
    public final EInfoReport getEIR() {
        synchronized( eir_ ) {
            getEIRImpl(eir_);
            return eir_;
        }
    }
    private native void getEIRImpl(final EInfoReport eir);

    @Override
    public EInfoReport getEIRInd() {
        synchronized( eir_ind_ ) {
            getEIRIndImpl(eir_ind_);
            return eir_ind_;
        }
    }
    private native void getEIRIndImpl(final EInfoReport eir);

    @Override
    public EInfoReport getEIRScanRsp() {
        synchronized( eir_scan_rsp_ ) {
            getEIRScanRspImpl(eir_scan_rsp_);
            return eir_scan_rsp_;
        }
    }
    private native void getEIRScanRspImpl(final EInfoReport eir);

    @Override
    public native short getTxPower ();

    /**
     * {@inheritDoc}
     * <p>
     * Native implementation calls DBTDevice::remove()
     * </p>
     */
    @Override
    protected native void deleteImpl(long nativeInstance);

    @Override
    public boolean addCharListener(final BTGattCharListener listener) {
        return addCharListenerImpl(listener, null);
    }

    @Override
    public boolean addCharListener(final BTGattCharListener listener, final BTGattChar associatedCharacteristic) {
        return addCharListenerImpl(listener, associatedCharacteristic);
    }
    private native boolean addCharListenerImpl(final BTGattCharListener listener, final BTGattChar associatedCharacteristic);

    @Override
    public native boolean removeCharListener(final BTGattCharListener l);

    @Override
    public native int removeAllAssociatedCharListener(final BTGattChar associatedCharacteristic);

    @Override
    public native int removeAllCharListener();

    /* local functionality */

    /* pp */ final void clearServiceCache() {
        synchronized(serviceCache) {
            for(int i = serviceCache.size() - 1; i >= 0; i-- ) {
                serviceCache.get(i).clear();
                serviceCache.remove(i);
            }
        }
    }
    private void updateServiceCache(final List<BTGattService> services) {
        synchronized(serviceCache) {
            clearServiceCache();
            if( null != services ) {
                for(final BTGattService service : services) {
                    serviceCache.add( new WeakReference<DBTGattService>( (DBTGattService)service ) );
                }
            }
        }
    }

    private final boolean checkServiceCache(final boolean retrieveGattServices) {
        synchronized(serviceCache) {
            if( serviceCache.isEmpty() ) {
                if( retrieveGattServices ) {
                    getGattServices();
                    if( serviceCache.isEmpty() ) {
                        return false;
                    }
                } else {
                    return false;
                }
            }
            return true;
        }
    }
}