summaryrefslogtreecommitdiffstats
path: root/examples/direct_bt_scanner/dbt_scanner.cpp
blob: ee84e8c8750bc994a4778c94ed0de61698f2980a (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
/*
 * 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/BTAddress.hpp>
#include <direct_bt/ATTPDUTypes.hpp>
#include <direct_bt/GATTHandler.hpp>
#include <direct_bt/GATTNumbers.hpp>
#include <direct_bt/DBTTypes.hpp>
#include <cinttypes>

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

using namespace direct_bt;

std::shared_ptr<direct_bt::DBTDevice> deviceFound = nullptr;
std::mutex mtxDeviceFound;
std::condition_variable cvDeviceFound;

class AdapterStatusListener : public direct_bt::DBTAdapterStatusListener {
    void adapterSettingsChanged(DBTAdapter const &a, const AdapterSetting oldmask, const AdapterSetting newmask,
                                const AdapterSetting changedmask, const uint64_t timestamp) override {
        fprintf(stderr, "****** Native Adapter SETTINGS_CHANGED: %s -> %s, changed %s\n",
                adapterSettingsToString(oldmask).c_str(),
                adapterSettingsToString(newmask).c_str(),
                adapterSettingsToString(changedmask).c_str());
        fprintf(stderr, "Status DBTAdapter:\n");
        fprintf(stderr, "%s\n", a.toString().c_str());
        (void)timestamp;
    }

    void deviceFound(direct_bt::DBTAdapter const &a, std::shared_ptr<direct_bt::DBTDevice> device, const uint64_t timestamp) override {
        fprintf(stderr, "****** FOUND__: %s\n", device->toString().c_str());
        fprintf(stderr, "Status Adapter:\n");
        fprintf(stderr, "%s\n", a.toString().c_str());
        {
            std::unique_lock<std::mutex> lockRead(mtxDeviceFound); // RAII-style acquire and relinquish via destructor
            ::deviceFound = device;
            cvDeviceFound.notify_all(); // notify waiting getter
        }
        (void)timestamp;
    }
    void deviceUpdated(direct_bt::DBTAdapter const &a, std::shared_ptr<direct_bt::DBTDevice> device, const uint64_t timestamp, const EIRDataType updateMask) override {
        fprintf(stderr, "****** UPDATED: %s of %s\n", direct_bt::eirDataMaskToString(updateMask).c_str(), device->toString().c_str());
        fprintf(stderr, "Status Adapter:\n");
        fprintf(stderr, "%s\n", a.toString().c_str());
        (void)timestamp;
    }
    void deviceConnected(direct_bt::DBTAdapter const &a, std::shared_ptr<direct_bt::DBTDevice> device, const uint64_t timestamp) override {
        fprintf(stderr, "****** CONNECTED: %s\n", device->toString().c_str());
        fprintf(stderr, "Status Adapter:\n");
        fprintf(stderr, "%s\n", a.toString().c_str());
        (void)timestamp;
    }
    void deviceDisconnected(direct_bt::DBTAdapter const &a, std::shared_ptr<direct_bt::DBTDevice> device, const uint64_t timestamp) override {
        fprintf(stderr, "****** DISCONNECTED: %s\n", device->toString().c_str());
        fprintf(stderr, "Status Adapter:\n");
        fprintf(stderr, "%s\n", a.toString().c_str());
        (void)timestamp;
    }
};

static const uuid16_t _TEMPERATURE_MEASUREMENT(GattCharacteristicType::TEMPERATURE_MEASUREMENT);

class MyGATTNotificationListener : public direct_bt::GATTNotificationListener {
    void notificationReceived(std::shared_ptr<DBTDevice> dev,
                              GATTCharacterisicsDeclRef charDecl, std::shared_ptr<const AttHandleValueRcv> charValue) override {
        const int64_t tR = direct_bt::getCurrentMilliseconds();
        fprintf(stderr, "****** GATT Notify (td %" PRIu64 " ms, dev-discovered %" PRIu64 " ms): From %s\n",
                (tR-charValue->ts_creation), (tR-dev->ts_creation), dev->toString().c_str());
        if( nullptr != charDecl ) {
            fprintf(stderr, "****** decl %s\n", charDecl->toString().c_str());
        }
        fprintf(stderr, "****** rawv %s\n", charValue->toString().c_str());
    }
};
class MyGATTIndicationListener : public direct_bt::GATTIndicationListener {
    void indicationReceived(std::shared_ptr<DBTDevice> dev,
                            GATTCharacterisicsDeclRef charDecl, std::shared_ptr<const AttHandleValueRcv> charValue,
                            const bool confirmationSent) override
    {
        const int64_t tR = direct_bt::getCurrentMilliseconds();
        fprintf(stderr, "****** GATT Indication (confirmed %d, td(msg %" PRIu64 " ms, dev-discovered %" PRIu64 " ms): From %s\n",
                confirmationSent, (tR-charValue->ts_creation), (tR-dev->ts_creation), dev->toString().c_str());
        if( nullptr != charDecl ) {
            fprintf(stderr, "****** decl %s\n", charDecl->toString().c_str());
            if( _TEMPERATURE_MEASUREMENT == *charDecl->uuid ) {
                std::shared_ptr<TemperatureMeasurementCharateristic> temp = TemperatureMeasurementCharateristic::get(charValue->getValue());
                if( nullptr != temp ) {
                    fprintf(stderr, "****** valu %s\n", temp->toString().c_str());
                }
            }
        }
        fprintf(stderr, "****** rawv %s\n", charValue->toString().c_str());
    }
};

// #define SCAN_CHARACTERISTIC_DESCRIPTORS 1
// #define SHOW_STATIC_SERVICE_CHARACTERISTIC_COMPOSITION 1

int main(int argc, char *argv[])
{
    bool ok = true, foundDevice=false;
    int dev_id = 0; // default
    bool waitForEnter=false;
    EUI48 waitForDevice = EUI48_ANY_DEVICE;
    bool forever = false;

    /**
     * BT Core Spec v5.2:  Vol 3, Part A L2CAP Spec: 7.9 PRIORITIZING DATA OVER HCI
     *
     * In order for guaranteed channels to meet their guarantees,
     * L2CAP should prioritize traffic over the HCI transport in devices that support HCI.
     * Packets for Guaranteed channels should receive higher priority than packets for Best Effort channels.
     * ...
     * I have noticed that w/o HCI le_connect, overall communication takes twice as long!!!
     */
    bool doHCI_Connect = true;

    for(int i=1; i<argc; i++) {
        if( !strcmp("-wait", argv[i]) ) {
            waitForEnter = true;
        } else if( !strcmp("-forever", argv[i]) ) {
            forever = true;
        } else if( !strcmp("-dev_id", argv[i]) && argc > (i+1) ) {
            dev_id = atoi(argv[++i]);
        } else if( !strcmp("-skipConnect", argv[i]) ) {
            doHCI_Connect = false;
        } else if( !strcmp("-mac", argv[i]) && argc > (i+1) ) {
            std::string macstr = std::string(argv[++i]);
            waitForDevice = EUI48(macstr);
        }
    }
    fprintf(stderr, "dev_id %d\n", dev_id);
    fprintf(stderr, "doHCI_Connect %d\n", doHCI_Connect);
    fprintf(stderr, "waitForDevice: %s\n", waitForDevice.toString().c_str());

    if( waitForEnter ) {
        fprintf(stderr, "Press ENTER to continue\n");
        getchar();
    }

    direct_bt::DBTAdapter adapter(dev_id);
    if( !adapter.hasDevId() ) {
        fprintf(stderr, "Default adapter not available.\n");
        exit(1);
    }
    if( !adapter.isValid() ) {
        fprintf(stderr, "Adapter invalid.\n");
        exit(1);
    }
    fprintf(stderr, "Using adapter: device %s, address %s: %s\n",
        adapter.getName().c_str(), adapter.getAddressString().c_str(), adapter.toString().c_str());

    adapter.addStatusListener(std::shared_ptr<direct_bt::DBTAdapterStatusListener>(new AdapterStatusListener()));

    const int64_t t0 = direct_bt::getCurrentMilliseconds();

    std::shared_ptr<direct_bt::HCISession> session = adapter.open();

    while( ok && ( forever || !foundDevice ) && nullptr != session ) {
        ok = adapter.startDiscovery();
        if( !ok) {
            perror("Adapter start discovery failed");
            goto out;
        }

        std::shared_ptr<direct_bt::DBTDevice> device = nullptr;
        {
            std::unique_lock<std::mutex> lockRead(mtxDeviceFound); // RAII-style acquire and relinquish via destructor
            while( nullptr == device ) { // FIXME deadlock, waiting forever!
                cvDeviceFound.wait(lockRead);
                if( nullptr != deviceFound ) {
                    foundDevice = deviceFound->getAddress() == waitForDevice; // match
                    if( foundDevice || ( EUI48_ANY_DEVICE == waitForDevice && deviceFound->isLEAddressType() ) ) {
                        // match or any LE device
                        device.swap(deviceFound); // take over deviceFound
                    }
                }
            }
        }
        adapter.stopDiscovery();

        if( ok && nullptr != device ) {
            const uint64_t t1 = direct_bt::getCurrentMilliseconds();

            //
            // HCI LE-Connect
            // (Without: Overall communication takes ~twice as long!!!)
            //
            uint16_t hciConnHandle;
            if( doHCI_Connect ) {
                hciConnHandle = device->defaultConnect();
                if( 0 == hciConnHandle ) {
                    fprintf(stderr, "Connect: Failed %s\n", device->toString().c_str());
                } else {
                    fprintf(stderr, "Connect: Success\n");
                }
            } else {
                fprintf(stderr, "Connect: Skipped %s\n", device->toString().c_str());
                hciConnHandle = 0;
            }
            const uint64_t t3 = direct_bt::getCurrentMilliseconds();
            const uint64_t td03 = t3 - t0;
            const uint64_t td13 = t3 - t1;
            const uint64_t td01 = t1 - t0;
            fprintf(stderr, "  discovery-only %" PRIu64 " ms,\n"
                            "  connect-only %" PRIu64 " ms,\n"
                            "  discovered to hci-connected %" PRIu64 " ms,\n"
                            "  total %" PRIu64 " ms,\n"
                            "  handle 0x%X\n",
                            td01, td13, (t3 - device->getCreationTimestamp()), td03, hciConnHandle);

            //
            // GATT Processing
            //
            const uint64_t t4 = direct_bt::getCurrentMilliseconds();
            // let's check further for full GATT
            std::shared_ptr<direct_bt::GATTHandler> gatt = device->connectGATT(GATTHandler::Defaults::L2CAP_READER_THREAD_POLL_TIMEOUT);
            if( nullptr != gatt ) {
                fprintf(stderr, "GATT usedMTU %d (server) -> %d (used)\n", gatt->getServerMTU(), gatt->getUsedMTU());

                gatt->setGATTIndicationListener(std::shared_ptr<GATTIndicationListener>(new MyGATTIndicationListener()), true /* sendConfirmation */);
                gatt->setGATTNotificationListener(std::shared_ptr<GATTNotificationListener>(new MyGATTNotificationListener()));

#ifdef SCAN_CHARACTERISTIC_DESCRIPTORS                         
                std::vector<std::vector<GATTUUIDHandle>> servicesCharacteristicDescriptors;
#endif                        
                std::vector<GATTPrimaryServiceRef> & primServices = gatt->discoverCompletePrimaryServices();
                const uint64_t t5 = direct_bt::getCurrentMilliseconds();
#ifdef SCAN_CHARACTERISTIC_DESCRIPTORS                        
                for(size_t i=0; i<primServices.size(); i++) {
                    std::vector<GATTUUIDHandle> serviceDescriptors;
                    gatt.discoverCharDescriptors(primServices.at(i), serviceDescriptors);
                    servicesCharacteristicDescriptors.push_back(serviceDescriptors);
                }
#endif                        
                const uint64_t t7 = direct_bt::getCurrentMilliseconds();
                {
                    const uint64_t td45 = t5 - t4; // connect -> complete primary services
                    const uint64_t td47 = t7 - t4; // connect -> gatt complete
                    const uint64_t td07 = t7 - t0; // total
                    fprintf(stderr, "\n\n\n");
                    fprintf(stderr, "GATT primary-services completed\n");
                    fprintf(stderr, "  gatt connect -> complete primary-services %" PRIu64 " ms,\n"
                                    "  gatt connect -> gatt complete %" PRIu64 " ms,\n"
                                    "  discovered to gatt complete %" PRIu64 " ms,\n"
                                    "  total %" PRIu64 " ms\n\n",
                                    td45, td47, (t7 - device->getCreationTimestamp()), td07);
                }
                if( gatt->isOpen() ) {
                    std::shared_ptr<GenericAccess> ga = gatt->getGenericAccess(primServices);
                    if( nullptr != ga ) {
                        fprintf(stderr, "  GenericAccess: %s\n\n", ga->toString().c_str());
                    }
                }
                if( gatt->isOpen() ) {
                    std::shared_ptr<DeviceInformation> di = gatt->getDeviceInformation(primServices);
                    if( nullptr != di ) {
                        fprintf(stderr, "  DeviceInformation: %s\n\n", di->toString().c_str());
                    }
                }

                for(size_t i=0; i<primServices.size() && gatt->isOpen(); i++) {
                    GATTPrimaryService & primService = *primServices.at(i);
                    fprintf(stderr, "  [%2.2d] Service %s\n", (int)i, primService.toString().c_str());
                    fprintf(stderr, "  [%2.2d] Service Characteristics\n", (int)i);
                    std::vector<GATTCharacterisicsDeclRef> & serviceCharacteristics = primService.characteristicDeclList;
                    for(size_t j=0; j<serviceCharacteristics.size() && gatt->isOpen(); j++) {
                        GATTCharacterisicsDecl & serviceChar = *serviceCharacteristics.at(j);
                        fprintf(stderr, "  [%2.2d.%2.2d] Decla: %s\n", (int)i, (int)j, serviceChar.toString().c_str());
                        if( serviceChar.hasProperties(GATTCharacterisicsDecl::PropertyBitVal::Read) ) {
                            POctets value(GATTHandler::ClientMaxMTU, 0);
                            if( gatt->readCharacteristicValue(serviceChar, value) ) {
                                fprintf(stderr, "  [%2.2d.%2.2d] Value: %s\n", (int)i, (int)j, value.toString().c_str());
                            }
                        }
                        if( nullptr != serviceChar.config ) {
                            const bool enableNotification = serviceChar.hasProperties(GATTCharacterisicsDecl::PropertyBitVal::Notify);
                            const bool enableIndication = serviceChar.hasProperties(GATTCharacterisicsDecl::PropertyBitVal::Indicate);
                            if( enableNotification || enableIndication ) {
                                bool res = gatt->configIndicationNotification(*serviceChar.config, enableNotification, enableIndication);
                                fprintf(stderr, "  [%2.2d.%2.2d] Config Notification(%d), Indication(%d): Result %d\n",
                                        (int)i, (int)j, enableNotification, enableIndication, res);
                            }
                        }
                    }
#ifdef SCAN_CHARACTERISTIC_DESCRIPTORS                            
                    fprintf(stderr, "  [%2.2d] Service Characteristics Descriptors\n", (int)i);
                    std::vector<GATTUUIDHandle> serviceDescriptors = servicesCharacteristicDescriptors.at(i);
                    for(size_t j=0; j<serviceDescriptors.size(); j++) {
                        fprintf(stderr, "  [%2.2d.%2.2d] %s\n", (int)i, (int)j, serviceDescriptors.at(j).toString().c_str());
                    }
#endif                            
                }
                // FIXME sleep 1s for potential callbacks ..
                sleep(1);
                device->disconnectGATT(); // redundant: also done at gatt->disconnect()
            } else {
                fprintf(stderr, "GATT connect failed: %s\n", gatt->getStateString().c_str());
            }
            device->disconnect(); // OK if not connected, also issues device->disconnectGATT() -> gatt->disconnect()
        } // if( ok && nullptr != device )
    }

#ifdef SHOW_STATIC_SERVICE_CHARACTERISTIC_COMPOSITION
    //
    // Show static composition of Services and Characteristics
    //
    for(size_t i=0; i<GATT_SERVICES.size(); i++) {
        const GattServiceCharacteristic * gsc = GATT_SERVICES.at(i);
        fprintf(stderr, "GattServiceCharacteristic %d: %s\n", (int)i, gsc->toString().c_str());
    }
#endif /* SHOW_STATIC_SERVICE_CHARACTERISTIC_COMPOSITION */

out:
    if( nullptr != session ) {
        session->close();
    }
    return 0;
}