aboutsummaryrefslogtreecommitdiffstats
path: root/src/direct_bt/DBTManager.cpp
blob: 5a49ef2ddfbe1c33bf6b976fc1d7479359176487 (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
/*
 * 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 <cstring>
#include <string>
#include <memory>
#include <cstdint>
#include <vector>
#include <cstdio>

#include <algorithm>

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

#include "BTIoctl.hpp"

#include "DBTManager.hpp"
#include "HCIIoctl.hpp"
#include "HCIComm.hpp"
#include "DBTTypes.hpp"

extern "C" {
    #include <inttypes.h>
    #include <unistd.h>
    #include <poll.h>
    #include <signal.h>
}

using namespace direct_bt;

void DBTManager::mgmtReaderThreadImpl() {
    mgmtReaderShallStop = false;
    mgmtReaderRunning = true;
    INFO_PRINT("DBTManager::reader: Started");

    while( !mgmtReaderShallStop ) {
        int len;
        if( !comm.isOpen() ) {
            // not open
            ERR_PRINT("DBTManager::reader: Not connected");
            mgmtReaderShallStop = true;
            break;
        }

        len = comm.read(rbuffer.get_wptr(), rbuffer.getSize());
        if( 0 < len ) {
            const uint16_t paramSize = len >= 6 ? rbuffer.get_uint16(4) : 0;
            if( len < 6 + paramSize ) {
                WARN_PRINT("DBTManager::reader: length mismatch %d < 6 + %d", len, paramSize);
                continue; // discard data
            }
            std::shared_ptr<MgmtEvent> event( MgmtEvent::getSpecialized(rbuffer.get_ptr(), len) );
            const MgmtEvent::Opcode opc = event->getOpcode();
            if( MgmtEvent::Opcode::CMD_COMPLETE == opc || MgmtEvent::Opcode::CMD_STATUS == opc ) {
                DBG_PRINT("DBTManager::reader: CmdResult %s", event->toString().c_str());
                mgmtEventRing.putBlocking( event );
            } else {
                // issue a callback
                MgmtEventCallbackList mgmtEventCallbackList = mgmtEventCallbackLists[opc];
                DBG_PRINT("DBTManager::reader: Event %s -> %zd callbacks", event->toString().c_str(), mgmtEventCallbackList.size());
                for (auto it = mgmtEventCallbackList.begin(); it != mgmtEventCallbackList.end(); ++it) {
                    MgmtEventCallback callback = *it;
                    callback.invoke(event);
                }
            }
        } else if( ETIMEDOUT != errno && !mgmtReaderShallStop ) { // expected exits
            ERR_PRINT("DBTManager::reader: HCIComm error");
        }
    }

    INFO_PRINT("DBTManager::reader: Ended");
    mgmtReaderRunning = false;
}

void DBTManager::sendMgmtEvent(std::shared_ptr<MgmtEvent> event) {
    const MgmtEvent::Opcode opc = event->getOpcode();
    MgmtEventCallbackList mgmtEventCallbackList = mgmtEventCallbackLists[opc];
    DBG_PRINT("DBTManager::sendMgmtEvent: Event %s -> %zd callbacks", event->toString().c_str(), mgmtEventCallbackList.size());
    for (auto it = mgmtEventCallbackList.begin(); it != mgmtEventCallbackList.end(); ++it) {
        MgmtEventCallback callback = *it;
        callback.invoke(event);
    }
}

static void mgmthandler_sigaction(int sig, siginfo_t *info, void *ucontext) {
    INFO_PRINT("DBTManager.sigaction: sig %d, info[code %d, errno %d, signo %d, pid %d, uid %d, fd %d]",
            sig, info->si_code, info->si_errno, info->si_signo,
            info->si_pid, info->si_uid, info->si_fd);
    (void)ucontext;

    if( SIGINT != sig ) {
        return;
    }
    {
        struct sigaction sa_setup;
        bzero(&sa_setup, sizeof(sa_setup));
        sa_setup.sa_handler = SIG_DFL;
        sigemptyset(&(sa_setup.sa_mask));
        sa_setup.sa_flags = 0;
        if( 0 != sigaction( SIGINT, &sa_setup, NULL ) ) {
            ERR_PRINT("DBTManager.sigaction: Resetting sighandler");
        }
    }
}

std::shared_ptr<MgmtEvent> DBTManager::send(MgmtCommand &req) {
    DBG_PRINT("DBTManager::send: Command %s", req.toString().c_str());
    {
        const std::lock_guard<std::recursive_mutex> lock(comm.mutex()); // RAII-style acquire and relinquish via destructor
        TROOctets & pdu = req.getPDU();
        if ( comm.write( pdu.get_ptr(), pdu.getSize() ) < 0 ) {
            ERR_PRINT("DBTManager::send: HCIComm error");
            return nullptr;
        }
    }
    // Ringbuffer read is thread safe
    std::shared_ptr<MgmtEvent> res = receiveNext();
    if( !res->validate(req) ) {
        WARN_PRINT("DBTManager::send: res mismatch: res %s; req %s", res->toString().c_str(), req.toString().c_str());
        return nullptr; // FIXME:: Shall we push back the event to wait for the right one?
    }
    return res;
}

std::shared_ptr<MgmtEvent> DBTManager::receiveNext() {
    return mgmtEventRing.getBlocking();
}

std::shared_ptr<AdapterInfo> DBTManager::initAdapter(const uint16_t dev_id, const BTMode btMode) {
    std::shared_ptr<AdapterInfo> adapterInfo = nullptr;
    MgmtCommand req0(MgmtOpcode::READ_INFO, dev_id);
    DBG_PRINT("DBTManager::initAdapter dev_id %d: req: %s", dev_id, req0.toString().c_str());
    {
        std::shared_ptr<MgmtEvent> res = send(req0);
        if( nullptr == res ) {
            goto fail;
        }
        DBG_PRINT("DBTManager::initAdapter dev_id %d: res: %s", dev_id, res->toString().c_str());
        if( MgmtEvent::Opcode::CMD_COMPLETE != res->getOpcode() || res->getTotalSize() < MgmtEvtAdapterInfo::getRequiredSize()) {
            ERR_PRINT("Insufficient data for adapter info: req %d, res %s", MgmtEvtAdapterInfo::getRequiredSize(), res->toString().c_str());
            goto fail;
        }
        adapterInfo = std::shared_ptr<AdapterInfo>( new AdapterInfo( *static_cast<MgmtEvtAdapterInfo*>(res.get()) ) );
        if( dev_id != adapterInfo->dev_id ) {
            throw InternalError("AdapterInfo dev_id="+std::to_string(adapterInfo->dev_id)+" != dev_id="+std::to_string(dev_id)+"]: "+adapterInfo->toString(), E_FILE_LINE);
        }
    }

    switch ( btMode ) {
        case BTMode::BT_MODE_DUAL:
            setMode(dev_id, MgmtOpcode::SET_SSP, 1);
            setMode(dev_id, MgmtOpcode::SET_BREDR, 1);
            setMode(dev_id, MgmtOpcode::SET_LE, 1);
            break;
        case BTMode::BT_MODE_BREDR:
            setMode(dev_id, MgmtOpcode::SET_SSP, 1);
            setMode(dev_id, MgmtOpcode::SET_BREDR, 1);
            setMode(dev_id, MgmtOpcode::SET_LE, 0);
            break;
        case BTMode::BT_MODE_LE:
            setMode(dev_id, MgmtOpcode::SET_SSP, 0);
            setMode(dev_id, MgmtOpcode::SET_BREDR, 0);
            setMode(dev_id, MgmtOpcode::SET_LE, 1);
            break;
    }

    setMode(dev_id, MgmtOpcode::SET_CONNECTABLE, 0);
    setMode(dev_id, MgmtOpcode::SET_FAST_CONNECTABLE, 0);
    setMode(dev_id, MgmtOpcode::SET_POWERED, 1);

fail:
    return adapterInfo;
}

void DBTManager::shutdownAdapter(const uint16_t dev_id) {
    setMode(dev_id, MgmtOpcode::SET_CONNECTABLE, 0);
    setMode(dev_id, MgmtOpcode::SET_FAST_CONNECTABLE, 0);
    setMode(dev_id, MgmtOpcode::SET_DISCOVERABLE, 0);
    setMode(dev_id, MgmtOpcode::SET_POWERED, 0);
}

DBTManager::DBTManager(const BTMode btMode)
:btMode(btMode), rbuffer(ClientMaxMTU), comm(HCI_DEV_NONE, HCI_CHANNEL_CONTROL, Defaults::MGMT_READER_THREAD_POLL_TIMEOUT),
 mgmtEventRing(MGMTEVT_RING_CAPACITY), mgmtReaderRunning(false), mgmtReaderShallStop(false)
{
    if( !comm.isOpen() ) {
        ERR_PRINT("DBTManager::open: Could not open mgmt control channel");
        return;
    }

    {
        struct sigaction sa_setup;
        bzero(&sa_setup, sizeof(sa_setup));
        sa_setup.sa_sigaction = mgmthandler_sigaction;
        sigemptyset(&(sa_setup.sa_mask));
        sa_setup.sa_flags = SA_SIGINFO;
        if( 0 != sigaction( SIGINT, &sa_setup, NULL ) ) {
            ERR_PRINT("DBTManager::open: Setting sighandler");
        }
    }
    mgmtReaderThread = std::thread(&DBTManager::mgmtReaderThreadImpl, this);

    PERF_TS_T0();

    bool ok = true;
    // Mandatory
    {
        MgmtCommand req0(MgmtOpcode::READ_VERSION, MgmtConstU16::INDEX_NONE);
        DBG_PRINT("DBTManager::open req: %s", req0.toString().c_str());
        std::shared_ptr<MgmtEvent> res = send(req0);
        if( nullptr == res ) {
            goto fail;
        }
        DBG_PRINT("DBTManager::open res: %s", res->toString().c_str());
        if( MgmtEvent::Opcode::CMD_COMPLETE != res->getOpcode() || res->getDataSize() < 3) {
            ERR_PRINT("Wrong version response: %s", res->toString().c_str());
            goto fail;
        }
        const uint8_t *data = res->getData();
        const uint8_t version = data[0];
        const uint16_t revision = get_uint16(data, 1, true /* littleEndian */);
        INFO_PRINT("Bluetooth version %d.%d", version, revision);
        if( version < 1 ) {
            ERR_PRINT("Bluetooth version >= 1.0 required")
            goto fail;
        }
    }
    // Optional
    {
        MgmtCommand req0(MgmtOpcode::READ_COMMANDS, MgmtConstU16::INDEX_NONE);
        DBG_PRINT("DBTManager::open req: %s", req0.toString().c_str());
        std::shared_ptr<MgmtEvent> res = send(req0);
        if( nullptr == res ) {
            goto next1;
        }
        DBG_PRINT("DBTManager::open res: %s", res->toString().c_str());
        if( MgmtEvent::Opcode::CMD_COMPLETE == res->getOpcode() && res->getDataSize() >= 4) {
            const uint8_t *data = res->getData();
            const uint16_t num_commands = get_uint16(data, 0, true /* littleEndian */);
            const uint16_t num_events = get_uint16(data, 2, true /* littleEndian */);
            INFO_PRINT("Bluetooth %d commands, %d events", num_commands, num_events);
#ifdef VERBOSE_ON
            const int expDataSize = 4 + num_commands * 2 + num_events * 2;
            if( res->getDataSize() >= expDataSize ) {
                for(int i=0; i< num_commands; i++) {
                    const MgmtOpcode op = static_cast<MgmtOpcode>( get_uint16(data, 4+i*2, true /* littleEndian */) );
                    DBG_PRINT("kernel op %d: %s", i, getMgmtOpcodeString(op).c_str());
                }
            }
#endif
        }
    }

next1:
    // Register to add/remove adapter optionally:
    // MgmtEvent::INDEX_ADDED, MgmtConst::INDEX_NONE;
    // MgmtEvent::INDEX_REMOVED, MgmtConst::INDEX_NONE;

    // Mandatory
    {
        MgmtCommand req0(MgmtOpcode::READ_INDEX_LIST, MgmtConstU16::INDEX_NONE);
        DBG_PRINT("DBTManager::open req: %s", req0.toString().c_str());
        std::shared_ptr<MgmtEvent> res = send(req0);
        if( nullptr == res ) {
            goto fail;
        }
        DBG_PRINT("DBTManager::open res: %s", res->toString().c_str());
        if( MgmtEvent::Opcode::CMD_COMPLETE != res->getOpcode() || res->getDataSize() < 2) {
            ERR_PRINT("Insufficient data for adapter index: res %s", res->toString().c_str());
            goto fail;
        }
        const uint8_t *data = res->getData();
        const uint16_t num_adapter = get_uint16(data, 0, true /* littleEndian */);
        INFO_PRINT("Bluetooth %d adapter", num_adapter);

        const int expDataSize = 2 + num_adapter * 2;
        if( res->getDataSize() < expDataSize ) {
            ERR_PRINT("Insufficient data for %d adapter indices: res %s", num_adapter, res->toString().c_str());
            goto fail;
        }
        adapterInfos.resize(num_adapter, nullptr);
        for(int i=0; ok && i < num_adapter; i++) {
            const uint16_t dev_id = get_uint16(data, 2+i*2, true /* littleEndian */);
            if( dev_id >= num_adapter ) {
                throw InternalError("dev_id "+std::to_string(dev_id)+" >= num_adapter "+std::to_string(num_adapter), E_FILE_LINE);
            }
            if( adapterInfos[dev_id] != nullptr ) {
                throw InternalError("adapters[dev_id="+std::to_string(dev_id)+"] != nullptr: "+adapterInfos[dev_id]->toString(), E_FILE_LINE);
            }
            std::shared_ptr<AdapterInfo> adapterInfo = initAdapter(dev_id, btMode);
            adapterInfos[dev_id] = adapterInfo;
            if( nullptr != adapterInfo ) {
                DBG_PRINT("DBTManager::adapters %d/%d: dev_id %d: %s", i, num_adapter, dev_id, adapterInfo->toString().c_str());
                ok = true;
            } else {
                DBG_PRINT("DBTManager::adapters %d/%d: dev_id %d: FAILED", i, num_adapter, dev_id);
                ok = false;
            }
        }
    }

    if( ok ) {
        addMgmtEventCallback(MgmtEvent::Opcode::CLASS_OF_DEV_CHANGED, bindClassFunction(this, &DBTManager::mgmtEvClassOfDeviceChangedCB));
        addMgmtEventCallback(MgmtEvent::Opcode::LOCAL_NAME_CHANGED, bindClassFunction(this, &DBTManager::mgmtEvLocalNameChangedCB));
        addMgmtEventCallback(MgmtEvent::Opcode::DISCOVERING, bindClassFunction(this, &DBTManager::mgmtEvDeviceDiscoveringCB));
        addMgmtEventCallback(MgmtEvent::Opcode::NEW_SETTINGS, bindClassFunction(this, &DBTManager::mgmtEvNewSettingsCB));
        addMgmtEventCallback(MgmtEvent::Opcode::DEVICE_FOUND, bindClassFunction(this, &DBTManager::mgmtEvDeviceFoundCB));
        addMgmtEventCallback(MgmtEvent::Opcode::DEVICE_DISCONNECTED, bindClassFunction(this, &DBTManager::mgmtEvDeviceDisconnectedCB));
        addMgmtEventCallback(MgmtEvent::Opcode::DEVICE_CONNECTED, bindClassFunction(this, &DBTManager::mgmtEvDeviceConnectedCB));
        addMgmtEventCallback(MgmtEvent::Opcode::CONNECT_FAILED, bindClassFunction(this, &DBTManager::mgmtEvConnectFailedCB));
        addMgmtEventCallback(MgmtEvent::Opcode::PIN_CODE_REQUEST, bindClassFunction(this, &DBTManager::mgmtEvDevicePinCodeRequestCB));
        addMgmtEventCallback(MgmtEvent::Opcode::DEVICE_UNPAIRED, bindClassFunction(this, &DBTManager::mgmtEvDeviceUnpairedCB));
        addMgmtEventCallback(MgmtEvent::Opcode::NEW_CONN_PARAM, bindClassFunction(this, &DBTManager::mgmtEvNewConnectionParamCB));
        addMgmtEventCallback(MgmtEvent::Opcode::DEVICE_WHITELIST_ADDED, bindClassFunction(this, &DBTManager::mgmtEvDeviceWhitelistAddedCB));
        addMgmtEventCallback(MgmtEvent::Opcode::DEVICE_WHITELIST_REMOVED, bindClassFunction(this, &DBTManager::mgmtEvDeviceWhilelistRemovedCB));
        PERF_TS_TD("DBTManager::open.ok");
        return;
    }

fail:
    close();
    PERF_TS_TD("DBTManager::open.fail");
    return;
}

void DBTManager::close() {
    DBG_PRINT("DBTManager::close: Start");
    clearAllMgmtEventCallbacks();
    if( mgmtReaderRunning && mgmtReaderThread.joinable() ) {
        mgmtReaderShallStop = true;
        pthread_t tid = mgmtReaderThread.native_handle();
        pthread_kill(tid, SIGINT);
    }

    for (auto it = adapterInfos.begin(); it != adapterInfos.end(); ) {
        shutdownAdapter((*it)->dev_id);
    }
    comm.close();

    if( mgmtReaderRunning && mgmtReaderThread.joinable() ) {
        // still running ..
        DBG_PRINT("DBTManager::close: join mgmtReaderThread");
        mgmtReaderThread.join();
    }
    mgmtReaderThread = std::thread(); // empty
    DBG_PRINT("DBTManager::close: End");
}

int DBTManager::findAdapterInfoIdx(const EUI48 &mac) const {
    auto begin = adapterInfos.begin();
    auto it = std::find_if(begin, adapterInfos.end(), [&](std::shared_ptr<AdapterInfo> const& p) {
        return p->address == mac;
    });
    if ( it == std::end(adapterInfos) ) {
        return -1;
    } else {
        return std::distance(begin, it);
    }
}
std::shared_ptr<AdapterInfo> DBTManager::findAdapterInfo(const EUI48 &mac) const {
    auto begin = adapterInfos.begin();
    auto it = std::find_if(begin, adapterInfos.end(), [&](std::shared_ptr<AdapterInfo> const& p) {
        return p->address == mac;
    });
    if ( it == std::end(adapterInfos) ) {
        return nullptr;
    } else {
        return *it;
    }
}
std::shared_ptr<AdapterInfo> DBTManager::getAdapterInfo(const int idx) const {
    if( 0 > idx || idx >= static_cast<int>(adapterInfos.size()) ) {
        throw IndexOutOfBoundsException(idx, adapterInfos.size(), 1, E_FILE_LINE);
    }
    std::shared_ptr<AdapterInfo> adapter = adapterInfos.at(idx);
    return adapter;
}

bool DBTManager::setMode(const int dev_id, const MgmtOpcode opc, const uint8_t mode) {
    MgmtUint8Cmd req(opc, dev_id, mode);
    DBG_PRINT("DBTManager::setMode: %s", req.toString().c_str());
    std::shared_ptr<MgmtEvent> res = send(req);
    if( nullptr != res ) {
        DBG_PRINT("DBTManager::setMode res: %s", res->toString().c_str());
        return true;
    } else {
        DBG_PRINT("DBTManager::setMode res: NULL");
        return false;
    }
}

ScanType DBTManager::startDiscovery(const int dev_id) {
    ScanType scanType;
    switch ( btMode ) {
        case BTMode::BT_MODE_DUAL:
            scanType = ScanType::SCAN_TYPE_DUAL;
            break;
        case BTMode::BT_MODE_BREDR:
            scanType = ScanType::SCAN_TYPE_BREDR;
            break;
        case BTMode::BT_MODE_LE:
            scanType = ScanType::SCAN_TYPE_LE;
            break;
    }
    return startDiscovery(dev_id, scanType);
}

ScanType DBTManager::startDiscovery(const int dev_id, const ScanType scanType) {
    MgmtUint8Cmd req(MgmtOpcode::START_DISCOVERY, dev_id, scanType);
    DBG_PRINT("DBTManager::startDiscovery: %s", req.toString().c_str());
    std::shared_ptr<MgmtEvent> res = send(req);
    if( nullptr == res ) {
        DBG_PRINT("DBTManager::startDiscovery res: NULL");
        return ScanType::SCAN_TYPE_NONE;
    }
    DBG_PRINT("DBTManager::startDiscovery res: %s", res->toString().c_str());
    ScanType type = ScanType::SCAN_TYPE_NONE;
    if( res->getOpcode() == MgmtEvent::Opcode::CMD_COMPLETE ) {
        const MgmtEvtCmdComplete &res1 = *static_cast<const MgmtEvtCmdComplete *>(res.get());
        if( MgmtStatus::SUCCESS == res1.getStatus() && 1 == res1.getDataSize() ) {
            type = static_cast<ScanType>( *res1.getData() );
            DBG_PRINT("DBTManager::startDiscovery res: ScanType %d", (int)type);
        } else {
            DBG_PRINT("DBTManager::startDiscovery no-success or invalid res: %s", res1.toString().c_str());
        }
    } else {
        DBG_PRINT("DBTManager::startDiscovery res: NULL");
    }
    return type;
}
bool DBTManager::stopDiscovery(const int dev_id, const ScanType type) {
    MgmtUint8Cmd req(MgmtOpcode::STOP_DISCOVERY, dev_id, type);
    DBG_PRINT("DBTManager::stopDiscovery: %s", req.toString().c_str());
    std::shared_ptr<MgmtEvent> res = send(req);
    if( nullptr == res ) {
        DBG_PRINT("DBTManager::stopDiscovery res: NULL");
        return false;
    }
    DBG_PRINT("DBTManager::stopDiscovery res: %s", res->toString().c_str());
    if( res->getOpcode() == MgmtEvent::Opcode::CMD_COMPLETE ) {
        const MgmtEvtCmdComplete &res1 = *static_cast<const MgmtEvtCmdComplete *>(res.get());
        return MgmtStatus::SUCCESS == res1.getStatus();
    } else {
        DBG_PRINT("DBTManager::stopDiscovery res: NULL");
        return false;
    }
}

uint16_t DBTManager::create_connection(const int dev_id,
                        const EUI48 &peer_bdaddr,
                        const BDAddressType peer_mac_type,
                        const BDAddressType own_mac_type,
                        const uint16_t interval, const uint16_t window,
                        const uint16_t min_interval, const uint16_t max_interval,
                        const uint16_t latency, const uint16_t supervision_timeout,
                        const uint16_t min_ce_length, const uint16_t max_ce_length,
                        const uint8_t initiator_filter) {
    // MgmtUint8Cmd req(MgmtOpcode::, dev_id, scanType);
    DBG_PRINT("DBTManager::le_create_conn: %s", peer_bdaddr.toString().c_str());
    (void)dev_id;
    (void)peer_mac_type;
    (void)own_mac_type;
    (void)interval;
    (void)window;
    (void)min_interval;
    (void)max_interval;
    (void)latency;
    (void)supervision_timeout;
    (void)min_ce_length;
    (void)max_ce_length;
    (void)initiator_filter;
    return 0;
}

bool DBTManager::disconnect(const int dev_id, const EUI48 &peer_bdaddr, const BDAddressType peer_mac_type, const uint8_t reason) {
    MgmtDisconnectCmd req(dev_id, peer_bdaddr, peer_mac_type);
    DBG_PRINT("DBTManager::disconnect: %s", req.toString().c_str());
    std::shared_ptr<MgmtEvent> res = send(req);
    if( nullptr == res ) {
        DBG_PRINT("DBTManager::stopDiscovery res: NULL");
        return false;
    }
    DBG_PRINT("DBTManager::disconnect res: %s", res->toString().c_str());
    if( res->getOpcode() == MgmtEvent::Opcode::CMD_COMPLETE ) {
        const MgmtEvtCmdComplete &res1 = *static_cast<const MgmtEvtCmdComplete *>(res.get());
        if( MgmtStatus::SUCCESS == res1.getStatus() ) {
            // explicit disconnected event
            MgmtEvtDeviceDisconnected *e = new MgmtEvtDeviceDisconnected(dev_id, peer_bdaddr, peer_mac_type, reason);
            sendMgmtEvent(std::shared_ptr<MgmtEvent>(e));
            return true;
        }
    } else {
        DBG_PRINT("DBTManager::disconnect res: NULL");
        return false;
    }
}

/***
 *
 * MgmtEventCallback section
 *
 */

void DBTManager::addMgmtEventCallback(const MgmtEvent::Opcode opc, const MgmtEventCallback &cb) {
    const std::lock_guard<std::recursive_mutex> lock(mtx_callbackLists); // RAII-style acquire and relinquish via destructor
    checkMgmtEventCallbackListsIndex(opc);
    mgmtEventCallbackLists[opc].push_back(cb);
}
int DBTManager::removeMgmtEventCallback(const MgmtEvent::Opcode opc, const MgmtEventCallback &cb) {
    const std::lock_guard<std::recursive_mutex> lock(mtx_callbackLists); // RAII-style acquire and relinquish via destructor
    checkMgmtEventCallbackListsIndex(opc);
    int count = 0;
    MgmtEventCallbackList &l = mgmtEventCallbackLists[opc];
    for (auto it = l.begin(); it != l.end(); ) {
        if ( *it == cb ) {
            it = l.erase(it);
            count++;
        } else {
            ++it;
        }
    }
    return count;
}
void DBTManager::clearMgmtEventCallbacks(const MgmtEvent::Opcode opc) {
    const std::lock_guard<std::recursive_mutex> lock(mtx_callbackLists); // RAII-style acquire and relinquish via destructor
    checkMgmtEventCallbackListsIndex(opc);
    mgmtEventCallbackLists[opc].clear();
}
void DBTManager::clearAllMgmtEventCallbacks() {
    const std::lock_guard<std::recursive_mutex> lock(mtx_callbackLists); // RAII-style acquire and relinquish via destructor
    for(size_t i=0; i<mgmtEventCallbackLists.size(); i++) {
        mgmtEventCallbackLists[i].clear();
    }
}

bool DBTManager::mgmtEvClassOfDeviceChangedCB(std::shared_ptr<MgmtEvent> e) {
    DBG_PRINT("DBRManager::EventCB:ClassOfDeviceChanged: %s", e->toString().c_str());
    return true;
}
bool DBTManager::mgmtEvLocalNameChangedCB(std::shared_ptr<MgmtEvent> e) {
    DBG_PRINT("DBRManager::EventCB:LocalNameChanged: %s", e->toString().c_str());
    const MgmtEvtLocalNameChanged &event = *static_cast<const MgmtEvtLocalNameChanged *>(e.get());
    std::shared_ptr<AdapterInfo> adapterInfo = getAdapterInfo(event.getDevID());
    std::string old_name = adapterInfo->getName();
    std::string old_shortName = adapterInfo->getShortName();
    bool nameChanged = old_name != event.getName();
    bool shortNameChanged = old_shortName != event.getShortName();
    if( nameChanged ) {
        adapterInfo->setName(event.getName());
    }
    if( shortNameChanged ) {
        adapterInfo->setShortName(event.getShortName());
    }
    DBG_PRINT("DBRManager::EventCB:LocalNameChanged: Name: %d: '%s' -> '%s'; ShortName: %d: '%s' -> '%s'",
            nameChanged, old_name.c_str(), adapterInfo->getName().c_str(),
            shortNameChanged, old_shortName.c_str(), adapterInfo->getShortName().c_str());
    (void)nameChanged;
    (void)shortNameChanged;
    return true;
}
bool DBTManager::mgmtEvDeviceDiscoveringCB(std::shared_ptr<MgmtEvent> e) {
    DBG_PRINT("DBRManager::EventCB:DeviceDiscovering: %s", e->toString().c_str());
    const MgmtEvtDiscovering &event = *static_cast<const MgmtEvtDiscovering *>(e.get());
    (void)event;
    return true;
}
bool DBTManager::mgmtEvNewSettingsCB(std::shared_ptr<MgmtEvent> e) {
    DBG_PRINT("DBRManager::EventCB:NewSettings: %s", e->toString().c_str());
    const MgmtEvtNewSettings &event = *static_cast<const MgmtEvtNewSettings *>(e.get());
    std::shared_ptr<AdapterInfo> adapterInfo = getAdapterInfo(event.getDevID());
    MgmtSetting old_setting = adapterInfo->getCurrentSetting();
    int res = adapterInfo->setCurrentSetting(event.getSettings());
    DBG_PRINT("DBRManager::EventCB:NewSettings: %d: %s -> %s", res,
            getMgmtSettingsString(old_setting).c_str(),
            getMgmtSettingsString(adapterInfo->getCurrentSetting()).c_str());
    (void)res;
    return true;
}
bool DBTManager::mgmtEvDeviceFoundCB(std::shared_ptr<MgmtEvent> e) {
    DBG_PRINT("DBRManager::EventCB:DeviceFound: %s", e->toString().c_str());
    const MgmtEvtDeviceFound &event = *static_cast<const MgmtEvtDeviceFound *>(e.get());
    (void)event;
    return true;
}
bool DBTManager::mgmtEvDeviceDisconnectedCB(std::shared_ptr<MgmtEvent> e) {
    DBG_PRINT("DBRManager::EventCB:DeviceDisconnected: %s", e->toString().c_str());
    const MgmtEvtDeviceDisconnected &event = *static_cast<const MgmtEvtDeviceDisconnected *>(e.get());
    (void)event;
    return true;
}
bool DBTManager::mgmtEvDeviceConnectedCB(std::shared_ptr<MgmtEvent> e) {
    DBG_PRINT("DBRManager::EventCB:DeviceConnected: %s", e->toString().c_str());
    const MgmtEvtDeviceConnected &event = *static_cast<const MgmtEvtDeviceConnected *>(e.get());
    (void)event;
    return true;
}
bool DBTManager::mgmtEvConnectFailedCB(std::shared_ptr<MgmtEvent> e) {
    DBG_PRINT("DBRManager::EventCB:ConnectFailed: %s", e->toString().c_str());
    const MgmtEvtDeviceConnectFailed &event = *static_cast<const MgmtEvtDeviceConnectFailed *>(e.get());
    (void)event;
    return true;
}
bool DBTManager::mgmtEvDevicePinCodeRequestCB(std::shared_ptr<MgmtEvent> e) {
    DBG_PRINT("DBRManager::EventCB:PinCodeRequest: %s", e->toString().c_str());
    const MgmtEvtPinCodeRequest &event = *static_cast<const MgmtEvtPinCodeRequest *>(e.get());
    (void)event;
    return true;
}
bool DBTManager::mgmtEvDeviceUnpairedCB(std::shared_ptr<MgmtEvent> e) {
    DBG_PRINT("DBRManager::EventCB:DeviceUnpaired: %s", e->toString().c_str());
    const MgmtEvtDeviceUnpaired &event = *static_cast<const MgmtEvtDeviceUnpaired *>(e.get());
    (void)event;
    return true;
}
bool DBTManager::mgmtEvNewConnectionParamCB(std::shared_ptr<MgmtEvent> e) {
    DBG_PRINT("DBRManager::EventCB:NewConnectionParam: %s", e->toString().c_str());
    const MgmtEvtNewConnectionParam &event = *static_cast<const MgmtEvtNewConnectionParam *>(e.get());
    (void)event;
    return true;
}
bool DBTManager::mgmtEvDeviceWhitelistAddedCB(std::shared_ptr<MgmtEvent> e) {
    DBG_PRINT("DBRManager::EventCB:DeviceAdded: %s", e->toString().c_str());
    const MgmtEvtDeviceWhitelistAdded &event = *static_cast<const MgmtEvtDeviceWhitelistAdded *>(e.get());
    (void)event;
    return true;
}
bool DBTManager::mgmtEvDeviceWhilelistRemovedCB(std::shared_ptr<MgmtEvent> e) {
    DBG_PRINT("DBRManager::EventCB:DeviceRemoved: %s", e->toString().c_str());
    const MgmtEvtDeviceWhitelistRemoved &event = *static_cast<const MgmtEvtDeviceWhitelistRemoved *>(e.get());
    (void)event;
    return true;
}