diff options
author | Sven Gothel <[email protected]> | 2020-10-25 10:33:12 +0100 |
---|---|---|
committer | Sven Gothel <[email protected]> | 2020-10-25 10:33:12 +0100 |
commit | 5f6fdee65c34337b1ade27de59192dbfe613317d (patch) | |
tree | a4e674e07e9d516ef3cea2bf6d67dcb93bf87bd6 /examples | |
parent | 530db7b53364c7ba3460d2db8bde53bf2a20ef3f (diff) |
Add ChangedAdapterSetCallback (C++), ChangedAdapterSetListener (Java) for [DBT|Bluetooth]Manager, enabling fully event driven workflow w/ adapter add/remove
Diffstat (limited to 'examples')
-rw-r--r-- | examples/direct_bt_scanner10/dbt_scanner10.cpp | 111 | ||||
-rw-r--r-- | examples/java/DBTScanner10.java | 115 |
2 files changed, 156 insertions, 70 deletions
diff --git a/examples/direct_bt_scanner10/dbt_scanner10.cpp b/examples/direct_bt_scanner10/dbt_scanner10.cpp index 9a9d162b..4c95f823 100644 --- a/examples/direct_bt_scanner10/dbt_scanner10.cpp +++ b/examples/direct_bt_scanner10/dbt_scanner10.cpp @@ -506,16 +506,20 @@ static bool startDiscovery(DBTAdapter *a, std::string msg) { return HCIStatusCode::SUCCESS == status; } -static std::shared_ptr<DBTAdapter> createAdapter(const int dev_id0) { +static std::shared_ptr<DBTAdapter> createAdapter(const int dev_id0, const bool validate_dev_id) { // pre-validate dev_id availability int dev_id; - DBTManager & mngr = DBTManager::get(BTMode::LE); - if( 0 > dev_id0 ) { - dev_id = mngr.getDefaultAdapterDevID(); - } else if( nullptr != mngr.getAdapterInfo(dev_id0) ) { - dev_id = dev_id0; + if( validate_dev_id ) { + DBTManager & mngr = DBTManager::get(BTMode::LE); + if( 0 > dev_id0 ) { + dev_id = mngr.getDefaultAdapterDevID(); + } else if( nullptr != mngr.getAdapterInfo(dev_id0) ) { + dev_id = dev_id0; + } else { + dev_id = -1; + } } else { - dev_id = -1; + dev_id = dev_id0; } if( 0 > dev_id ) { fprintf(stderr, "Adapter not available (1): Request %d, deduced %d\n", dev_id0, dev_id); @@ -531,7 +535,6 @@ static std::shared_ptr<DBTAdapter> createAdapter(const int dev_id0) { fprintf(stderr, "Adapter not powered (2): %s\n", adapter->toString().c_str()); return nullptr; } - fprintf(stderr, "Using adapter: %s\n", adapter->toString().c_str()); adapter->addStatusListener(std::shared_ptr<AdapterStatusListener>(new MyAdapterStatusListener())); @@ -548,12 +551,68 @@ static std::shared_ptr<DBTAdapter> createAdapter(const int dev_id0) { return adapter; } -void test(int dev_id) { +static jau::cow_vector<std::shared_ptr<DBTAdapter>> adapterList; + +static std::shared_ptr<DBTAdapter> getAdapter(const uint16_t dev_id) { + std::shared_ptr<std::vector<std::shared_ptr<DBTAdapter>>> snapshot = adapterList.get_snapshot(); + auto begin = snapshot->begin(); + auto it = std::find_if(begin, snapshot->end(), [&](std::shared_ptr<DBTAdapter> const& p) -> bool { + return p->dev_id == dev_id; + }); + if ( it == std::end(*snapshot) ) { + return nullptr; + } else { + return *it; + } +} +static int removeAdapter(const uint16_t dev_id) { + const std::lock_guard<std::recursive_mutex> lock(adapterList.get_write_mutex()); + std::shared_ptr<std::vector<std::shared_ptr<DBTAdapter>>> store = adapterList.copy_store(); + int count = 0; + for(auto it = store->begin(); it != store->end(); ) { + if ( (*it)->dev_id == dev_id ) { + it = store->erase(it); + count++; + } else { + ++it; + } + } + if( 0 < count ) { + adapterList.set_store(std::move(store)); + } + return count; +} + +static bool myChangedAdapterSetFunc(const bool added, const AdapterInfo& adapterInfo) { + if( added ) { + std::shared_ptr<DBTAdapter> pre = getAdapter(adapterInfo.dev_id); + if( nullptr != pre ) { + fprintf(stderr, "****** Adapter ADDED__: Not new %s\n", pre->toString().c_str()); + } else { + if( adapterInfo.isCurrentSettingBitSet(AdapterSetting::POWERED) ) { + std::shared_ptr<DBTAdapter> adapter = createAdapter(adapterInfo.dev_id, false /* validate_dev_id */); + if( nullptr != adapter ) { + adapterList.push_back(adapter); + fprintf(stderr, "****** Adapter ADDED__: Created %s\n", adapter->toString().c_str()); + } + } else { + fprintf(stderr, "****** Adapter ADDED__: Ignored %s\n", adapterInfo.toString().c_str()); + } + } + } else { + const int count = removeAdapter(adapterInfo.dev_id); + fprintf(stderr, "****** Adapter REMOVED: count %d, %s\n", count, adapterInfo.toString().c_str()); + } + return true; +} + +void test() { bool done = false; timestamp_t0 = getCurrentMilliseconds(); - std::shared_ptr<DBTAdapter> adapter = createAdapter(dev_id); + DBTManager & mngr = DBTManager::get(BTMode::LE); + mngr.addChangedAdapterSetCallback(myChangedAdapterSetFunc); while( !done ) { if( 0 == MULTI_MEASUREMENTS || @@ -566,28 +625,22 @@ void test(int dev_id) { printDevicesProcessed("****** DevicesProcessed "); done = true; } else { - // validate existing adapter - if( nullptr != adapter ) { - if( !adapter->isValid() /* || !adapter->isPowered() */ ) { - // In case of removed adapter, not just powered-off (soft-reset) - // We could also close adapter on !isPowered() here, but its not required - adapter operational. - adapter->close(); - adapter = nullptr; // purge - } - } - // re-create adapter if required - if( nullptr == adapter ) { - adapter = createAdapter(dev_id); - } std::this_thread::sleep_for(std::chrono::milliseconds(2000)); } } - fprintf(stderr, "****** EOL Adapter's Devices - pre close: %s\n", adapter->toString().c_str()); - if( nullptr != adapter ) { + + jau::for_each_cow(adapterList, [](std::shared_ptr<DBTAdapter>& adapter) { + fprintf(stderr, "****** EOL Adapter's Devices - pre close: %s\n", adapter->toString().c_str()); adapter->printSharedPtrListOfDevices(); adapter->close(); fprintf(stderr, "****** EOL Adapter's Devices - post close\n"); adapter->printSharedPtrListOfDevices(); + }); + fprintf(stderr, "****** EOL Adapter's Devices - post close all\n"); + + { + int count = mngr.removeChangedAdapterSetCallback(myChangedAdapterSetFunc); + fprintf(stderr, "****** EOL Removed ChangedAdapterSetCallback %d\n", count); } } @@ -595,7 +648,6 @@ void test(int dev_id) { int main(int argc, char *argv[]) { - int dev_id = -1; // default BTMode btMode = BTMode::NONE; bool waitForEnter=false; @@ -612,8 +664,6 @@ int main(int argc, char *argv[]) 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("-dev_id", argv[i]) && argc > (i+1) ) { - dev_id = atoi(argv[++i]); } else if( !strcmp("-btmode", argv[i]) && argc > (i+1) ) { btMode = getBTMode(argv[++i]); if( BTMode::NONE != btMode ) { @@ -650,7 +700,7 @@ int main(int argc, char *argv[]) } fprintf(stderr, "pid %d\n", getpid()); - fprintf(stderr, "Run with '[-dev_id <adapter-index>] [-btmode LE|BREDR|DUAL] " + fprintf(stderr, "Run with '[-btmode LE|BREDR|DUAL] " "[-disconnect] [-enableGATTPing] [-count <number>] [-single] [-show_update_events] [-quiet] " "[-resetEachCon connectionCount] " "(-mac <device_address>)* (-wl <device_address>)* " @@ -670,7 +720,6 @@ int main(int argc, char *argv[]) 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, "dev_id %d\n", dev_id); fprintf(stderr, "btmode %s\n", getBTModeString(btMode).c_str()); printList( "waitForDevice: ", waitForDevices); @@ -680,7 +729,7 @@ int main(int argc, char *argv[]) getchar(); } fprintf(stderr, "****** TEST start\n"); - test(dev_id); + test(); fprintf(stderr, "****** TEST end\n"); if( true ) { // Just for testing purpose, i.e. triggering DBTManager::close() within the test controlled app, diff --git a/examples/java/DBTScanner10.java b/examples/java/DBTScanner10.java index 7c490f24..78283bc9 100644 --- a/examples/java/DBTScanner10.java +++ b/examples/java/DBTScanner10.java @@ -30,7 +30,10 @@ import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; +import java.util.function.Predicate; import org.tinyb.AdapterSettings; import org.tinyb.BluetoothAdapter; @@ -54,6 +57,7 @@ import org.tinyb.HCIStatusCode; import org.tinyb.HCIWhitelistConnectType; import org.tinyb.PairingMode; import org.tinyb.ScanType; +import org.tinyb.BluetoothManager.ChangedAdapterSetListener; import direct_bt.tinyb.DBTManager; @@ -87,8 +91,6 @@ public class DBTScanner10 { boolean SHOW_UPDATE_EVENTS = false; boolean QUIET = false; - int dev_id = -1; // use default - int shutdownTest = 0; static void printf(final String format, final Object... args) { @@ -525,25 +527,10 @@ public class DBTScanner10 { return HCIStatusCode.SUCCESS == status; } - private BluetoothAdapter createAdapter(final BluetoothManager mngr, final int dev_id0) { - BluetoothAdapter adapter; - if( 0 > dev_id0 ) { - adapter = mngr.getDefaultAdapter(); - } else { - adapter = mngr.getAdapter(dev_id0); - if( !adapter.isPowered() ) { - adapter = mngr.getDefaultAdapter(); - } - } - final int dev_id = null != adapter ? adapter.getDevID() : -1; - if( 0 > dev_id ) { - println("Adapter not available (1): Request "+dev_id0+", deduced "+dev_id); - return null; - } - + private boolean initAdapter(final BluetoothAdapter adapter) { if( !adapter.isPowered() ) { // should have been covered above println("Adapter not powered (2): "+adapter.toString()); - return null; + return false; } println("Using adapter: "+adapter.toString()); @@ -564,18 +551,71 @@ public class DBTScanner10 { } } else { if( !startDiscovery(adapter, "kick-off") ) { + return false; } } - return adapter; + return true; } - public void runTest(final BluetoothManager manager) { - BluetoothAdapter adapter = createAdapter(manager, dev_id); + private final List<BluetoothAdapter> adapters = new CopyOnWriteArrayList<BluetoothAdapter>(); + + @SuppressWarnings("unused") + private BluetoothAdapter getAdapter(final int dev_id) { + for( int i=0; i<adapters.size(); i++) { + final BluetoothAdapter a = adapters.get(i); + if( dev_id == a.getDevID() ) { + return a; + } + } + return null; + } + + private int removeAdapter(final int dev_id) { + // Using removeIf allows performing test on all object and remove within one write-lock cycle + final int count[] = { 0 }; + adapters.removeIf(new Predicate<BluetoothAdapter>() { + @Override + public boolean test(final BluetoothAdapter t) { + if( dev_id == t.getDevID() ) { + count[0]++; + return true; + } + return false; + } + }); + return count[0]; + } + private final BluetoothManager.ChangedAdapterSetListener myChangedAdapterSetListener = + new BluetoothManager.ChangedAdapterSetListener() { + @Override + public void adapterAdded(final BluetoothAdapter adapter) { + if( adapter.isPowered() ) { + if( initAdapter( adapter ) ) { + adapters.add(adapter); + println("****** Adapter ADDED__: NewInit " + adapter); + } else { + println("****** Adapter ADDED__: Failed_ " + adapter); + } + } else { + println("****** Adapter ADDED__: Ignored " + adapter); + } + } + + @Override + public void adapterRemoved(final BluetoothAdapter adapter) { + final int count = removeAdapter(adapter.getDevID()); + println("****** Adapter REMOVED: count "+count+", " + adapter); + } + }; + + public void runTest(final BluetoothManager manager) { timestamp_t0 = BluetoothUtils.currentTimeMillis(); boolean done = false; + manager.addChangedAdapterSetListener(myChangedAdapterSetListener); + while( !done ) { if( 0 == MULTI_MEASUREMENTS.get() || ( -1 == MULTI_MEASUREMENTS.get() && !waitForDevices.isEmpty() && devicesProcessed.containsAll(waitForDevices) ) @@ -587,19 +627,6 @@ public class DBTScanner10 { println("****** DevicesProcessed "+Arrays.toString(devicesProcessed.toArray())); done = true; } else { - // validate existing adapter - if( null != adapter ) { - if( !adapter.isValid() /* || !adapter.isPowered() */ ) { - // In case of removed adapter, not just powered-off (soft-reset) - // We could also close adapter on !isPowered() here, but its not required - adapter operational. - adapter.close(); - adapter = null; // purge - } - } - // re-create adapter if required - if( null == adapter ) { - adapter = createAdapter(manager, dev_id); - } try { Thread.sleep(2000); } catch (final InterruptedException e) { @@ -608,6 +635,19 @@ public class DBTScanner10 { } } + adapters.forEach(new Consumer<BluetoothAdapter>() { + @Override + public void accept(final BluetoothAdapter a) { + println("****** EOL Adapter's Devices - pre_ close: " + a); + a.close(); + println("****** EOL Adapter's Devices - post close: " + a); + } } ); + + { + final int count = manager.removeChangedAdapterSetListener(myChangedAdapterSetListener); + println("****** EOL Removed ChangedAdapterSetCallback " + count); + } + // All implicit via destructor or shutdown hook! // manager.shutdown(); /* implies: adapter.close(); */ } @@ -663,8 +703,6 @@ public class DBTScanner10 { test.SHOW_UPDATE_EVENTS = true; } else if( arg.equals("-quiet") ) { test.QUIET = true; - } else if( arg.equals("-dev_id") && args.length > (i+1) ) { - test.dev_id = Integer.valueOf(args[++i]).intValue(); } else if( arg.equals("-shutdown") && args.length > (i+1) ) { test.shutdownTest = Integer.valueOf(args[++i]).intValue(); } else if( arg.equals("-mac") && args.length > (i+1) ) { @@ -690,7 +728,7 @@ public class DBTScanner10 { test.RESET_ADAPTER_EACH_CONN = Integer.valueOf(args[++i]).intValue(); } } - println("Run with '[-default_dev_id <adapter-index>] [-dev_id <adapter-index>] [-btmode LE|BREDR|DUAL] "+ + println("Run with '[-btmode LE|BREDR|DUAL] "+ "[-bluetoothManager <BluetoothManager-Implementation-Class-Name>] "+ "[-disconnect] [-enableGATTPing] [-count <number>] [-single] (-char <uuid>)* [-show_update_events] [-quiet] "+ "[-resetEachCon connectionCount] "+ @@ -714,7 +752,6 @@ public class DBTScanner10 { println("SHOW_UPDATE_EVENTS "+test.SHOW_UPDATE_EVENTS); println("QUIET "+test.QUIET); - println("dev_id "+test.dev_id); println("waitForDevice: "+Arrays.toString(test.waitForDevices.toArray())); println("characteristicList: "+Arrays.toString(test.charIdentifierList.toArray())); |