Direct-BT  2.3.1
Direct-BT - Direct Bluetooth Programming.
dbt_scanner10.cpp

This dbt_scanner10 C++ scanner example uses the Direct-BT fully event driven workflow and adds multithreading, i.e. one thread processes each found device found as notified via the event listener.

dbt_scanner10 represents the recommended utilization of Direct-BT.

dbt_scanner10 Invocation Examples:

Using scripts/run-dbt_scanner10.sh from dist directory:

Special Actions

/*
* 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 <fstream>
#include <iostream>
#include <cinttypes>
#include <pthread.h>
#include <csignal>
#include <jau/darray.hpp>
extern "C" {
#include <unistd.h>
}
using namespace direct_bt;
using namespace jau;
/** \file
* This _dbt_scanner10_ C++ scanner example uses the Direct-BT fully event driven workflow
* and adds multithreading, i.e. one thread processes each found device found
* as notified via the event listener.
*
* _dbt_scanner10_ represents the recommended utilization of Direct-BT.
*
* ### dbt_scanner10 Invocation Examples:
* Using `scripts/run-dbt_scanner10.sh` from `dist` directory:
* * Scan and read all devices (using default auto-sec w/ keyboard iocap)
* ~~~
* ../scripts/run-dbt_scanner10.sh
* ~~~
*
* * Read device C0:26:DA:01:DA:B1 (using default auto-sec w/ keyboard iocap)
* ~~~
* ../scripts/run-dbt_scanner10.sh -dev C0:26:DA:01:DA:B1
* ~~~
*
* * Read device C0:26:DA:01:DA:B1 (enforcing no security)
* ~~~
* ../scripts/run-dbt_scanner10.sh -dev C0:26:DA:01:DA:B1 -seclevel C0:26:DA:01:DA:B1 1
* ~~~
*
* * Read any device containing C0:26:DA (enforcing no security)
* ~~~
* ../scripts/run-dbt_scanner10.sh -dev C0:26:DA -seclevel C0:26:DA 1
* ~~~
*
* * Read any device containing name `TAIDOC` (enforcing no security)
* ~~~
* ../scripts/run-dbt_scanner10.sh -dev 'TAIDOC' -seclevel 'TAIDOC' 1
* ~~~
*
* * Read device C0:26:DA:01:DA:B1, basic debug flags enabled (using default auto-sec w/ keyboard iocap)
* ~~~
* ../scripts/run-dbt_scanner10.sh -dev C0:26:DA:01:DA:B1 -dbt_debug true
* ~~~
*
* * Read device C0:26:DA:01:DA:B1, all debug flags enabled (using default auto-sec w/ keyboard iocap)
* ~~~
* ../scripts/run-dbt_scanner10.sh -dev C0:26:DA:01:DA:B1 -dbt_debug adapter.event,gatt.data,hci.event,hci.scan_ad_eir,mgmt.event
* ~~~
*
* ## Special Actions
* * To do a BT adapter removal/add via software, assuming the device is '1-4' (Bus 1.Port 4):
* ~~~
* echo '1-4' > /sys/bus/usb/drivers/usb/unbind
* echo '1-4' > /sys/bus/usb/drivers/usb/bind
* ~~~
*/
const static std::string KEY_PATH = "keys";
static uint64_t timestamp_t0;
static int RESET_ADAPTER_EACH_CONN = 0;
static std::atomic<int> deviceReadyCount = 0;
static std::atomic<int> MULTI_MEASUREMENTS = 8;
static bool KEEP_CONNECTED = true;
static bool GATT_PING_ENABLED = false;
static bool REMOVE_DEVICE = true;
static bool USE_WHITELIST = false;
static std::string charIdentifier = "";
static int charValue = 0;
static bool SHOW_UPDATE_EVENTS = false;
static bool QUIET = false;
static void connectDiscoveredDevice(std::shared_ptr<BTDevice> device);
static void processReadyDevice(std::shared_ptr<BTDevice> device);
static void removeDevice(std::shared_ptr<BTDevice> device);
static void resetAdapter(BTAdapter *a, int mode);
static bool startDiscovery(BTAdapter *a, std::string msg);
void adapterSettingsChanged(BTAdapter &a, const AdapterSetting oldmask, const AdapterSetting newmask,
const AdapterSetting changedmask, const uint64_t timestamp) override {
const bool initialSetting = AdapterSetting::NONE == oldmask;
if( initialSetting ) {
fprintf_td(stderr, "****** SETTINGS_INITIAL: %s -> %s, changed %s\n", to_string(oldmask).c_str(),
to_string(newmask).c_str(), to_string(changedmask).c_str());
} else {
fprintf_td(stderr, "****** SETTINGS_CHANGED: %s -> %s, changed %s\n", to_string(oldmask).c_str(),
to_string(newmask).c_str(), to_string(changedmask).c_str());
}
fprintf_td(stderr, "Status BTAdapter:\n");
fprintf_td(stderr, "%s\n", a.toString().c_str());
(void)timestamp;
if( !initialSetting &&
{
std::thread sd(::startDiscovery, &a, "powered-on"); // @suppress("Invalid arguments")
sd.detach();
}
}
void discoveringChanged(BTAdapter &a, const ScanType currentMeta, const ScanType changedType, const bool changedEnabled, const bool keepAlive, const uint64_t timestamp) override {
fprintf_td(stderr, "****** DISCOVERING: meta %s, changed[%s, enabled %d, keepAlive %d]: %s\n",
to_string(currentMeta).c_str(), to_string(changedType).c_str(), changedEnabled, keepAlive, a.toString().c_str());
(void)timestamp;
}
bool deviceFound(std::shared_ptr<BTDevice> device, const uint64_t timestamp) override {
(void)timestamp;
// Requires BREDR or LE Secure Connection support: WIP
fprintf_td(stderr, "****** FOUND__-2: Skip non 'public LE' and non 'random static public LE' %s\n", device->toString(true).c_str());
return false;
}
)
)
)
{
fprintf_td(stderr, "****** FOUND__-0: Connecting %s\n", device->toString(true).c_str());
{
const uint64_t td = getCurrentMilliseconds() - timestamp_t0; // adapter-init -> now
fprintf_td(stderr, "PERF: adapter-init -> FOUND__-0 %" PRIu64 " ms\n", td);
}
std::thread dc(::connectDiscoveredDevice, device); // @suppress("Invalid arguments")
dc.detach();
return true;
} else {
fprintf_td(stderr, "****** FOUND__-1: NOP %s\n", device->toString(true).c_str());
return false;
}
}
void deviceUpdated(std::shared_ptr<BTDevice> device, const EIRDataType updateMask, const uint64_t timestamp) override {
fprintf_td(stderr, "****** UPDATED: %s of %s\n", to_string(updateMask).c_str(), device->toString(true).c_str());
}
(void)timestamp;
}
void deviceConnected(std::shared_ptr<BTDevice> device, const uint16_t handle, const uint64_t timestamp) override {
fprintf_td(stderr, "****** CONNECTED: %s\n", device->toString(true).c_str());
(void)handle;
(void)timestamp;
}
void devicePairingState(std::shared_ptr<BTDevice> device, const SMPPairingState state, const PairingMode mode, const uint64_t timestamp) override {
fprintf_td(stderr, "****** PAIRING STATE: state %s, mode %s, %s\n",
to_string(state).c_str(), to_string(mode).c_str(), device->toString().c_str());
(void)timestamp;
switch( state ) {
// next: deviceReady(..)
break;
const bool res = SMPKeyBin::remove(KEY_PATH, device->getAddressAndType());
fprintf_td(stderr, "****** PAIRING_STATE: state %s; Remove key file %s, res %d\n",
to_string(state).c_str(), SMPKeyBin::getFilename(KEY_PATH, device->getAddressAndType()).c_str(), res);
// next: deviceReady() or deviceDisconnected(..)
} break;
// next: FEATURE_EXCHANGE_STARTED
break;
// next: FEATURE_EXCHANGE_COMPLETED
break;
// next: PASSKEY_EXPECTED... or KEY_DISTRIBUTION
break;
if( nullptr != sec && sec->getPairingPasskey() != BTSecurityRegistry::Entry::NO_PASSKEY ) {
std::thread dc(&BTDevice::setPairingPasskey, device, static_cast<uint32_t>( sec->getPairingPasskey() ));
dc.detach();
} else {
std::thread dc(&BTDevice::setPairingPasskey, device, 0);
// 3s disconnect: std::thread dc(&BTDevice::setPairingPasskeyNegative, device);
dc.detach();
}
// next: KEY_DISTRIBUTION or FAILED
} break;
if( nullptr != sec ) {
dc.detach();
} else {
std::thread dc(&BTDevice::setPairingNumericComparison, device, false);
dc.detach();
}
// next: KEY_DISTRIBUTION or FAILED
} break;
// FIXME: ABORT
break;
// next: COMPLETED or FAILED
break;
// next: deviceReady(..)
break;
default: // nop
break;
}
}
void deviceReady(std::shared_ptr<BTDevice> device, const uint64_t timestamp) override {
(void)timestamp;
)
)
)
{
fprintf_td(stderr, "****** READY-0: Processing[%d] %s\n", deviceReadyCount.load(), device->toString(true).c_str());
processReadyDevice(device); // AdapterStatusListener::deviceReady() explicitly allows prolonged and complex code execution!
} else {
fprintf_td(stderr, "****** READY-1: NOP %s\n", device->toString(true).c_str());
}
}
void deviceDisconnected(std::shared_ptr<BTDevice> device, const HCIStatusCode reason, const uint16_t handle, const uint64_t timestamp) override {
fprintf_td(stderr, "****** DISCONNECTED: Reason 0x%X (%s), old handle %s: %s\n",
static_cast<uint8_t>(reason), to_string(reason).c_str(),
to_hexstring(handle).c_str(), device->toString(true).c_str());
(void)timestamp;
if( REMOVE_DEVICE ) {
std::thread dc(::removeDevice, device); // @suppress("Invalid arguments")
dc.detach();
} else {
}
std::thread dc(::resetAdapter, &device->getAdapter(), 1); // @suppress("Invalid arguments")
dc.detach();
}
}
std::string toString() const override {
return "MyAdapterStatusListener[this "+to_hexstring(this)+"]";
}
};
private:
int i, j;
public:
MyGATTEventListener(int i_, int j_) : i(i_), j(j_) {}
void notificationReceived(BTGattCharRef charDecl, const TROOctets& char_value, const uint64_t timestamp) override {
const uint64_t tR = getCurrentMilliseconds();
fprintf_td(stderr, "**[%2.2d.%2.2d] Characteristic-Notify: UUID %s, td %" PRIu64 " ******\n",
i, j, charDecl->value_type->toUUID128String().c_str(), (tR-timestamp));
fprintf_td(stderr, "**[%2.2d.%2.2d] Characteristic: %s ******\n", i, j, charDecl->toString().c_str());
if( _TEMPERATURE_MEASUREMENT == *charDecl->value_type ) {
std::shared_ptr<GattTemperatureMeasurement> temp = GattTemperatureMeasurement::get(char_value);
if( nullptr != temp ) {
fprintf_td(stderr, "**[%2.2d.%2.2d] Value T: %s ******\n", i, j, temp->toString().c_str());
}
}
fprintf_td(stderr, "**[%2.2d.%2.2d] Value R: %s ******\n", i, j, char_value.toString().c_str());
}
void indicationReceived(BTGattCharRef charDecl,
const TROOctets& char_value, const uint64_t timestamp,
const bool confirmationSent) override
{
const uint64_t tR = getCurrentMilliseconds();
fprintf_td(stderr, "**[%2.2d.%2.2d] Characteristic-Indication: UUID %s, td %" PRIu64 ", confirmed %d ******\n",
i, j, charDecl->value_type->toUUID128String().c_str(), (tR-timestamp), confirmationSent);
fprintf_td(stderr, "**[%2.2d.%2.2d] Characteristic: %s ******\n", i, j, charDecl->toString().c_str());
if( _TEMPERATURE_MEASUREMENT == *charDecl->value_type ) {
std::shared_ptr<GattTemperatureMeasurement> temp = GattTemperatureMeasurement::get(char_value);
if( nullptr != temp ) {
fprintf_td(stderr, "**[%2.2d.%2.2d] Value T: %s ******\n", i, j, temp->toString().c_str());
}
}
fprintf_td(stderr, "**[%2.2d.%2.2d] Value R: %s ******\n", i, j, char_value.toString().c_str());
}
};
static void connectDiscoveredDevice(std::shared_ptr<BTDevice> device) {
fprintf_td(stderr, "****** Connecting Device: Start %s\n", device->toString().c_str());
// Testing listener lifecycle @ device dtor
class TempAdapterStatusListener : public AdapterStatusListener {
void deviceUpdated(std::shared_ptr<BTDevice> device, const EIRDataType updateMask, const uint64_t timestamp) override {
fprintf_td(stderr, "****** UPDATED(2): %s of %s\n", to_string(updateMask).c_str(), device->toString(true).c_str());
}
(void)timestamp;
}
void deviceConnected(std::shared_ptr<BTDevice> device, const uint16_t handle, const uint64_t timestamp) override {
fprintf_td(stderr, "****** CONNECTED(2): %s\n", device->toString(true).c_str());
(void)handle;
(void)timestamp;
}
std::string toString() const override {
return "TempAdapterStatusListener[this "+to_hexstring(this)+"]";
}
};
device->addStatusListener(std::shared_ptr<AdapterStatusListener>(new TempAdapterStatusListener()));
{
const HCIStatusCode r = device->unpair();
fprintf_td(stderr, "****** Connecting Device: Unpair-Pre result: %s\n", to_string(r).c_str());
}
{
const HCIStatusCode r = device->getAdapter().stopDiscovery();
fprintf_td(stderr, "****** Connecting Device: stopDiscovery result %s\n", to_string(r).c_str());
}
if( nullptr != sec ) {
fprintf_td(stderr, "****** Connecting Device: Found SecurityDetail %s for %s\n", sec->toString().c_str(), device->toString().c_str());
} else {
fprintf_td(stderr, "****** Connecting Device: No SecurityDetail for %s\n", device->toString().c_str());
}
const BTSecurityLevel req_sec_level = nullptr != sec ? sec->getSecLevel() : BTSecurityLevel::UNSET;
HCIStatusCode res = SMPKeyBin::readAndApply(KEY_PATH, *device, req_sec_level, true /* verbose */);
fprintf_td(stderr, "****** Connecting Device: SMPKeyBin::readAndApply(..) result %s\n", to_string(res).c_str());
if( HCIStatusCode::SUCCESS != res ) {
if( nullptr != sec ) {
if( sec->isSecurityAutoEnabled() ) {
bool r = device->setConnSecurityAuto( sec->getSecurityAutoIOCap() );
fprintf_td(stderr, "****** Connecting Device: Using SecurityDetail.SEC AUTO %s, set OK %d\n", sec->toString().c_str(), r);
} else if( sec->isSecLevelOrIOCapSet() ) {
bool r = device->setConnSecurityBest( sec->getSecLevel(), sec->getIOCap() );
fprintf_td(stderr, "****** Connecting Device: Using SecurityDetail.Level+IOCap %s, set OK %d\n", sec->toString().c_str(), r);
} else {
fprintf_td(stderr, "****** Connecting Device: Setting SEC AUTO security detail w/ KEYBOARD_ONLY (%s) -> set OK %d\n", sec->toString().c_str(), r);
}
} else {
fprintf_td(stderr, "****** Connecting Device: Setting SEC AUTO security detail w/ KEYBOARD_ONLY -> set OK %d\n", r);
}
}
if( !USE_WHITELIST ) {
res = device->connectDefault();
} else {
}
fprintf_td(stderr, "****** Connecting Device: End result %s of %s\n", to_string(res).c_str(), device->toString().c_str());
startDiscovery(&device->getAdapter(), "post-connect");
}
}
static void processReadyDevice(std::shared_ptr<BTDevice> device) {
fprintf_td(stderr, "****** Processing Ready Device: Start %s\n", device->toString().c_str());
device->getAdapter().stopDiscovery(); // make sure for pending connections on failed connect*(..) command
const uint64_t t1 = getCurrentMilliseconds();
SMPKeyBin::createAndWrite(*device, KEY_PATH, false /* overwrite */, true /* verbose */);
bool success = false;
{
LE_PHYs resRx, resTx;
HCIStatusCode res = device->getConnectedLE_PHY(resRx, resTx);
fprintf_td(stderr, "****** Connected LE PHY: status %s: RX %s, TX %s\n",
to_string(res).c_str(), to_string(resRx).c_str(), to_string(resTx).c_str());
}
//
// GATT Service Processing
//
fprintf_td(stderr, "****** Processing Ready Device: GATT start: %s\n", device->getAddressAndType().toString().c_str());
if( !QUIET ) {
}
try {
if( 0 == primServices.size() ) {
fprintf_td(stderr, "****** Processing Ready Device: getServices() failed %s\n", device->toString().c_str());
goto exit;
}
const uint64_t t5 = getCurrentMilliseconds();
if( !QUIET ) {
const uint64_t td01 = t1 - timestamp_t0; // adapter-init -> processing-start
const uint64_t td15 = t5 - t1; // get-gatt-services
const uint64_t tdc5 = t5 - device->getLastDiscoveryTimestamp(); // discovered to gatt-complete
const uint64_t td05 = t5 - timestamp_t0; // adapter-init -> gatt-complete
fprintf_td(stderr, "\n\n\n");
fprintf_td(stderr, "PERF: GATT primary-services completed\n");
fprintf_td(stderr, "PERF: adapter-init to processing-start %" PRIu64 " ms,\n"
"PERF: get-gatt-services %" PRIu64 " ms,\n"
"PERF: discovered to gatt-complete %" PRIu64 " ms (connect %" PRIu64 " ms),\n"
"PERF: adapter-init to gatt-complete %" PRIu64 " ms\n\n",
td01, td15, tdc5, (tdc5 - td15), td05);
}
#if 0
{
// WIP: Implement a simple Characteristic ping-pong writeValue <-> notify transmission for stress testing.
BTManager & manager = device->getAdapter().getManager();
if( nullptr != charIdentifier && charIdentifier.length() > 0 ) {
BTGattChar * char2 = (BTGattChar*) nullptr;
// manager.find(BluetoothType.GATT_CHARACTERISTIC, null, charIdentifier, device);
fprintf_td(stderr, "Char UUID %s\n", charIdentifier.c_str());
fprintf_td(stderr, " over device : %s\n", char2->toString().c_str());
if( nullptr != char2 ) {
bool cccdEnableResult[2];
bool cccdRet = char2->addCharListener( std::shared_ptr<BTGattCharListener>( new MyGATTEventListener(char2) ),
cccdEnableResult );
if( !QUIET ) {
fprintf_td(stderr, "Added CharPingPongListenerRes Notification(%d), Indication(%d): Result %d\n",
cccdEnableResult[0], cccdEnableResult[1], cccdRet);
}
if( cccdRet ) {
uint8_t cmd[] { (uint8_t)charValue }; // request device model
bool wres = char2->writeValueNoResp(cmd);
if( !QUIET ) {
fprintf_td(stderr, "Write response: "+wres);
}
}
}
}
}
#endif
std::shared_ptr<GattGenericAccessSvc> ga = device->getGattGenericAccess();
if( nullptr != ga && !QUIET ) {
fprintf_td(stderr, " GenericAccess: %s\n\n", ga->toString().c_str());
}
{
std::shared_ptr<BTGattHandler> gatt = device->getGattHandler();
if( nullptr != gatt && gatt->isConnected() ) {
std::shared_ptr<GattDeviceInformationSvc> di = gatt->getDeviceInformation(primServices);
if( nullptr != di && !QUIET ) {
fprintf_td(stderr, " DeviceInformation: %s\n\n", di->toString().c_str());
}
}
}
for(size_t i=0; i<primServices.size(); i++) {
BTGattService & primService = *primServices.at(i);
if( !QUIET ) {
fprintf_td(stderr, " [%2.2d] Service UUID %s\n", i, primService.type->toUUID128String().c_str());
fprintf_td(stderr, " [%2.2d] %s\n", i, primService.toString().c_str());
}
jau::darray<BTGattCharRef> & serviceCharacteristics = primService.characteristicList;
for(size_t j=0; j<serviceCharacteristics.size(); j++) {
BTGattChar & serviceChar = *serviceCharacteristics.at(j);
if( !QUIET ) {
fprintf_td(stderr, " [%2.2d.%2.2d] Characteristic: UUID %s\n", i, j, serviceChar.value_type->toUUID128String().c_str());
fprintf_td(stderr, " [%2.2d.%2.2d] %s\n", i, j, serviceChar.toString().c_str());
}
if( serviceChar.readValue(value) ) {
std::string sval = dfa_utf8_decode(value.get_ptr(), value.getSize());
if( !QUIET ) {
fprintf_td(stderr, " [%2.2d.%2.2d] value: %s ('%s')\n", (int)i, (int)j, value.toString().c_str(), sval.c_str());
}
}
}
jau::darray<BTGattDescRef> & charDescList = serviceChar.descriptorList;
for(size_t k=0; k<charDescList.size(); k++) {
BTGattDesc & charDesc = *charDescList.at(k);
if( !QUIET ) {
fprintf_td(stderr, " [%2.2d.%2.2d.%2.2d] Descriptor: UUID %s\n", i, j, k, charDesc.type->toUUID128String().c_str());
fprintf_td(stderr, " [%2.2d.%2.2d.%2.2d] %s\n", i, j, k, charDesc.toString().c_str());
}
}
bool cccdEnableResult[2];
bool cccdRet = serviceChar.addCharListener( std::shared_ptr<BTGattChar::Listener>( new MyGATTEventListener(i, j) ),
cccdEnableResult );
if( !QUIET ) {
fprintf_td(stderr, " [%2.2d.%2.2d] Characteristic-Listener: Notification(%d), Indication(%d): Added %d\n",
(int)i, (int)j, cccdEnableResult[0], cccdEnableResult[1], cccdRet);
fprintf_td(stderr, "\n");
}
}
fprintf_td(stderr, "\n");
}
// FIXME sleep 1s for potential callbacks ..
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
success = true;
} catch ( std::exception & e ) {
fprintf_td(stderr, "****** Processing Ready Device: Exception caught for %s: %s\n", device->toString().c_str(), e.what());
}
exit:
fprintf_td(stderr, "****** Processing Ready Device: End-1: Success %d on %s; devInProc %zu\n",
success, device->toString().c_str(), BTDeviceRegistry::getProcessingDeviceCount());
startDiscovery(&device->getAdapter(), "post-processing-1");
}
if( KEEP_CONNECTED && GATT_PING_ENABLED && success ) {
while( device->pingGATT() ) {
fprintf_td(stderr, "****** Processing Ready Device: pingGATT OK: %s\n", device->getAddressAndType().toString().c_str());
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
fprintf_td(stderr, "****** Processing Ready Device: pingGATT failed, waiting for disconnect: %s\n", device->getAddressAndType().toString().c_str());
// Even w/ GATT_PING_ENABLED, we utilize disconnect event to clean up -> remove
}
if( !QUIET ) {
}
fprintf_td(stderr, "****** Processing Ready Device: End-2: Success %d on %s; devInProc %zu\n",
success, device->toString().c_str(), BTDeviceRegistry::getProcessingDeviceCount());
if( success ) {
}
if( !KEEP_CONNECTED ) {
{
const HCIStatusCode unpair_res = device->unpair();
fprintf_td(stderr, "****** Processing Ready Device: Unpair-Post result: %s\n", to_string(unpair_res).c_str());
}
device->remove();
resetAdapter(&device->getAdapter(), 2);
startDiscovery(&device->getAdapter(), "post-processing-2");
}
}
if( 0 < MULTI_MEASUREMENTS ) {
fprintf_td(stderr, "****** Processing Ready Device: MULTI_MEASUREMENTS left %d: %s\n", MULTI_MEASUREMENTS.load(), device->getAddressAndType().toString().c_str());
}
}
static void removeDevice(std::shared_ptr<BTDevice> device) {
fprintf_td(stderr, "****** Remove Device: removing: %s\n", device->getAddressAndType().toString().c_str());
device->remove();
startDiscovery(&device->getAdapter(), "post-remove-device");
}
}
static void resetAdapter(BTAdapter *a, int mode) {
fprintf_td(stderr, "****** Reset Adapter: reset[%d] start: %s\n", mode, a->toString().c_str());
HCIStatusCode res = a->reset();
fprintf_td(stderr, "****** Reset Adapter: reset[%d] end: %s, %s\n", mode, to_string(res).c_str(), a->toString().c_str());
}
static bool le_scan_active = true; // default value
static const uint16_t le_scan_interval = 24; // default value
static const uint16_t le_scan_window = 24; // default value
static const uint8_t filter_policy = 0; // default value
static bool startDiscovery(BTAdapter *a, std::string msg) {
fprintf_td(stderr, "****** Start discovery (%s) result: %s\n", msg.c_str(), to_string(status).c_str());
return HCIStatusCode::SUCCESS == status;
}
static bool initAdapter(std::shared_ptr<BTAdapter>& adapter) {
// Even if adapter is not yet powered, listen to it and act when it gets powered-on
adapter->addStatusListener(std::shared_ptr<AdapterStatusListener>(new MyAdapterStatusListener()));
// Flush discovered devices after registering our status listener.
// This avoids discovered devices before we have registered!
if( !adapter->isPowered() ) { // should have been covered above
fprintf_td(stderr, "Adapter not powered (2): %s\n", adapter->toString().c_str());
return false;
}
if( USE_WHITELIST ) {
for (auto it = WHITELIST.begin(); it != WHITELIST.end(); ++it) {
fprintf_td(stderr, "Added to WHITELIST: res %d, address %s\n", res, it->toString().c_str());
}
} else {
if( !startDiscovery(adapter.get(), "kick-off") ) {
return false;
}
}
return true;
}
static bool myChangedAdapterSetFunc(const bool added, std::shared_ptr<BTAdapter>& adapter) {
if( added ) {
if( initAdapter( adapter ) ) {
fprintf_td(stderr, "****** Adapter ADDED__: InitOK. %s\n", adapter->toString().c_str());
} else {
fprintf_td(stderr, "****** Adapter ADDED__: Ignored %s\n", adapter->toString().c_str());
}
fprintf_td(stderr, "****** Adapter Features: %s\n", direct_bt::to_string(adapter->getLEFeatures()).c_str());
} else {
fprintf_td(stderr, "****** Adapter REMOVED: %s\n", adapter->toString().c_str());
}
return true;
}
void test() {
bool done = false;
fprintf_td(stderr, "DirectBT Native Version %s (API %s)\n", DIRECT_BT_VERSION, DIRECT_BT_VERSION_API);
while( !done ) {
if( 0 == MULTI_MEASUREMENTS ||
)
{
fprintf_td(stderr, "****** EOL Test MULTI_MEASUREMENTS left %d, processed %zu/%zu\n",
fprintf_td(stderr, "****** WaitForDevice %s\n", BTDeviceRegistry::getWaitForDevicesString().c_str());
fprintf_td(stderr, "****** DevicesProcessed %s\n", BTDeviceRegistry::getProcessedDevicesString().c_str());
done = true;
} else {
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
}
}
//
// just a manually controlled pull down to show status, not required
//
jau::for_each_const(adapterList, [](const std::shared_ptr<BTAdapter>& adapter) {
fprintf_td(stderr, "****** EOL Adapter's Devices - pre close: %s\n", adapter->toString().c_str());
adapter->printDeviceLists();
});
{
fprintf_td(stderr, "****** EOL Removed ChangedAdapterSetCallback %d\n", count);
mngr.close();
}
jau::for_each_const(adapterList, [](const std::shared_ptr<BTAdapter>& adapter) {
fprintf_td(stderr, "****** EOL Adapter's Devices - post close: %s\n", adapter->toString().c_str());
adapter->printDeviceLists();
});
}
#include <cstdio>
int main(int argc, char *argv[])
{
BTMode btMode = BTMode::DUAL;
bool waitForEnter=false;
for(int i=1; i<argc; i++) {
if( !strcmp("-dbt_debug", argv[i]) && argc > (i+1) ) {
setenv("direct_bt.debug", argv[++i], 1 /* overwrite */);
} else if( !strcmp("-dbt_verbose", argv[i]) && argc > (i+1) ) {
setenv("direct_bt.verbose", argv[++i], 1 /* overwrite */);
} else if( !strcmp("-dbt_gatt", argv[i]) && argc > (i+1) ) {
setenv("direct_bt.gatt", argv[++i], 1 /* overwrite */);
} else if( !strcmp("-dbt_l2cap", argv[i]) && argc > (i+1) ) {
setenv("direct_bt.l2cap", argv[++i], 1 /* overwrite */);
} else if( !strcmp("-dbt_hci", argv[i]) && argc > (i+1) ) {
setenv("direct_bt.hci", argv[++i], 1 /* overwrite */);
} else if( !strcmp("-dbt_mgmt", argv[i]) && argc > (i+1) ) {
setenv("direct_bt.mgmt", argv[++i], 1 /* overwrite */);
} else if( !strcmp("-btmode", argv[i]) && argc > (i+1) ) {
btMode = to_BTMode(argv[++i]);
if( BTMode::NONE != btMode ) {
setenv("direct_bt.mgmt.btmode", to_string(btMode).c_str(), 1 /* overwrite */);
}
} else if( !strcmp("-wait", argv[i]) ) {
waitForEnter = true;
} else if( !strcmp("-show_update_events", argv[i]) ) {
} else if( !strcmp("-quiet", argv[i]) ) {
QUIET = true;
} else if( !strcmp("-scanPassive", argv[i]) ) {
le_scan_active = false;
} else if( !strcmp("-dev", argv[i]) && argc > (i+1) ) {
std::string addrOrNameSub = std::string(argv[++i]);
} else if( !strcmp("-wl", argv[i]) && argc > (i+1) ) {
std::string macstr = std::string(argv[++i]);
fprintf(stderr, "Whitelist + %s\n", wle.toString().c_str());
WHITELIST.push_back( wle );
USE_WHITELIST = true;
} else if( !strcmp("-passkey", argv[i]) && argc > (i+2) ) {
const std::string addrOrNameSub(argv[++i]);
sec->passkey = atoi(argv[++i]);
fprintf(stderr, "Set passkey in %s\n", sec->toString().c_str());
} else if( !strcmp("-seclevel", argv[i]) && argc > (i+2) ) {
const std::string addrOrNameSub(argv[++i]);
sec->sec_level = to_BTSecurityLevel(atoi(argv[++i]));
fprintf(stderr, "Set sec_level in %s\n", sec->toString().c_str());
} else if( !strcmp("-iocap", argv[i]) && argc > (i+2) ) {
const std::string addrOrNameSub(argv[++i]);
sec->io_cap = to_SMPIOCapability(atoi(argv[++i]));
fprintf(stderr, "Set io_cap in %s\n", sec->toString().c_str());
} else if( !strcmp("-secauto", argv[i]) && argc > (i+2) ) {
const std::string addrOrNameSub(argv[++i]);
sec->io_cap_auto = to_SMPIOCapability(atoi(argv[++i]));
fprintf(stderr, "Set SEC AUTO security io_cap in %s\n", sec->toString().c_str());
} else if( !strcmp("-charid", argv[i]) && argc > (i+1) ) {
charIdentifier = std::string(argv[++i]);
} else if( !strcmp("-charval", argv[i]) && argc > (i+1) ) {
charValue = atoi(argv[++i]);
} else if( !strcmp("-disconnect", argv[i]) ) {
KEEP_CONNECTED = false;
} else if( !strcmp("-enableGATTPing", argv[i]) ) {
} else if( !strcmp("-keepDevice", argv[i]) ) {
REMOVE_DEVICE = false;
} else if( !strcmp("-count", argv[i]) && argc > (i+1) ) {
MULTI_MEASUREMENTS = atoi(argv[++i]);
} else if( !strcmp("-single", argv[i]) ) {
} else if( !strcmp("-resetEachCon", argv[i]) && argc > (i+1) ) {
RESET_ADAPTER_EACH_CONN = atoi(argv[++i]);
}
}
fprintf(stderr, "pid %d\n", getpid());
fprintf(stderr, "Run with '[-btmode LE|BREDR|DUAL] "
"[-disconnect] [-enableGATTPing] [-count <number>] [-single] [-show_update_events] [-quiet] "
"[-scanPassive]"
"[-resetEachCon connectionCount] "
"(-dev <device_[address|name]_sub>)* (-wl <device_address>)* "
"(-seclevel <device_[address|name]_sub> <int_sec_level>)* "
"(-iocap <device_[address|name]_sub> <int_iocap>)* "
"(-secauto <device_[address|name]_sub> <int_iocap>)* "
"(-passkey <device_[address|name]_sub> <digits>)* "
"[-unpairPre] [-unpairPost] "
"[-charid <uuid>] [-charval <byte-val>] "
"[-dbt_verbose true|false] "
"[-dbt_debug true|false|adapter.event,gatt.data,hci.event,hci.scan_ad_eir,mgmt.event] "
"[-dbt_mgmt cmd.timeout=3000,ringsize=64,...] "
"[-dbt_hci cmd.complete.timeout=10000,cmd.status.timeout=3000,ringsize=64,...] "
"[-dbt_gatt cmd.read.timeout=500,cmd.write.timeout=500,cmd.init.timeout=2500,ringsize=128,...] "
"[-dbt_l2cap reader.timeout=10000,restart.count=0,...] "
"\n");
fprintf(stderr, "MULTI_MEASUREMENTS %d\n", MULTI_MEASUREMENTS.load());
fprintf(stderr, "KEEP_CONNECTED %d\n", KEEP_CONNECTED);
fprintf(stderr, "RESET_ADAPTER_EACH_CONN %d\n", RESET_ADAPTER_EACH_CONN);
fprintf(stderr, "GATT_PING_ENABLED %d\n", GATT_PING_ENABLED);
fprintf(stderr, "REMOVE_DEVICE %d\n", REMOVE_DEVICE);
fprintf(stderr, "USE_WHITELIST %d\n", USE_WHITELIST);
fprintf(stderr, "SHOW_UPDATE_EVENTS %d\n", SHOW_UPDATE_EVENTS);
fprintf(stderr, "QUIET %d\n", QUIET);
fprintf(stderr, "btmode %s\n", to_string(btMode).c_str());
fprintf(stderr, "scanActive %s\n", to_string(le_scan_active).c_str());
fprintf(stderr, "characteristic-id: %s\n", charIdentifier.c_str());
fprintf(stderr, "characteristic-value: %d\n", charValue);
fprintf(stderr, "security-details: %s\n", BTSecurityRegistry::allToString().c_str());
fprintf(stderr, "waitForDevice: %s\n", BTDeviceRegistry::getWaitForDevicesString().c_str());
if( waitForEnter ) {
fprintf(stderr, "Press ENTER to continue\n");
getchar();
}
fprintf(stderr, "****** TEST start\n");
test();
fprintf(stderr, "****** TEST end\n");
if( true ) {
// Just for testing purpose, i.e. triggering BTManager::close() within the test controlled app,
// instead of program shutdown.
fprintf(stderr, "****** Manager close start\n");
BTManager & mngr = BTManager::get(); // already existing
mngr.close();
fprintf(stderr, "****** Manager close end\n");
}
}
direct_bt::BTDeviceRegistry::getWaitForDevicesString
std::string getWaitForDevicesString() noexcept
Definition: BTDeviceRegistry.cpp:62
direct_bt::BTGattService::characteristicList
jau::darray< BTGattCharRef > characteristicList
List of Characteristic Declarations as shared reference.
Definition: BTGattService.hpp:97
direct_bt::BTAdapter::stopDiscovery
HCIStatusCode stopDiscovery() noexcept
Closes the discovery session.
Definition: BTAdapter.cpp:756
direct_bt::BTDevice::connectDefault
HCIStatusCode connectDefault() noexcept
Establish a default HCI connection to this device, using certain default parameter.
Definition: BTDevice.cpp:532
jau::darray::at
const_reference at(size_type i) const
Like std::vector::at(size_type), immutable reference.
Definition: darray.hpp:719
direct_bt::AdapterSetting
AdapterSetting
Adapter Setting Bits.
Definition: BTTypes1.hpp:136
DirectBT.hpp
direct_bt::BTSecurityRegistry::getOrCreate
Entry * getOrCreate(const std::string &addrOrNameSub) noexcept
Determines whether the given.
Definition: BTSecurityRegistry.cpp:71
direct_bt::BTDeviceRegistry::areAllDevicesProcessed
bool areAllDevicesProcessed(DeviceQueryMatchFunc m) noexcept
Returns.
Definition: BTDeviceRegistry.cpp:126
direct_bt::BTGattHandler::getDeviceInformation
std::shared_ptr< GattDeviceInformationSvc > getDeviceInformation(jau::darray< BTGattServiceRef > &primServices)
Definition: BTGattHandler.cpp:1096
direct_bt::BTGattChar::hasProperties
bool hasProperties(const PropertyBitVal v) const noexcept
Definition: BTGattChar.hpp:216
direct_bt::BTDevice::remove
void remove() noexcept
Disconnects this device via disconnect(..) if getConnected()==true and explicitly removes its shared ...
Definition: BTDevice.cpp:1784
direct_bt::BTDeviceRegistry::getProcessedDevicesString
std::string getProcessedDevicesString() noexcept
Definition: BTDeviceRegistry.cpp:92
direct_bt::GattGenericAccessSvc::toString
std::string toString() const noexcept
Definition: GATTNumbers.cpp:382
direct_bt::BTDevice::setConnSecurityAuto
bool setConnSecurityAuto(const SMPIOCapability iocap_auto) noexcept
Set automatic security negotiation of BTSecurityLevel and SMPIOCapability pairing mode.
Definition: BTDevice.cpp:1274
darray.hpp
direct_bt::GattTemperatureMeasurement::get
static std::shared_ptr< GattTemperatureMeasurement > get(const TROOctets &source) noexcept
Definition: GATTNumbers.cpp:414
direct_bt::BTSecurityRegistry::Entry::isSecLevelOrIOCapSet
constexpr bool isSecLevelOrIOCapSet() const noexcept
Definition: BTSecurityRegistry.hpp:59
le_scan_interval
static const uint16_t le_scan_interval
Definition: dbt_scanner10.cpp:633
direct_bt::HCIWhitelistConnectType::HCI_AUTO_CONN_ALWAYS
@ HCI_AUTO_CONN_ALWAYS
Auto Connect: Only supported for LE on Linux .
direct_bt::EIRDataType
EIRDataType
Bit mask of 'Extended Inquiry Response' (EIR) data fields, indicating a set of related data.
Definition: BTTypes0.hpp:752
direct_bt::BTAdapter::reset
HCIStatusCode reset() noexcept
Reset the adapter.
Definition: BTAdapter.cpp:489
direct_bt::to_BTSecurityLevel
constexpr BTSecurityLevel to_BTSecurityLevel(const uint8_t v) noexcept
Definition: BTTypes0.hpp:244
direct_bt::BTSecurityRegistry::allToString
std::string allToString() noexcept
Definition: BTSecurityRegistry.cpp:93
direct_bt::SMPPairingState::PASSKEY_EXPECTED
@ PASSKEY_EXPECTED
Phase 2: Authentication (MITM) PASSKEY expected now, see PairingMode::PASSKEY_ENTRY_ini.
direct_bt::BDAddressAndType::getBLERandomAddressType
BLERandomAddressType getBLERandomAddressType() const noexcept
Returns the BLERandomAddressType.
Definition: BTAddress.hpp:479
direct_bt::BTAdapter::getLEFeatures
constexpr LE_Features getLEFeatures() const noexcept
Return LE_Features for this controller.
Definition: BTAdapter.hpp:465
basic_algos.hpp
direct_bt::BTGattChar::readValue
bool readValue(POctets &res, int expectedLength=-1)
BT Core Spec v5.2: Vol 3, Part G GATT: 4.8.1 Read Characteristic Value.
Definition: BTGattChar.cpp:304
direct_bt::BTSecurityRegistry::getStartOf
Entry * getStartOf(const EUI48 &addr, const std::string &name) noexcept
Returns a matching Entry,.
Definition: BTSecurityRegistry.hpp:153
direct_bt::BTGattDesc::type
std::unique_ptr< const uuid_t > type
Type of descriptor.
Definition: BTGattDesc.hpp:102
direct_bt::BTSecurityRegistry::Entry::io_cap_auto
SMPIOCapability io_cap_auto
Definition: BTSecurityRegistry.hpp:50
direct_bt::TROOctets::toString
std::string toString() const noexcept
Definition: OctetTypes.hpp:244
direct_bt::BTSecurityRegistry::Entry::getPairingPasskey
constexpr int getPairingPasskey() const noexcept
Definition: BTSecurityRegistry.hpp:70
SHOW_UPDATE_EVENTS
static bool SHOW_UPDATE_EVENTS
Definition: dbt_scanner10.cpp:123
direct_bt::BTSecurityRegistry::Entry
Definition: BTSecurityRegistry.hpp:42
dfa_utf8_decode.hpp
direct_bt
Definition: ATTPDUTypes.hpp:171
direct_bt::to_BTMode
BTMode to_BTMode(const std::string &value) noexcept
Maps the specified name to a constant of BTMode.
Definition: BTTypes0.cpp:360
direct_bt::BTGattDesc::toString
virtual std::string toString() const noexcept override
Definition: BTGattDesc.cpp:82
direct_bt::BTMode::NONE
@ NONE
Zero mode, neither DUAL, BREDR nor LE.
direct_bt::BTGattChar
Definition: BTGattChar.hpp:75
direct_bt::BTDevice::getConnectedLE_PHY
HCIStatusCode getConnectedLE_PHY(LE_PHYs &resRx, LE_PHYs &resTx) noexcept
Request and return LE_PHYs bit for the given connection.
Definition: BTDevice.cpp:1648
direct_bt::AdapterStatusListener
BTAdapter status listener for BTDevice discovery events: Added, updated and removed; as well as for c...
Definition: BTAdapter.hpp:67
direct_bt::BTAdapter::removeDiscoveredDevices
int removeDiscoveredDevices() noexcept
Discards all discovered devices.
Definition: BTAdapter.cpp:877
direct_bt::BTDevice::setPairingNumericComparison
HCIStatusCode setPairingNumericComparison(const bool equal) noexcept
Method sets the numeric comparison result, see PairingMode::NUMERIC_COMPARE_ini.
Definition: BTDevice.cpp:1350
direct_bt::SMPPairingState::OOB_EXPECTED
@ OOB_EXPECTED
Phase 2: Authentication (MITM) OOB data expected now, see PairingMode::OUT_OF_BAND.
direct_bt::BTDevice::getLastDiscoveryTimestamp
uint64_t getLastDiscoveryTimestamp() const noexcept
Returns the timestamp in monotonic milliseconds when this device instance has discovered or connected...
Definition: BTDevice.hpp:260
direct_bt::BTDevice::pingGATT
bool pingGATT() noexcept
Issues a GATT ping to the device, validating whether it is still reachable.
Definition: BTDevice.cpp:1575
direct_bt::SMPKeyBin::getFilename
static std::string getFilename(const std::string &path, const BDAddressAndType &addrAndType_)
Definition: SMPKeyBin.hpp:292
direct_bt::BTDeviceRegistry::getProcessingDeviceCount
size_t getProcessingDeviceCount() noexcept
Definition: BTDeviceRegistry.cpp:162
direct_bt::to_SMPIOCapability
constexpr SMPIOCapability to_SMPIOCapability(const uint8_t v) noexcept
Definition: SMPTypes.hpp:199
_TEMPERATURE_MEASUREMENT
static const uuid16_t _TEMPERATURE_MEASUREMENT(GattCharacteristicType::TEMPERATURE_MEASUREMENT)
removeDevice
static void removeDevice(std::shared_ptr< BTDevice > device)
Definition: dbt_scanner10.cpp:613
direct_bt::SMPPairingState::KEY_DISTRIBUTION
@ KEY_DISTRIBUTION
Phase 3: Key & value distribution started after SMPPairConfirmMsg or SMPPairPubKeyMsg (LE Secure Conn...
direct_bt::uuid16_t
Definition: UUID.hpp:98
direct_bt::BDAddressAndType::toString
std::string toString() const noexcept
Definition: BTTypes0.cpp:333
direct_bt::BTAdapter::printDeviceLists
void printDeviceLists() noexcept
Print the internally maintained BTDevice lists to stderr:
Definition: BTAdapter.cpp:325
jau
Definition: basic_algos.hpp:34
direct_bt::BTDeviceRegistry::addToProcessingDevices
void addToProcessingDevices(const BDAddressAndType &a, const std::string &n) noexcept
Definition: BTDeviceRegistry.cpp:145
direct_bt::BTSecurityRegistry::Entry::toString
std::string toString() const noexcept
Definition: BTSecurityRegistry.hpp:74
direct_bt::BTGattService
Representing a complete [Primary] Service Declaration including its list of Characteristic Declaratio...
Definition: BTGattService.hpp:67
direct_bt::ScanType
ScanType
Meta ScanType as derived from BTMode, with defined value mask consisting of BDAddressType bits.
Definition: BTTypes0.hpp:294
WHITELIST
static jau::darray< BDAddressAndType > WHITELIST
Definition: dbt_scanner10.cpp:118
direct_bt::BTDevice::toString
std::string toString() const noexcept override
Definition: BTDevice.hpp:303
direct_bt::BTManager::close
void close() noexcept
Definition: BTManager.cpp:538
direct_bt::BTDevice::getAddressAndType
constexpr BDAddressAndType const & getAddressAndType() const noexcept
Returns the unique device EUI48 address and BDAddressType type.
Definition: BTDevice.hpp:278
direct_bt::BTGattChar::addCharListener
bool addCharListener(std::shared_ptr< Listener > l)
Add the given BTGattChar::Listener to the listener list if not already present.
Definition: BTGattChar.cpp:285
direct_bt::BTDeviceRegistry::isWaitingForDevice
bool isWaitingForDevice(const EUI48 &address, const std::string &name, DeviceQueryMatchFunc m) noexcept
Returns.
Definition: BTDeviceRegistry.cpp:120
direct_bt::BTSecurityLevel
BTSecurityLevel
Bluetooth Security Level.
Definition: BTTypes0.hpp:211
direct_bt::BTSecurityRegistry::Entry::getIOCap
constexpr const SMPIOCapability & getIOCap() const noexcept
Definition: BTSecurityRegistry.hpp:63
QUIET
static bool QUIET
Definition: dbt_scanner10.cpp:124
direct_bt::BTAdapter::isPowered
bool isPowered() const noexcept
Returns whether the adapter is valid, plugged in and powered.
Definition: BTAdapter.hpp:437
direct_bt::HCIStatusCode
HCIStatusCode
BT Core Spec v5.2: Vol 1, Part F Controller Error Codes: 1.3 List of Error Codes.
Definition: HCITypes.hpp:124
RESET_ADAPTER_EACH_CONN
static int RESET_ADAPTER_EACH_CONN
Definition: dbt_scanner10.cpp:108
jau::darray
Implementation of a dynamic linear array storage, aka vector.
Definition: darray.hpp:102
timestamp_t0
static uint64_t timestamp_t0
Definition: dbt_scanner10.cpp:106
direct_bt::BTGattCharRef
std::shared_ptr< BTGattChar > BTGattCharRef
Definition: BTGattChar.hpp:409
direct_bt::BTSecurityRegistry::Entry::getPairingNumericComparison
constexpr bool getPairingNumericComparison() const noexcept
Definition: BTSecurityRegistry.hpp:72
direct_bt::BTDevice::getGattGenericAccess
std::shared_ptr< GattGenericAccessSvc > getGattGenericAccess()
Returns the shared GenericAccess instance, retrieved by getGattService() or nullptr if not available.
Definition: BTDevice.cpp:1590
le_scan_window
static const uint16_t le_scan_window
Definition: dbt_scanner10.cpp:634
TEMPERATURE_MEASUREMENT
@ TEMPERATURE_MEASUREMENT
Definition: test_datatype02.hpp:82
direct_bt::BDAddressAndType::type
BDAddressType type
Definition: BTAddress.hpp:429
jau::fprintf_td
int fprintf_td(FILE *stream, const char *format,...) noexcept
Convenient fprintf() invocation, prepending the environment::getElapsedMillisecond() timestamp.
Definition: debug.cpp:188
direct_bt::BTManager::getAdapters
jau::darray< std::shared_ptr< BTAdapter > > getAdapters()
Returns a list of currently added DBTAdapter.
Definition: BTManager.hpp:367
MULTI_MEASUREMENTS
static std::atomic< int > MULTI_MEASUREMENTS
Definition: dbt_scanner10.cpp:111
direct_bt::BTAdapter::toString
std::string toString() const noexcept override
Definition: BTAdapter.hpp:784
direct_bt::BTDevice::setPairingPasskey
HCIStatusCode setPairingPasskey(const uint32_t passkey) noexcept
Method sets the given passkey entry, see PairingMode::PASSKEY_ENTRY_ini.
Definition: BTDevice.cpp:1304
direct_bt::SMPPairingState::FAILED
@ FAILED
Pairing failed.
direct_bt::BTGattHandler::Defaults::MAX_ATT_MTU
@ MAX_ATT_MTU
direct_bt::BTDeviceRegistry::addToWaitForDevices
void addToWaitForDevices(const std::string &addrOrNameSub) noexcept
Definition: BTDeviceRegistry.cpp:46
direct_bt::BTDeviceRegistry::removeFromProcessingDevices
bool removeFromProcessingDevices(const BDAddressAndType &a) noexcept
Definition: BTDeviceRegistry.cpp:149
direct_bt::SMPPairingState::FEATURE_EXCHANGE_COMPLETED
@ FEATURE_EXCHANGE_COMPLETED
Phase 1: Pairing responded by responding (slave) device via SMPPairingMsg.
direct_bt::BTManager::removeChangedAdapterSetCallback
int removeChangedAdapterSetCallback(const ChangedAdapterSetCallback &l)
Remove the given ChangedAdapterSetCallback from this manager.
Definition: BTManager.cpp:1238
direct_bt::BTManager::get
static BTManager & get(const BTMode defaultBTMode=BTMode::NONE)
Retrieves the singleton instance.
Definition: BTManager.hpp:320
direct_bt::BTSecurityRegistry::Entry::io_cap
SMPIOCapability io_cap
Definition: BTSecurityRegistry.hpp:49
GATT_PING_ENABLED
static bool GATT_PING_ENABLED
Definition: dbt_scanner10.cpp:114
direct_bt::GattDeviceInformationSvc::toString
std::string toString() const noexcept
Definition: GATTNumbers.cpp:407
direct_bt::BTSecurityLevel::UNSET
@ UNSET
Security Level not set, value 0.
jau::darray::size
constexpr size_type size() const noexcept
Like std::vector::size().
Definition: darray.hpp:668
Read
@ Read
Definition: test_datatype02.hpp:106
direct_bt::PairingMode
PairingMode
Bluetooth secure pairing mode.
Definition: BTTypes0.hpp:261
direct_bt::BTDevice::removeAllCharListener
int removeAllCharListener() noexcept
Remove all BTGattCharListener from the list.
Definition: BTDevice.cpp:1638
direct_bt::BTDeviceRegistry::addToProcessedDevices
void addToProcessedDevices(const BDAddressAndType &a, const std::string &n) noexcept
Definition: BTDeviceRegistry.cpp:80
MyAdapterStatusListener
Definition: dbt_scanner00.cpp:55
direct_bt::BTManager
A thread safe singleton handler of the Linux Kernel's BlueZ manager control channel.
Definition: BTManager.hpp:201
direct_bt::BTDeviceRegistry::isDeviceProcessing
bool isDeviceProcessing(const BDAddressAndType &a) noexcept
Definition: BTDeviceRegistry.cpp:158
main
int main(int argc, char *argv[])
Definition: dbt_scanner10.cpp:730
direct_bt::BLERandomAddressType::STATIC_PUBLIC
@ STATIC_PUBLIC
Static public 'random' device address 0b11.
direct_bt::SMPPairingState::REQUESTED_BY_RESPONDER
@ REQUESTED_BY_RESPONDER
Phase 0: Pairing requested by responding (slave) device via SMPSecurityReqMsg.
jau::dfa_utf8_decode
uint32_t dfa_utf8_decode(uint32_t &state, uint32_t &codep, const uint32_t byte_value)
Definition: dfa_utf8_decode.cpp:90
direct_bt::BTDevice::setConnSecurityBest
bool setConnSecurityBest(const BTSecurityLevel sec_level, const SMPIOCapability io_cap) noexcept
Convenience method to determine the best practice BTSecurityLevel and SMPIOCapability based on the gi...
Definition: BTDevice.cpp:1258
direct_bt::BTGattService::type
std::unique_ptr< const uuid_t > type
Service type UUID.
Definition: BTGattService.hpp:94
jau::for_each_const
constexpr UnaryFunction for_each_const(T &data, UnaryFunction f, std::enable_if_t< is_cow_type< T >::value, bool >=true) noexcept
Definition: basic_algos.hpp:323
direct_bt::BTAdapter::addStatusListener
bool addStatusListener(std::shared_ptr< AdapterStatusListener > l)
Add the given listener to the list if not already present.
Definition: BTAdapter.cpp:548
REMOVE_DEVICE
static bool REMOVE_DEVICE
Definition: dbt_scanner10.cpp:115
direct_bt::BTGattChar::toString
std::string toString() const noexcept override
Definition: BTGattChar.cpp:106
le_scan_active
static bool le_scan_active
Definition: dbt_scanner10.cpp:632
KEY_PATH
static const std::string KEY_PATH
Definition: dbt_scanner10.cpp:104
direct_bt::SMPPairingState::NUMERIC_COMPARE_EXPECTED
@ NUMERIC_COMPARE_EXPECTED
Phase 2: Authentication (MITM) Numeric Comparison Reply expected now, see PairingMode::NUMERIC_COMPAR...
USE_WHITELIST
static bool USE_WHITELIST
Definition: dbt_scanner10.cpp:117
direct_bt::TROOctets
Transient read only octet data, i.e.
Definition: OctetTypes.hpp:59
direct_bt::SMPKeyBin::readAndApply
static HCIStatusCode readAndApply(const std::string &path, BTDevice &device, const BTSecurityLevel minSecLevel, const bool verbose_)
Create a new SMPKeyBin instance on the fly based upon stored file denoted by path and BTDevice::getAd...
Definition: SMPKeyBin.cpp:92
direct_bt::to_string
std::string to_string(const BDAddressType type) noexcept
Definition: BTTypes0.cpp:129
direct_bt::BTManager::addChangedAdapterSetCallback
void addChangedAdapterSetCallback(const ChangedAdapterSetCallback &l)
ChangedAdapterSetCallback handling.
Definition: BTManager.cpp:1230
direct_bt::BTAdapter
BTAdapter represents one Bluetooth Controller.
Definition: BTAdapter.hpp:250
direct_bt::BTSecurityRegistry::Entry::getSecurityAutoIOCap
constexpr const SMPIOCapability & getSecurityAutoIOCap() const noexcept
Definition: BTSecurityRegistry.hpp:68
direct_bt::SMPIOCapability::KEYBOARD_ONLY
@ KEYBOARD_ONLY
Keyboard input only, value 2.
direct_bt::BTMode::DUAL
@ DUAL
Dual Bluetooth mode, i.e.
jau::getCurrentMilliseconds
uint64_t getCurrentMilliseconds() noexcept
Returns current monotonic time in milliseconds.
Definition: basic_types.cpp:47
charValue
static int charValue
Definition: dbt_scanner10.cpp:121
direct_bt::AdapterSetting::NONE
@ NONE
direct_bt::EUI48
A packed 48 bit EUI-48 identifier, formerly known as MAC-48 or simply network device MAC address (Med...
Definition: BTAddress.hpp:388
direct_bt::BDAddressAndType::address
EUI48 address
Definition: BTAddress.hpp:428
direct_bt::BTAdapter::getManager
BTManager & getManager() const noexcept
Returns a reference to the used singleton BTManager instance, used to create this adapter.
Definition: BTAdapter.hpp:570
jau::to_hexstring
std::string to_hexstring(value_type const &v) noexcept
Produce a lower-case hexadecimal string representation of the given pointer.
Definition: string_util.hpp:104
cpp_lang_util.hpp
connectDiscoveredDevice
static void connectDiscoveredDevice(std::shared_ptr< BTDevice > device)
Definition: dbt_scanner10.cpp:354
direct_bt::BTSecurityRegistry::Entry::sec_level
BTSecurityLevel sec_level
Definition: BTSecurityRegistry.hpp:48
direct_bt::BTGattService::toString
std::string toString() const noexcept override
Definition: BTGattService.cpp:66
direct_bt::BTDeviceRegistry::isWaitingForAnyDevice
bool isWaitingForAnyDevice() noexcept
Definition: BTDeviceRegistry.cpp:56
direct_bt::BTDevice::getGattServices
jau::darray< std::shared_ptr< BTGattService > > getGattServices() noexcept
Returns a list of shared GATTService available on this device if successful, otherwise returns an emp...
Definition: BTDevice.cpp:1525
direct_bt::BTGattHandler::isConnected
bool isConnected() const noexcept
Definition: BTGattHandler.hpp:253
initAdapter
static bool initAdapter(std::shared_ptr< BTAdapter > &adapter)
Definition: dbt_scanner10.cpp:643
direct_bt::SMPPairingState::NONE
@ NONE
No pairing in process.
MyGATTEventListener
Definition: dbt_scanner00.cpp:118
direct_bt::SMPPairingState::FEATURE_EXCHANGE_STARTED
@ FEATURE_EXCHANGE_STARTED
Phase 1: Pairing requested by initiating (master) device via SMPPairingMsg.
processReadyDevice
static void processReadyDevice(std::shared_ptr< BTDevice > device)
Definition: dbt_scanner10.cpp:425
direct_bt::BTDeviceRegistry::getProcessedDeviceCount
size_t getProcessedDeviceCount() noexcept
Definition: BTDeviceRegistry.cpp:88
direct_bt::HCIStatusCode::SUCCESS
@ SUCCESS
direct_bt::SMPKeyBin::remove
static bool remove(const std::string &path, const BDAddressAndType &addrAndType_)
Definition: SMPKeyBin.hpp:296
direct_bt::BTDevice::addStatusListener
bool addStatusListener(std::shared_ptr< AdapterStatusListener > l)
Add the given AdapterStatusListener to the list if not already present, intended to listen only for e...
Definition: BTDevice.cpp:248
direct_bt::BTAdapter::addDeviceToWhitelist
bool addDeviceToWhitelist(const BDAddressAndType &addressAndType, const HCIWhitelistConnectType ctype, const uint16_t conn_interval_min=12, const uint16_t conn_interval_max=12, const uint16_t conn_latency=0, const uint16_t supervision_timeout=getHCIConnSupervisorTimeout(0, 15))
Add the given device to the adapter's autoconnect whitelist.
Definition: BTAdapter.cpp:522
direct_bt::BTSecurityRegistry::Entry::NO_PASSKEY
static constexpr int NO_PASSKEY
Definition: BTSecurityRegistry.hpp:43
myChangedAdapterSetFunc
static bool myChangedAdapterSetFunc(const bool added, std::shared_ptr< BTAdapter > &adapter)
Definition: dbt_scanner10.cpp:668
direct_bt::BTDevice::getGattHandler
std::shared_ptr< BTGattHandler > getGattHandler() noexcept
Returns the connected GATTHandler or nullptr, see connectGATT(), getGattService() and disconnect().
Definition: BTDevice.cpp:1520
deviceReadyCount
static std::atomic< int > deviceReadyCount
Definition: dbt_scanner10.cpp:109
direct_bt::BTGattChar::value_type
std::unique_ptr< const uuid_t > value_type
Definition: BTGattChar.hpp:189
direct_bt::SMPKeyBin::createAndWrite
static bool createAndWrite(const BTDevice &device, const std::string &path, const bool overwrite, const bool verbose_)
Create a new SMPKeyBin instance on the fly based upon given BTDevice's BTSecurityLevel,...
Definition: SMPKeyBin.cpp:79
startDiscovery
static bool startDiscovery(BTAdapter *a, std::string msg)
Definition: dbt_scanner10.cpp:637
direct_bt::BTGattChar::writeValueNoResp
bool writeValueNoResp(const TROOctets &value)
BT Core Spec v5.2: Vol 3, Part G GATT: 4.9.1 Write Characteristic Value Without Response.
Definition: BTGattChar.cpp:327
direct_bt::BTSecurityRegistry::Entry::passkey
int passkey
Definition: BTSecurityRegistry.hpp:51
direct_bt::BTGattChar::descriptorList
jau::darray< BTGattDescRef > descriptorList
List of Characteristic Descriptions as shared reference.
Definition: BTGattChar.hpp:192
direct_bt::BTDevice::getName
std::string const getName() const noexcept
Definition: BTDevice.cpp:124
deviceFound
std::shared_ptr< BTDevice > deviceFound
This C++ direct_bt scanner example is a TinyB backward compatible and not fully event driven.
Definition: dbt_scanner00.cpp:51
filter_policy
static const uint8_t filter_policy
Definition: dbt_scanner10.cpp:635
direct_bt::BTDeviceRegistry::isDeviceProcessed
bool isDeviceProcessed(const BDAddressAndType &a) noexcept
Definition: BTDeviceRegistry.cpp:84
direct_bt::BTDeviceRegistry::getWaitForDevicesCount
size_t getWaitForDevicesCount() noexcept
Definition: BTDeviceRegistry.cpp:59
direct_bt::POctets
Persistent octet data, i.e.
Definition: OctetTypes.hpp:451
direct_bt::BTAdapter::startDiscovery
HCIStatusCode startDiscovery(const bool keepAlive=true, const bool le_scan_active=false, const uint16_t le_scan_interval=24, const uint16_t le_scan_window=24, const uint8_t filter_policy=0x00)
Starts a new discovery session.
Definition: BTAdapter.cpp:679
direct_bt::BTDevice::unpair
HCIStatusCode unpair() noexcept
Unpairs this device from the adapter while staying connected.
Definition: BTDevice.cpp:1772
direct_bt::AdapterSetting::POWERED
@ POWERED
direct_bt::SMPPairingState
SMPPairingState
SMP Pairing Process state definition.
Definition: SMPTypes.hpp:101
direct_bt::BTSecurityRegistry::Entry::getSecLevel
constexpr const BTSecurityLevel & getSecLevel() const noexcept
Definition: BTSecurityRegistry.hpp:62
KEEP_CONNECTED
static bool KEEP_CONNECTED
Definition: dbt_scanner10.cpp:113
direct_bt::BTGattHandler::number
static constexpr int number(const Defaults d)
Definition: BTGattHandler.hpp:149
direct_bt::isAdapterSettingBitSet
constexpr bool isAdapterSettingBitSet(const AdapterSetting mask, const AdapterSetting bit) noexcept
Definition: BTTypes1.hpp:177
resetAdapter
static void resetAdapter(BTAdapter *a, int mode)
Definition: dbt_scanner10.cpp:626
direct_bt::LE_PHYs
LE_PHYs
LE Transport PHY bit values.
Definition: BTTypes0.hpp:175
direct_bt::BDAddressType::BDADDR_LE_PUBLIC
@ BDADDR_LE_PUBLIC
Bluetooth LE public address.
direct_bt::BDAddressAndType
Unique Bluetooth EUI48 address and BDAddressType tuple.
Definition: BTAddress.hpp:417
test
void test()
Definition: dbt_scanner10.cpp:682
direct_bt::BTDevice::getAdapter
BTAdapter & getAdapter() const
Returns the managing adapter.
Definition: BTDevice.hpp:243
direct_bt::BTGattDesc
BT Core Spec v5.2: Vol 3, Part G GATT: 3.3.3 Characteristic Descriptor.
Definition: BTGattDesc.hpp:62
direct_bt::BTMode
BTMode
Bluetooth adapter operating mode.
Definition: BTTypes0.hpp:56
direct_bt::GattTemperatureMeasurement::toString
std::string toString() const noexcept
Definition: GATTNumbers.cpp:453
direct_bt::SMPPairingState::COMPLETED
@ COMPLETED
Phase 3: Key & value distribution completed by responding (slave) device sending SMPIdentInfoMsg (#1)...
direct_bt::BTGattChar::Listener
BTGattChar event listener for notification and indication events.
Definition: BTGattChar.hpp:122
direct_bt::BTSecurityRegistry::Entry::isSecurityAutoEnabled
constexpr bool isSecurityAutoEnabled() const noexcept
Definition: BTSecurityRegistry.hpp:65
charIdentifier
static std::string charIdentifier
Definition: dbt_scanner10.cpp:120