aboutsummaryrefslogtreecommitdiffstats
path: root/java/jni/direct_bt/DBTDevice.cxx
blob: d28ac0c2650b3e6b270463998d277f40fd76b6c4 (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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
/*
 * 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.
 */

#include "direct_bt_tinyb_DBTDevice.h"

// #define VERBOSE_ON 1
#include <dbt_debug.hpp>

#include "JNIMem.hpp"
#include "helper_base.hpp"
#include "helper_dbt.hpp"

#include "direct_bt/DBTDevice.hpp"
#include "direct_bt/DBTAdapter.hpp"

using namespace direct_bt;

static const std::string _notificationReceivedMethodArgs("(Lorg/tinyb/BluetoothGattCharacteristic;[BJ)V");
static const std::string _indicationReceivedMethodArgs("(Lorg/tinyb/BluetoothGattCharacteristic;[BJZ)V");

class JNICharacteristicListener : public GATTCharacteristicListener {
  private:
    /**
        package org.tinyb;

        public abstract class GATTCharacteristicListener {
            long nativeInstance;

            public void notificationReceived(final BluetoothGattCharacteristic charDecl,
                                             final byte[] value, final long timestamp) {
            }

            public void indicationReceived(final BluetoothGattCharacteristic charDecl,
                                           final byte[] value, final long timestamp,
                                           final boolean confirmationSent) {
            }

        };
    */
    const GATTCharacteristic * associatedCharacteristicRef;
    JNIGlobalRef listenerObj; // keep listener instance alive
    JNIGlobalRef associatedCharacteristicObj; // keeps associated characteristic alive, if not null
    jmethodID  mNotificationReceived = nullptr;
    jmethodID  mIndicationReceived = nullptr;

  public:

    JNICharacteristicListener(JNIEnv *env, DBTDevice *device, jobject listener, GATTCharacteristic * associatedCharacteristicRef)
    : associatedCharacteristicRef(associatedCharacteristicRef),
      listenerObj(listener)
    {
        jclass listenerClazz = search_class(env, listenerObj.getObject());
        java_exception_check_and_throw(env, E_FILE_LINE);
        if( nullptr == listenerClazz ) {
            throw InternalError("CharacteristicListener not found", E_FILE_LINE);
        }

        if( nullptr != associatedCharacteristicRef ) {
            JavaGlobalObj::check(associatedCharacteristicRef->getJavaObject(), E_FILE_LINE);
            associatedCharacteristicObj = JavaGlobalObj::GetJavaObject(associatedCharacteristicRef->getJavaObject()); // new global ref
        }

        mNotificationReceived = search_method(env, listenerClazz, "notificationReceived", _notificationReceivedMethodArgs.c_str(), false);
        java_exception_check_and_throw(env, E_FILE_LINE);
        if( nullptr == mNotificationReceived ) {
            throw InternalError("GATTCharacteristicListener has no notificationReceived"+_notificationReceivedMethodArgs+" method, for "+device->toString(), E_FILE_LINE);
        }
        mIndicationReceived = search_method(env, listenerClazz, "indicationReceived", _indicationReceivedMethodArgs.c_str(), false);
        java_exception_check_and_throw(env, E_FILE_LINE);
        if( nullptr == mNotificationReceived ) {
            throw InternalError("GATTCharacteristicListener has no indicationReceived"+_indicationReceivedMethodArgs+" method, for "+device->toString(), E_FILE_LINE);
        }
    }

    bool match(const GATTCharacteristic & characteristic) override {
        if( nullptr == associatedCharacteristicRef ) {
            return true;
        }
        return characteristic == *associatedCharacteristicRef;
    }

    void notificationReceived(GATTCharacteristicRef charDecl,
                              std::shared_ptr<TROOctets> charValue, const uint64_t timestamp) override {
        JNIEnv *env = *jni_env;
        JavaGlobalObj::check(charDecl->getJavaObject(), E_FILE_LINE);
        jobject jCharDecl = JavaGlobalObj::GetObject(charDecl->getJavaObject());

        const size_t value_size = charValue->getSize();
        jbyteArray jvalue = env->NewByteArray((jsize)value_size);
        env->SetByteArrayRegion(jvalue, 0, (jsize)value_size, (const jbyte *)charValue->get_ptr());
        java_exception_check_and_throw(env, E_FILE_LINE);


        env->CallVoidMethod(listenerObj.getObject(), mNotificationReceived,
                            jCharDecl, jvalue, (jlong)timestamp);
        java_exception_check_and_throw(env, E_FILE_LINE);
    }

    void indicationReceived(GATTCharacteristicRef charDecl,
                            std::shared_ptr<TROOctets> charValue, const uint64_t timestamp,
                            const bool confirmationSent) override {
        JNIEnv *env = *jni_env;
        JavaGlobalObj::check(charDecl->getJavaObject(), E_FILE_LINE);
        jobject jCharDecl = JavaGlobalObj::GetObject(charDecl->getJavaObject());

        const size_t value_size = charValue->getSize();
        jbyteArray jvalue = env->NewByteArray((jsize)value_size);
        env->SetByteArrayRegion(jvalue, 0, (jsize)value_size, (const jbyte *)charValue->get_ptr());
        java_exception_check_and_throw(env, E_FILE_LINE);


        env->CallVoidMethod(listenerObj.getObject(), mIndicationReceived,
                            jCharDecl, jvalue, (jlong)timestamp, (jboolean)confirmationSent);
        java_exception_check_and_throw(env, E_FILE_LINE);
    }
};


void Java_direct_1bt_tinyb_DBTDevice_initImpl(JNIEnv *env, jobject obj)
{
    try {
        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
}

jstring Java_direct_1bt_tinyb_DBTDevice_getNameImpl(JNIEnv *env, jobject obj) {
    try {
        DBTDevice *nativePtr = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(nativePtr->getJavaObject(), E_FILE_LINE);
        return from_string_to_jstring(env, nativePtr->getName());
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
    return nullptr;
}

jstring Java_direct_1bt_tinyb_DBTDevice_toStringImpl(JNIEnv *env, jobject obj) {
    try {
        DBTDevice *nativePtr = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(nativePtr->getJavaObject(), E_FILE_LINE);
        return from_string_to_jstring(env, nativePtr->toString());
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
    return nullptr;
}

jboolean Java_direct_1bt_tinyb_DBTDevice_addCharacteristicListener(JNIEnv *env, jobject obj, jobject listener, jobject jAssociatedCharacteristic) {
    try {
        if( nullptr == listener ) {
            throw IllegalArgumentException("characteristicListener argument is null", E_FILE_LINE);
        }
        {
            JNICharacteristicListener * pre =
                    getObjectRef<JNICharacteristicListener>(env, listener, "nativeInstance");
            if( nullptr != pre ) {
                throw IllegalStateException("CharacteristicListener's nativeInstance not null, already in use", E_FILE_LINE);
                return false;
            }
        }
        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
        std::shared_ptr<GATTHandler> gatt = device->getGATTHandler();
        if( nullptr == gatt ) {
            throw IllegalStateException("Characteristic's device GATTHandle not connected: "+ device->toString(), E_FILE_LINE);
        }

        GATTCharacteristic * associatedCharacteristicRef = nullptr;
        if( nullptr != jAssociatedCharacteristic ) {
            associatedCharacteristicRef = getDBTObject<GATTCharacteristic>(env, jAssociatedCharacteristic);
        }

        std::shared_ptr<GATTCharacteristicListener> l =
                std::shared_ptr<GATTCharacteristicListener>( new JNICharacteristicListener(env, device, listener, associatedCharacteristicRef) );

        if( gatt->addCharacteristicListener(l) ) {
            setInstance(env, listener, l.get());
            return JNI_TRUE;
        }
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
    return JNI_FALSE;
}

jboolean Java_direct_1bt_tinyb_DBTDevice_removeCharacteristicListener(JNIEnv *env, jobject obj, jobject jlistener) {
    try {
        if( nullptr == jlistener ) {
            throw IllegalArgumentException("characteristicListener argument is null", E_FILE_LINE);
        }
        JNICharacteristicListener * pre =
                getObjectRef<JNICharacteristicListener>(env, jlistener, "nativeInstance");
        if( nullptr == pre ) {
            WARN_PRINT("characteristicListener's nativeInstance is null, not in use");
            return false;
        }
        setObjectRef<JNICharacteristicListener>(env, jlistener, nullptr, "nativeInstance");

        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
        std::shared_ptr<GATTHandler> gatt = device->getGATTHandler();
        if( nullptr == gatt ) {
            // OK to have GATTHandler being shutdown @ disable
            DBG_PRINT("Characteristic's device GATTHandle not connected: %s", device->toString().c_str());
            return false;
        }

        if( ! gatt->removeCharacteristicListener(pre) ) {
            WARN_PRINT("Failed to remove characteristicListener with nativeInstance: %p at %s", pre, device->toString().c_str());
            return false;
        }
        return true;
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
    return JNI_FALSE;
}

jint Java_direct_1bt_tinyb_DBTDevice_removeAllAssociatedCharacteristicListener(JNIEnv *env, jobject obj, jobject jAssociatedCharacteristic) {
    try {
        if( nullptr == jAssociatedCharacteristic ) {
            throw IllegalArgumentException("associatedCharacteristic argument is null", E_FILE_LINE);
        }
        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
        std::shared_ptr<GATTHandler> gatt = device->getGATTHandler();
        if( nullptr == gatt ) {
            // OK to have GATTHandler being shutdown @ disable
            DBG_PRINT("Characteristic's device GATTHandle not connected: %s", device->toString().c_str());
            return 0;
        }

        GATTCharacteristic * associatedCharacteristicRef = getDBTObject<GATTCharacteristic>(env, jAssociatedCharacteristic);
        JavaGlobalObj::check(associatedCharacteristicRef->getJavaObject(), E_FILE_LINE);

        return gatt->removeAllAssociatedCharacteristicListener(associatedCharacteristicRef);
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
    return 0;
}

jint Java_direct_1bt_tinyb_DBTDevice_removeAllCharacteristicListener(JNIEnv *env, jobject obj) {
    try {
        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
        std::shared_ptr<GATTHandler> gatt = device->getGATTHandler();
        if( nullptr == gatt ) {
            // OK to have GATTHandler being shutdown @ disable
            DBG_PRINT("Characteristic's device GATTHandle not connected: %s", device->toString().c_str());
            return 0;
        }
        return gatt->removeAllCharacteristicListener();
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
    return 0;
}

void Java_direct_1bt_tinyb_DBTDevice_deleteImpl(JNIEnv *env, jobject obj, jlong nativeInstance)
{
    (void)obj;
    try {
        DBTDevice *device = castInstance<DBTDevice>(nativeInstance);
        device->remove();
        // No delete: DBTDevice instance owned by DBTAdapter
        // However, device->remove() might issue destruction
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
}

jboolean Java_direct_1bt_tinyb_DBTDevice_disconnectImpl(JNIEnv *env, jobject obj)
{
    try {
        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
        return device->disconnect() ? JNI_TRUE : JNI_FALSE;
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
    return JNI_FALSE;
}

jboolean Java_direct_1bt_tinyb_DBTDevice_removeImpl(JNIEnv *env, jobject obj)
{
    try {
        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
        device->remove();
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
    return JNI_TRUE;
}

jboolean Java_direct_1bt_tinyb_DBTDevice_connectImpl__(JNIEnv *env, jobject obj)
{
    try {
        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
        bool res = device->connectDefault();
        return res ? JNI_TRUE : JNI_FALSE;
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
    return JNI_FALSE;
}

jboolean Java_direct_1bt_tinyb_DBTDevice_connectImpl__SSSSSS(JNIEnv *env, jobject obj,
                                                             jshort interval, jshort window,
                                                             jshort min_interval, jshort max_interval,
                                                             jshort latency, jshort timeout)
{
    try {
        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
        bool res;
        switch( device->addressType ) {
            case BDAddressType::BDADDR_LE_PUBLIC:
                /* fall through intended */
            case BDAddressType::BDADDR_LE_RANDOM:
                res = device->connectLE(interval, window, min_interval, max_interval, latency, timeout);
                break;
            default:
                res = device->connectDefault();
                break;
        }
        return res ? JNI_TRUE : JNI_FALSE;
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
    return JNI_FALSE;
}

//
// getter
//

static const std::string _serviceClazzCtorArgs("(JLdirect_bt/tinyb/DBTDevice;ZLjava/lang/String;SS)V");

jobject Java_direct_1bt_tinyb_DBTDevice_getServicesImpl(JNIEnv *env, jobject obj) {
    try {
        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);

        std::vector<GATTServiceRef> services = device->getGATTServices(); // implicit GATT connect and discovery if required incl GenericAccess retrieval
        if( services.size() > 0 ) {
            std::shared_ptr<GenericAccess> ga = device->getGATTGenericAccess();
            if( nullptr != ga ) {
                env->SetShortField(obj, getField(env, obj, "appearance", "S"), static_cast<jshort>(ga->appearance));
                java_exception_check_and_throw(env, E_FILE_LINE);
                DBG_PRINT("DBTDevice.getServices(): GenericAccess: %s", ga->toString().c_str());
            }
        } else {
            return nullptr;
        }

        // DBTGattService(final long nativeInstance, final DBTDevice device, final boolean isPrimary,
        //                final String type_uuid, final short handleStart, final short handleEnd)

        std::function<jobject(JNIEnv*, jclass, jmethodID, GATTService*)> ctor_service =
                [](JNIEnv *env, jclass clazz, jmethodID clazz_ctor, GATTService *service)->jobject {
                    // prepare adapter ctor
                    std::shared_ptr<DBTDevice> device = service->getDeviceChecked();
                    JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
                    jobject jdevice = JavaGlobalObj::GetObject(device->getJavaObject());
                    const jboolean isPrimary = service->isPrimary;
                    const jstring uuid = from_string_to_jstring(env,
                            directBTJNISettings.getUnifyUUID128Bit() ? service->type->toUUID128String() :
                                                                       service->type->toString());
                    java_exception_check_and_throw(env, E_FILE_LINE);

                    jobject jservice = env->NewObject(clazz, clazz_ctor, (jlong)service, jdevice, isPrimary,
                            uuid, service->startHandle, service->endHandle);
                    java_exception_check_and_throw(env, E_FILE_LINE);
                    JNIGlobalRef::check(jservice, E_FILE_LINE);
                    std::shared_ptr<JavaAnonObj> jServiceRef = service->getJavaObject();
                    JavaGlobalObj::check(jServiceRef, E_FILE_LINE);

                    return JavaGlobalObj::GetObject(jServiceRef);
                };
        return convert_vector_sharedptr_to_jarraylist<GATTService>(env, services, _serviceClazzCtorArgs.c_str(), ctor_service);
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
    return nullptr;
}

jboolean Java_direct_1bt_tinyb_DBTDevice_pingGATTImpl(JNIEnv *env, jobject obj)
{
    try {
        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);

        return device->pingGATT() ? JNI_TRUE : JNI_FALSE;
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
    return JNI_FALSE;
}

jstring Java_direct_1bt_tinyb_DBTDevice_getIcon(JNIEnv *env, jobject obj)
{
    try {
        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
        return nullptr; // FIXME
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
    return nullptr; // FIXME;
}

void Java_direct_1bt_tinyb_DBTDevice_setTrustedImpl(JNIEnv *env, jobject obj, jboolean value)
{
    try {
        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
        (void)value;
        // FIXME
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
}

void Java_direct_1bt_tinyb_DBTDevice_setBlockedImpl(JNIEnv *env, jobject obj, jboolean value)
{
    try {
        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
        (void)value;
        // FIXME
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
}

jboolean JNICALL Java_direct_1bt_tinyb_DBTDevice_getLegacyPairing(JNIEnv *env, jobject obj)
{
    try {
        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
        return JNI_FALSE; // FIXME
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
    return JNI_FALSE;
}

jshort Java_direct_1bt_tinyb_DBTDevice_getRSSI(JNIEnv *env, jobject obj)
{
    try {
        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
        return (jshort) device->getRSSI();
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
    return 0;
}


jobjectArray Java_direct_1bt_tinyb_DBTDevice_getUUIDs(JNIEnv *env, jobject obj)
{
    try {
        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
        return nullptr; // FIXME
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
    return nullptr;
}

jstring Java_direct_1bt_tinyb_DBTDevice_getModalias(JNIEnv *env, jobject obj)
{
    try {
        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
        return nullptr; // FIXME
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
    return nullptr;
}

jobject Java_direct_1bt_tinyb_DBTDevice_getManufacturerData(JNIEnv *env, jobject obj)
{
    try {
        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
        std::shared_ptr<ManufactureSpecificData> mdata = device->getManufactureSpecificData();

        jclass map_cls = search_class(env, "java/util/HashMap");
        jmethodID map_ctor = search_method(env, map_cls, "<init>", "(I)V", false);
        jmethodID map_put = search_method(env, map_cls, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", false);

        jclass short_cls = search_class(env, "java/lang/Short");
        jmethodID short_ctor = search_method(env, short_cls, "<init>", "(S)V", false);
        jobject result = nullptr;

        if( nullptr != mdata ) {
            result = env->NewObject(map_cls, map_ctor, 1);
            jbyteArray arr = env->NewByteArray(mdata->data.getSize());
            env->SetByteArrayRegion(arr, 0, mdata->data.getSize(), (const jbyte *)mdata->data.get_ptr());
            jobject key = env->NewObject(short_cls, short_ctor, mdata->company);
            env->CallObjectMethod(result, map_put, key, arr);

            env->DeleteLocalRef(arr);
            env->DeleteLocalRef(key);
        } else {
            result = env->NewObject(map_cls, map_ctor, 0);
        }
        if (nullptr == result) {
            throw std::bad_alloc();
        }
        return result;
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
    return nullptr;
}

jshort Java_direct_1bt_tinyb_DBTDevice_getTxPower(JNIEnv *env, jobject obj)
{
    try {
        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
        return (jshort) device->getTxPower();
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
    return 0;
}

//
// BooleanDeviceCBContext
//

struct BooleanDeviceCBContext {
    EUI48 deviceAddress;
    JNIGlobalRef javaCallback_ref;
    jmethodID  mRun;
    JNIGlobalRef boolean_cls_ref;
    jmethodID boolean_ctor;

    bool operator==(const BooleanDeviceCBContext& rhs) const
    {
        if( &rhs == this ) {
            return true;
        }
        return rhs.deviceAddress == deviceAddress &&
               rhs.javaCallback_ref == javaCallback_ref;
    }

    bool operator!=(const BooleanDeviceCBContext& rhs) const
    { return !( *this == rhs ); }

};
typedef std::shared_ptr<BooleanDeviceCBContext> BooleanDeviceCBContextRef;


//
// Blocked
//

static void disableBlockedNotifications(JNIEnv *env, jobject obj, DBTManager &mgmt)
{
    InvocationFunc<bool, std::shared_ptr<MgmtEvent>> * funcptr =
            getObjectRef<InvocationFunc<bool, std::shared_ptr<MgmtEvent>>>(env, obj, "blockedNotificationRef");
    if( nullptr != funcptr ) {
        FunctionDef<bool, std::shared_ptr<MgmtEvent>> funcDef( funcptr );
        funcptr = nullptr;
        setObjectRef(env, obj, funcptr, "blockedNotificationRef"); // clear java ref
        int count;
        if( 1 != ( count = mgmt.removeMgmtEventCallback(MgmtEvent::Opcode::DEVICE_BLOCKED, funcDef) ) ) {
            throw direct_bt::InternalError(std::string("removeMgmtEventCallback of ")+funcDef.toString()+" not 1 but "+std::to_string(count), E_FILE_LINE);
        }
        if( 1 != ( count = mgmt.removeMgmtEventCallback(MgmtEvent::Opcode::DEVICE_UNBLOCKED, funcDef) ) ) {
            throw direct_bt::InternalError(std::string("removeMgmtEventCallback of ")+funcDef.toString()+" not 1 but "+std::to_string(count), E_FILE_LINE);
        }
    }
}
void Java_direct_1bt_tinyb_DBTDevice_disableBlockedNotificationsImpl(JNIEnv *env, jobject obj)
{
    try {
        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
        DBTManager & mgmt = device->getAdapter().getManager();

        disableBlockedNotifications(env, obj, mgmt);
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
}
void Java_direct_1bt_tinyb_DBTDevice_enableBlockedNotificationsImpl(JNIEnv *env, jobject obj, jobject javaCallback)
{
    try {
        DBTDevice *device= getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
        DBTAdapter & adapter = device->getAdapter();
        DBTManager & mgmt = adapter.getManager();

        disableBlockedNotifications(env, obj, mgmt);

        bool(*nativeCallback)(BooleanDeviceCBContextRef&, std::shared_ptr<MgmtEvent>) =
                [](BooleanDeviceCBContextRef& ctx_ref, std::shared_ptr<MgmtEvent> e)->bool {
            bool isBlocked = false;
            if( MgmtEvent::Opcode::DEVICE_BLOCKED == e->getOpcode() ) {
                const MgmtEvtDeviceBlocked &event = *static_cast<const MgmtEvtDeviceBlocked *>(e.get());
                if( event.getAddress() != ctx_ref->deviceAddress ) {
                    return false; // not this device
                }
                isBlocked = true;
            } else if( MgmtEvent::Opcode::DEVICE_UNBLOCKED == e->getOpcode() ) {
                const MgmtEvtDeviceUnblocked &event = *static_cast<const MgmtEvtDeviceUnblocked *>(e.get());
                if( event.getAddress() != ctx_ref->deviceAddress ) {
                    return false; // not this device
                }
                isBlocked = false;
            } else {
                return false; // oops
            }

            jobject result = jni_env->NewObject(ctx_ref->boolean_cls_ref.getClass(), ctx_ref->boolean_ctor, isBlocked ? JNI_TRUE : JNI_FALSE);
            jni_env->CallVoidMethod(*(ctx_ref->javaCallback_ref), ctx_ref->mRun, result);
            jni_env->DeleteLocalRef(result);
            return true;
        };
        jclass notification = search_class(*jni_env, javaCallback);
        jmethodID  mRun = search_method(*jni_env, notification, "run", "(Ljava/lang/Object;)V", false);
        java_exception_check_and_throw(env, E_FILE_LINE);
        jni_env->DeleteLocalRef(notification);

        jclass boolean_cls = search_class(*jni_env, "java/lang/Boolean");
        jmethodID boolean_ctor = search_method(*jni_env, boolean_cls, "<init>", "(Z)V", false);
        java_exception_check_and_throw(env, E_FILE_LINE);

        BooleanDeviceCBContext * ctx = new BooleanDeviceCBContext{
            device->getAddress(), JNIGlobalRef(javaCallback), mRun, JNIGlobalRef(boolean_cls), boolean_ctor };
        jni_env->DeleteLocalRef(boolean_cls);

        // move BooleanDeviceCBContextRef into CaptureInvocationFunc and operator== includes javaCallback comparison
        FunctionDef<bool, std::shared_ptr<MgmtEvent>> funcDef = bindCaptureFunc(BooleanDeviceCBContextRef(ctx), nativeCallback);
        setObjectRef(env, obj, funcDef.cloneFunction(), "blockedNotificationRef"); // set java ref
        mgmt.addMgmtEventCallback(adapter.dev_id, MgmtEvent::Opcode::DEVICE_BLOCKED, funcDef);
        mgmt.addMgmtEventCallback(adapter.dev_id, MgmtEvent::Opcode::DEVICE_UNBLOCKED, funcDef);
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
}

//
// Paired
//

static void disablePairedNotifications(JNIEnv *env, jobject obj, DBTManager &mgmt)
{
    InvocationFunc<bool, std::shared_ptr<MgmtEvent>> * funcptr =
            getObjectRef<InvocationFunc<bool, std::shared_ptr<MgmtEvent>>>(env, obj, "pairedNotificationRef");
    if( nullptr != funcptr ) {
        FunctionDef<bool, std::shared_ptr<MgmtEvent>> funcDef( funcptr );
        funcptr = nullptr;
        setObjectRef(env, obj, funcptr, "pairedNotificationRef"); // clear java ref
        int count;
        if( 1 != ( count = mgmt.removeMgmtEventCallback(MgmtEvent::Opcode::DEVICE_UNPAIRED, funcDef) ) ) {
            throw direct_bt::InternalError(std::string("removeMgmtEventCallback of ")+funcDef.toString()+" not 1 but "+std::to_string(count), E_FILE_LINE);
        }
    }
}
void Java_direct_1bt_tinyb_DBTDevice_disablePairedNotificationsImpl(JNIEnv *env, jobject obj)
{
    try {
        DBTDevice *device = getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
        DBTManager & mgmt = device->getAdapter().getManager();

        disablePairedNotifications(env, obj, mgmt);
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
}
void Java_direct_1bt_tinyb_DBTDevice_enablePairedNotificationsImpl(JNIEnv *env, jobject obj, jobject javaCallback)
{
    try {
        DBTDevice *device= getDBTObject<DBTDevice>(env, obj);
        JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE);
        DBTAdapter & adapter = device->getAdapter();
        DBTManager & mgmt = adapter.getManager();

        disablePairedNotifications(env, obj, mgmt);

        bool(*nativeCallback)(BooleanDeviceCBContextRef&, std::shared_ptr<MgmtEvent>) =
                [](BooleanDeviceCBContextRef& ctx_ref, std::shared_ptr<MgmtEvent> e)->bool {
            const MgmtEvtDeviceUnpaired &event = *static_cast<const MgmtEvtDeviceUnpaired *>(e.get());
            if( event.getAddress() != ctx_ref->deviceAddress ) {
                return false; // not this device
            }
            jobject result = jni_env->NewObject(ctx_ref->boolean_cls_ref.getClass(), ctx_ref->boolean_ctor, JNI_FALSE);
            jni_env->CallVoidMethod(*(ctx_ref->javaCallback_ref), ctx_ref->mRun, result);
            jni_env->DeleteLocalRef(result);
            return true;
        };
        jclass notification = search_class(*jni_env, javaCallback);
        jmethodID  mRun = search_method(*jni_env, notification, "run", "(Ljava/lang/Object;)V", false);
        java_exception_check_and_throw(env, E_FILE_LINE);
        jni_env->DeleteLocalRef(notification);

        jclass boolean_cls = search_class(*jni_env, "java/lang/Boolean");
        jmethodID boolean_ctor = search_method(*jni_env, boolean_cls, "<init>", "(Z)V", false);
        java_exception_check_and_throw(env, E_FILE_LINE);

        BooleanDeviceCBContext * ctx = new BooleanDeviceCBContext{
            device->getAddress(), JNIGlobalRef(javaCallback), mRun, JNIGlobalRef(boolean_cls), boolean_ctor };
        jni_env->DeleteLocalRef(boolean_cls);

        // move BooleanDeviceCBContextRef into CaptureInvocationFunc and operator== includes javaCallback comparison
        FunctionDef<bool, std::shared_ptr<MgmtEvent>> funcDef = bindCaptureFunc(BooleanDeviceCBContextRef(ctx), nativeCallback);
        setObjectRef(env, obj, funcDef.cloneFunction(), "pairedNotificationRef"); // set java ref
        // FIXME: Figure out paired:=true, as currently we only attach to unpaired
        mgmt.addMgmtEventCallback(adapter.dev_id, MgmtEvent::Opcode::DEVICE_UNPAIRED, funcDef);
    } catch(...) {
        rethrow_and_raise_java_exception(env);
    }
}