Direct-BT v3.3.0-1-gc2d430c
Direct-BT - Direct Bluetooth Programming.
BTAdapter.hpp
Go to the documentation of this file.
1/*
2 * Author: Sven Gothel <sgothel@jausoft.com>
3 * Copyright (c) 2020 Gothel Software e.K.
4 * Copyright (c) 2020 ZAFENA AB
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining
7 * a copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sublicense, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be
15 * included in all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 */
25
26#ifndef BT_ADAPTER_HPP_
27#define BT_ADAPTER_HPP_
28
29#include <cstring>
30#include <string>
31#include <memory>
32#include <cstdint>
33
34#include <mutex>
35#include <atomic>
36
37#include <jau/darray.hpp>
38#include <jau/cow_darray.hpp>
39#include <jau/simple_timer.hpp>
40#include "BTTypes1.hpp"
41
42#include "BTDevice.hpp"
43
44#include "HCIHandler.hpp"
45
46#include "DBGattServer.hpp"
47
48#include "SMPKeyBin.hpp"
49#include "jau/int_types.hpp"
50
51namespace direct_bt {
52
53 /** @defgroup DBTUserAPI Direct-BT General User Level API
54 * General User level Direct-BT API types and functionality, [see Direct-BT Overview](namespacedirect__bt.html#details).
55 *
56 * @{
57 */
58
59 class BTAdapter; // forward
60 class BTManager; // forward
61 typedef std::shared_ptr<BTManager> BTManagerRef;
62
63 /**
64 * Discovery policy defines the BTAdapter discovery mode after connecting a remote BTDevice:
65 * - turned-off (DiscoveryPolicy::AUTO_OFF)
66 * - paused until all connected BTDevice become disconnected, effectively until AdapterStatusListener::deviceDisconnected() (DiscoveryPolicy::PAUSE_CONNECTED_UNTIL_DISCONNECTED).
67 * - paused until all connected devices reach readiness inclusive optional SMP pairing (~120ms) and GATT service discovery (~700ms), effectively until AdapterStatusListener::deviceReady(). (DiscoveryPolicy::PAUSE_CONNECTED_UNTIL_READY, default)
68 * - paused until all connected devices are optionally SMP paired (~120ms), exclusive GATT service discovery (~700ms -> ~1200ms, DiscoveryPolicy::PAUSE_CONNECTED_UNTIL_PAIRED)
69 * - always enabled, i.e. re-enabled if automatically turned-off by HCI host OS as soon as possible (DiscoveryPolicy::ALWAYS_ON)
70 *
71 * Policy is set via BTAdapter::startDiscovery()
72 *
73 * Default is DiscoveryPolicy::PAUSE_CONNECTED_UNTIL_READY, as it has been shown that continuous advertising
74 * reduces the bandwidth for the initial bring-up time including GATT service discovery considerably.
75 * Continuous advertising would increase the readiness lag of the remote device until AdapterStatusListener::deviceReady().
76 *
77 * In case users favors faster parallel discovery of new remote devices and hence a slower readiness,
78 * DiscoveryPolicy::PAUSE_CONNECTED_UNTIL_PAIRED or even DiscoveryPolicy::ALWAYS_ON can be used.
79 *
80 * @since 2.5.0
81 */
82 enum class DiscoveryPolicy : uint8_t {
83 /** Turn off discovery when connected and leave discovery disabled, if turned off by host system. */
84 AUTO_OFF = 0,
85 /**
86 * Pause discovery until all connected BTDevice become disconnected,
87 * effectively until AdapterStatusListener::deviceDisconnected().
88 */
90 /**
91 * Pause discovery until all connected BTDevice reach readiness inclusive optional SMP pairing (~120ms) without GATT service discovery (~700ms),
92 * effectively until AdapterStatusListener::deviceReady(). This is the default!
93 */
95 /** Pause discovery until all connected BTDevice are optionally SMP paired (~120ms) without GATT service discovery (~700ms). */
97 /** Always keep discovery enabled, i.e. re-enabled if automatically turned-off by HCI host OS as soon as possible. */
98 ALWAYS_ON = 4
99 };
100 constexpr uint8_t number(const DiscoveryPolicy rhs) noexcept {
101 return static_cast<uint8_t>(rhs);
102 }
103 constexpr DiscoveryPolicy to_DiscoveryPolicy(const uint8_t v) noexcept {
104 if( 1 <= v && v <= 4 ) {
105 return static_cast<DiscoveryPolicy>(v);
106 }
108 }
109 std::string to_string(const DiscoveryPolicy v) noexcept;
110
111 /**
112 * {@link BTAdapter} status listener for remote {@link BTDevice} discovery events: Added, updated and removed;
113 * as well as for certain {@link BTAdapter} events.
114 * <p>
115 * User implementations shall return as early as possible to avoid blocking the event-handler thread,
116 * if not specified within the methods otherwise (see AdapterStatusListener::deviceReady()).<br>
117 * Especially complex mutable operations on BTDevice or BTAdapter should be issued off-thread!
118 * </p>
119 * <p>
120 * A listener instance may be attached to a {@link BTAdapter} via
121 * {@link BTAdapter::addStatusListener(const AdapterStatusListenerRef&)}.
122 * </p>
123 * <p>
124 * The listener receiver maintains a unique set of listener instances without duplicates.
125 * </p>
126 */
128 public:
129 /**
130 * BTAdapter setting(s) changed.
131 * @param adapter the adapter which settings have changed.
132 * @param oldmask the previous settings mask. AdapterSetting::NONE indicates the initial setting notification, see BTAdapter::addStatusListener().
133 * @param newmask the new settings mask
134 * @param changedmask the changes settings mask. AdapterSetting::NONE indicates the initial setting notification, see BTAdapter::addStatusListener().
135 * @param timestamp the time in monotonic milliseconds when this event occurred. See BasicTypes::getCurrentMilliseconds().
136 */
137 virtual void adapterSettingsChanged(BTAdapter &adapter, const AdapterSetting oldmask, const AdapterSetting newmask,
138 const AdapterSetting changedmask, const uint64_t timestamp) {
139 (void)adapter;
140 (void)oldmask;
141 (void)newmask;
142 (void)changedmask;
143 (void)timestamp;
144 }
145
146 /**
147 * BTAdapter's discovery state has changed, i.e. enabled or disabled.
148 * @param adapter the adapter which discovering state has changed.
149 * @param currentMeta the current meta ScanType
150 * @param changedType denotes the changed native ScanType
151 * @param changedEnabled denotes whether the changed native ScanType has been enabled or disabled
152 * @param policy the current DiscoveryPolicy of the BTAdapter, chosen via BTAdapter::startDiscovery()
153 * @param timestamp the time in monotonic milliseconds when this event occurred. See BasicTypes::getCurrentMilliseconds().
154 *
155 * changeScanType(const ScanType current, const bool enable, const ScanType enableChanged) noexcept {
156 */
157 virtual void discoveringChanged(BTAdapter &adapter, const ScanType currentMeta, const ScanType changedType, const bool changedEnabled, const DiscoveryPolicy policy, const uint64_t timestamp) {
158 (void)adapter;
159 (void)currentMeta;
160 (void)changedType;
161 (void)changedEnabled;
162 (void)policy;
163 (void)timestamp;
164 }
165
166 /**
167 * A remote BTDevice has been newly discovered.
168 * <p>
169 * The boolean return value informs the adapter whether the device shall be made persistent for connection `true`,
170 * or that it can be discarded `false`.<br>
171 * If no registered AdapterStatusListener::deviceFound() implementation returns `true`,
172 * the device instance will be removed from all internal lists and can no longer being used.<br>
173 * If any registered AdapterStatusListener::deviceFound() implementation returns `true`,
174 * the device will be made persistent, is ready to connect and BTDevice::remove() shall be called after usage.
175 * </p>
176 *
177 * BTDevice::unpair() has been called already.
178 *
179 * @param device the found remote device
180 * @param timestamp the time in monotonic milliseconds when this event occurred. See BasicTypes::getCurrentMilliseconds().
181 * @return true if the device shall be made persistent and BTDevice::remove() issued later. Otherwise false to remove device right away.
182 * @see BTDevice::unpair()
183 * @see BTDevice::getEIR()
184 */
185 virtual bool deviceFound(const BTDeviceRef& device, const uint64_t timestamp) {
186 (void)device;
187 (void)timestamp;
188 return false;
189 }
190
191 /**
192 * An already discovered remote BTDevice has been updated.
193 * @param device the updated remote device
194 * @param updateMask the update mask of changed data
195 * @param timestamp the time in monotonic milliseconds when this event occurred. See BasicTypes::getCurrentMilliseconds().
196 *
197 * @see BTDevice::getEIR()
198 */
199 virtual void deviceUpdated(const BTDeviceRef& device, const EIRDataType updateMask, const uint64_t timestamp) {
200 (void)device;
201 (void)updateMask;
202 (void)timestamp;
203 }
204
205 /**
206 * Remote BTDevice got connected
207 *
208 * If a BTRole::Master BTDevice gets connected, BTDevice::unpair() has been called already.
209 *
210 * @param device the remote device which has been connected, holding the new connection handle.
211 * @param discovered `true` if discovered before connected and deviceFound() has been sent (default), otherwise `false`.
212 * @param timestamp the time in monotonic milliseconds when this event occurred. See BasicTypes::getCurrentMilliseconds().
213 * @see BTDevice::unpair()
214 * @since 2.6.6
215 */
216 virtual void deviceConnected(const BTDeviceRef& device, const bool discovered, const uint64_t timestamp) {
217 (void)device;
218 (void)discovered;
219 (void)timestamp;
220 }
221
222 /**
223 * An already connected remote BTDevice's ::SMPPairingState has changed.
224 * @param device the remote device which PairingMode has been changed.
225 * @param state the current ::SMPPairingState of the connected device, see BTDevice::getCurrentPairingState()
226 * @param mode the current ::PairingMode of the connected device, see BTDevice::getCurrentPairingMode()
227 * @param timestamp the time in monotonic milliseconds when this event occurred. See BasicTypes::getCurrentMilliseconds().
228 * @see BTDevice::setPairingPasskey()
229 * @see BTDevice::setPairingNumericComparison()
230 */
231 virtual void devicePairingState(const BTDeviceRef& device, const SMPPairingState state, const PairingMode mode, const uint64_t timestamp) {
232 (void)device;
233 (void)state;
234 (void)mode;
235 (void)timestamp;
236 }
237
238 /**
239 * Remote BTDevice is ready for user (GATT) processing, i.e. already connected, optionally (SMP) paired.
240 *
241 * In case of a LE connection to a remote BTDevice in BTRole::Slave, a GATT server (GATTRole::Server),
242 * user needs to call BTDevice::getGattServices() to have GATT MTU size negotiated and GATT services discovered.
243 * <p>
244 * Method is being called from a dedicated native thread, hence restrictions on method duration and complex mutable operations don't apply here.
245 * </p>
246 * @param device the remote device ready to use
247 * @param timestamp the time in monotonic milliseconds when this event occurred. See BasicTypes::getCurrentMilliseconds().
248 * @see ::SMPPairingState::COMPLETED
249 * @see BTDevice::getGattServices()
250 */
251 virtual void deviceReady(const BTDeviceRef& device, const uint64_t timestamp) {
252 (void)device;
253 (void)timestamp;
254 }
255
256 /**
257 * Remote BTDevice got disconnected
258 *
259 * BTDevice::unpair() has been called already.
260 *
261 * @param device the remote device which has been disconnected with zeroed connection handle.
262 * @param reason the HCIStatusCode reason for disconnection
263 * @param handle the disconnected connection handle, which has been unassigned from the device already
264 * @param timestamp the time in monotonic milliseconds when this event occurred. See BasicTypes::getCurrentMilliseconds().
265 * @see BTDevice::unpair()
266 */
267 virtual void deviceDisconnected(const BTDeviceRef& device, const HCIStatusCode reason, const uint16_t handle, const uint64_t timestamp) {
268 (void)device;
269 (void)reason;
270 (void)handle;
271 (void)timestamp;
272 }
273
274 ~AdapterStatusListener() noexcept override = default;
275
276 std::string toString() const noexcept override { return "AdapterStatusListener["+jau::to_hexstring(this)+"]"; }
277
278 std::string get_java_class() const noexcept override {
279 return java_class();
280 }
281 static std::string java_class() noexcept {
282 return std::string(JAVA_MAIN_PACKAGE "AdapterStatusListener");
283 }
284
285 /**
286 * Default comparison operator, merely testing for same memory reference.
287 * <p>
288 * Specializations may override.
289 * </p>
290 */
291 virtual bool operator==(const AdapterStatusListener& rhs) const
292 { return this == &rhs; }
293
294 bool operator!=(const AdapterStatusListener& rhs) const
295 { return !(*this == rhs); }
296 };
297 typedef std::shared_ptr<AdapterStatusListener> AdapterStatusListenerRef;
298
299 // *************************************************
300 // *************************************************
301 // *************************************************
302
303 /**
304 * BTAdapter represents one local Bluetooth Controller.
305 *
306 * @anchor BTAdapterRoles
307 * Local BTAdapter roles (see getRole()):
308 *
309 * - {@link BTRole::Master}: The local adapter is discovering remote ::BTRole::Slave {@link BTDevice}s and may initiate connections. Enabled via startDiscovery(), but also per default at construction.
310 * - {@link BTRole::Slave}: The local adapter is advertising to remote ::BTRole::Master {@link BTDevice}s and may accept connections. Enabled explicitly via startAdvertising() until startDiscovery().
311 *
312 * Note the remote {@link BTDevice}'s [opposite role](@ref BTDeviceRoles).
313 *
314 * Controlling Environment variables:
315 * - 'direct_bt.debug.adapter.event': Debug messages about events, see debug_events
316 *
317 * @see BTDevice
318 * @see @ref BTDeviceRoles
319 * @see @ref BTGattHandlerRoles
320 * @see [Bluetooth Specification](https://www.bluetooth.com/specifications/bluetooth-core-specification/)
321 * @see [Direct-BT Overview](namespacedirect__bt.html#details)
322 */
323 class BTAdapter : public BTObject
324 {
325 private:
326 friend BTManager;
327
328 const bool debug_event, debug_lock;
329 BTManagerRef mgmt;
330 std::atomic_bool adapter_operational;
331 AdapterInfo adapterInfo;
332
333 /** Flag signaling whether initialize() has been called, regardless of success. */
334 jau::sc_atomic_bool adapter_initialized;
335 /** Flag signaling whether adapter was powered-off at initialize() */
336 jau::sc_atomic_bool adapter_poweredoff_at_init;
337
338 LE_Features le_features;
339
340 /** BT5: True if HCI_LE_Set_Extended_Scan_Parameters and HCI_LE_Set_Extended_Scan_Enable is supported (Bluetooth 5.0). */
341 bool hci_uses_ext_scan;
342 /** BT5: True if HCI_LE_Extended_Create_Connection is supported (Bluetooth 5.0). */
343 bool hci_uses_ext_conn;
344 /** BT5: True if HCI_LE_Extended_Advertising Data is supported (Bluetooth 5.0). */
345 bool hci_uses_ext_adv;
346
347 /**
348 * Either the adapter's initially reported public identity address or a random address setup via HCI before discovery or advertising.
349 */
350 BDAddressAndType visibleAddressAndType;
351 HCILEOwnAddressType visibleMACType;
352 MgmtIdentityResolvingKey privacyIRK;
353
354 public:
356
357 /**
358 * Adapter's internal temporary device id.
359 * <p>
360 * The internal device id is constant across the adapter lifecycle,
361 * but may change after its destruction.
362 */
363 const uint16_t dev_id;
364
365 private:
366 jau::ordered_atomic<BTRole, std::memory_order_relaxed> btRole; // = BTRole::Master (default)
367 HCIHandler hci;
368
370 jau::ordered_atomic<ScanType, std::memory_order_relaxed> currentMetaScanType; // = ScanType::NONE
371 jau::ordered_atomic<DiscoveryPolicy, std::memory_order_relaxed> discovery_policy; // = DiscoveryPolicy::PAUSE_CONNECTED_UNTIL_READY
372
373 jau::relaxed_atomic_bool scan_filter_dup; // = true;
374
375 SMPIOCapability iocap_defaultval = SMPIOCapability::UNSET;
376 const BTDevice* single_conn_device_ptr = nullptr;
377 std::mutex mtx_single_conn_device;
378 std::condition_variable cv_single_conn_device;
379
382
383 /** All discovered devices: Transient until removeDiscoveredDevices(), startDiscovery(). */
384 device_list_t discoveredDevices;
385 /** All connected devices: Transient until disconnect or removal. */
386 device_list_t connectedDevices;
387 /** All active shared devices: Persistent until removal. Final holder of BTDevice lifecycle! */
388 device_list_t sharedDevices;
389 /** All connected devices for which discovery has been paused. */
390 weak_device_list_t pausing_discovery_devices;
391 /** An SMP event watchdog for each device in pairing state */
392 jau::simple_timer smp_watchdog;
393 jau::fraction_i64 smp_timeoutfunc(jau::simple_timer& timer);
394
395 struct StatusListenerPair {
396 /** The actual listener */
398 /** The optional weak device reference. Weak, b/c it shall not block destruction */
399 std::weak_ptr<BTDevice> wbr_device;
400
401 bool match(const BTDeviceRef& device) const noexcept {
402 BTDeviceRef sda = wbr_device.lock();
403 if( nullptr != sda && nullptr != device ) {
404 return *sda == *device;
405 } else {
406 return true;
407 }
408 }
409 };
410 typedef jau::cow_darray<StatusListenerPair, size_type> statusListenerList_t;
411 static statusListenerList_t::equal_comparator adapterStatusListenerRefEqComparator;
412 statusListenerList_t statusListenerList;
413
414 // Storing SMPKeyBin entries, referenced by their remote address, i.e. BTDevice address.
415 std::string key_path;
416 typedef std::shared_ptr<SMPKeyBin> SMPKeyBinRef;
417 typedef jau::darray<SMPKeyBinRef, size_type> key_list_t;
418 key_list_t key_list;
419 BTSecurityLevel sec_level_server = BTSecurityLevel::UNSET;
421
422 DBGattServerRef gattServerData = nullptr;
423
424 mutable std::mutex mtx_discoveredDevices;
425 mutable std::mutex mtx_connectedDevices;
426 mutable std::mutex mtx_pausingDiscoveryDevices;
427 mutable std::mutex mtx_discovery;
428 mutable std::mutex mtx_sharedDevices; // final mutex of all BTDevice lifecycle
429 mutable std::mutex mtx_keys;
430 mutable jau::sc_atomic_bool sync_data;
431
432 bool updateDataFromHCI() noexcept;
433 bool updateDataFromAdapterInfo() noexcept;
434 bool initialSetup() noexcept;
435 bool enableListening(const bool enable) noexcept;
436
437 static BTDeviceRef findDevice(HCIHandler& hci, device_list_t & devices, const EUI48 & address, const BDAddressType addressType) noexcept;
438 static BTDeviceRef findDevice(device_list_t & devices, BTDevice const & device) noexcept;
439 static BTDeviceRef findWeakDevice(weak_device_list_t & devices, const EUI48 & address, const BDAddressType addressType) noexcept;
440 static BTDeviceRef findWeakDevice(weak_device_list_t & devices, BTDevice const & device) noexcept;
441 static void printDeviceList(const std::string& prefix, const BTAdapter::device_list_t& list) noexcept;
442 static void printWeakDeviceList(const std::string& prefix, BTAdapter::weak_device_list_t& list) noexcept;
443
444 /** Private class only for private make_shared(). */
445 class ctor_cookie { friend BTAdapter; ctor_cookie(const uint16_t secret) { (void)secret; } };
446
447 /** Private std::make_shared<BTAdapter>(..) vehicle for friends. */
448 static std::shared_ptr<BTAdapter> make_shared(const BTManagerRef& mgmt_, const AdapterInfo& adapterInfo_) {
449 return std::make_shared<BTAdapter>(BTAdapter::ctor_cookie(0), mgmt_, adapterInfo_);
450 }
451
452 /**
453 * Closes all device connections, stops discovery and cleans up all references.
454 * <p>
455 * To be called at
456 *
457 * - destructor or when powered off (active = true)
458 * - AdapterSetting changed, POWERED disabled, just powered off (active = false)
459 * - when `!isPowered()` is detected in methods (active = false)
460 * </p>
461 * @param active true if still powered and actively stopDiscovery and disconnect devices, otherwise this is a passive operation
462 */
463 void poweredOff(bool active, const std::string& msg) noexcept;
464
466 friend void BTDevice::remove() noexcept;
467 friend BTDevice::~BTDevice() noexcept;
468
469 friend std::shared_ptr<ConnectionInfo> BTDevice::getConnectionInfo() noexcept;
470 friend void BTDevice::sendMgmtEvDeviceDisconnected(std::unique_ptr<MgmtEvent> evt) noexcept;
471 friend HCIStatusCode BTDevice::disconnect(const HCIStatusCode reason) noexcept;
472 friend HCIStatusCode BTDevice::connectLE(uint16_t interval, uint16_t window,
473 uint16_t min_interval, uint16_t max_interval,
474 uint16_t latency, uint16_t supervision_timeout) noexcept;
475 friend HCIStatusCode BTDevice::connectBREDR(const uint16_t pkt_type, const uint16_t clock_offset, const uint8_t role_switch) noexcept;
476 friend void BTDevice::processL2CAPSetup(BTDeviceRef sthis);
477 friend bool BTDevice::updateIdentityAddress(BDAddressAndType const & identityAddress, bool sendEvent) noexcept;
478 friend bool BTDevice::updatePairingState(const BTDeviceRef& sthis, const MgmtEvent& evt, const HCIStatusCode evtStatus, SMPPairingState claimed_state) noexcept;
479 friend void BTDevice::hciSMPMsgCallback(const BTDeviceRef& sthis, const SMPPDUMsg& msg, const HCIACLData::l2cap_frame& source) noexcept;
480 friend void BTDevice::processDeviceReady(BTDeviceRef sthis, const uint64_t timestamp);
481 friend bool BTDevice::connectGATT(const std::shared_ptr<BTDevice>& sthis) noexcept;
482 friend jau::darray<BTGattServiceRef> BTDevice::getGattServices() noexcept;
483
484 bool lockConnect(const BTDevice & device, const bool wait, const SMPIOCapability io_cap) noexcept;
485 bool unlockConnect(const BTDevice & device) noexcept;
486 bool unlockConnectAny() noexcept;
487
488 bool addDevicePausingDiscovery(const BTDeviceRef & device) noexcept;
489 BTDeviceRef findDevicePausingDiscovery (const EUI48 & address, const BDAddressType & addressType) noexcept;
490 void clearDevicesPausingDiscovery() noexcept;
491 jau::nsize_t getDevicesPausingDiscoveryCount() noexcept;
492
493 bool addConnectedDevice(const BTDeviceRef & device) noexcept;
494 bool removeConnectedDevice(const BTDevice & device) noexcept;
495 size_type disconnectAllDevices(const HCIStatusCode reason=HCIStatusCode::REMOTE_USER_TERMINATED_CONNECTION ) noexcept;
496 BTDeviceRef findConnectedDevice (const EUI48 & address, const BDAddressType & addressType) noexcept;
497 jau::nsize_t getConnectedDeviceCount() const noexcept;
498
499 bool addDiscoveredDevice(BTDeviceRef const &device) noexcept;
500
501 void removeDevice(BTDevice & device) noexcept;
502
503 bool addSharedDevice(BTDeviceRef const &device) noexcept;
504 BTDeviceRef getSharedDevice(const BTDevice & device) noexcept;
505 void removeSharedDevice(const BTDevice & device) noexcept;
506
507 static SMPKeyBinRef findSMPKeyBin(key_list_t & keys, BDAddressAndType const & remoteAddress) noexcept;
508 static bool removeSMPKeyBin(key_list_t & keys, BDAddressAndType const & remoteAddress, const bool remove_file, const std::string& key_path_) noexcept;
509 SMPKeyBinRef findSMPKeyBin(BDAddressAndType const & remoteAddress) noexcept;
510 /** Adding a SMPKeyBin will remove previous entry. */
511 bool addSMPKeyBin(const SMPKeyBinRef& key, const bool write_file) noexcept;
512 bool removeSMPKeyBin(BDAddressAndType const & remoteAddress, const bool remove_file) noexcept;
513
514 L2CAPServer l2cap_att_srv;
515 jau::service_runner l2cap_service;
516 std::unique_ptr<L2CAPClient> l2cap_att;
517 std::mutex mtx_l2cap_att;
518 std::condition_variable cv_l2cap_att;
519 void l2capServerWork(jau::service_runner& sr) noexcept;
520 void l2capServerInit(jau::service_runner& sr) noexcept;
521 void l2capServerEnd(jau::service_runner& sr) noexcept;
522 std::unique_ptr<L2CAPClient> get_l2cap_connection(const std::shared_ptr<BTDevice>& device);
523
524 void mgmtEvNewSettingsMgmt(const MgmtEvent& e) noexcept;
525 void updateAdapterSettings(const bool off_thread, const AdapterSetting new_settings, const bool sendEvent, const uint64_t timestamp) noexcept;
526 void mgmtEvDeviceDiscoveringMgmt(const MgmtEvent& e) noexcept;
527 void mgmtEvLocalNameChangedMgmt(const MgmtEvent& e) noexcept;
528 void mgmtEvDeviceFoundHCI(const MgmtEvent& e) noexcept;
529
530 void mgmtEvPairDeviceCompleteMgmt(const MgmtEvent& e) noexcept;
531 void mgmtEvNewLongTermKeyMgmt(const MgmtEvent& e) noexcept;
532 void mgmtEvNewLinkKeyMgmt(const MgmtEvent& e) noexcept;
533 void mgmtEvNewIdentityResolvingKeyMgmt(const MgmtEvent& e) noexcept;
534
535 void mgmtEvHCIAnyHCI(const MgmtEvent& e) noexcept;
536 void mgmtEvMgmtAnyMgmt(const MgmtEvent& e) noexcept;
537 void mgmtEvDeviceDiscoveringHCI(const MgmtEvent& e) noexcept;
538 void mgmtEvDeviceConnectedHCI(const MgmtEvent& e) noexcept;
539 void mgmtEvDeviceConnectedMgmt(const MgmtEvent& e) noexcept;
540
541 void mgmtEvConnectFailedHCI(const MgmtEvent& e) noexcept;
542 void mgmtEvHCILERemoteUserFeaturesHCI(const MgmtEvent& e) noexcept;
543 void mgmtEvHCILEPhyUpdateCompleteHCI(const MgmtEvent& e) noexcept;
544 void mgmtEvDeviceDisconnectedHCI(const MgmtEvent& e) noexcept;
545
546 // Local BTRole::Slave
547 void mgmtEvLELTKReqEventHCI(const MgmtEvent& e) noexcept;
548 void mgmtEvLELTKReplyAckCmdHCI(const MgmtEvent& e) noexcept;
549 void mgmtEvLELTKReplyRejCmdHCI(const MgmtEvent& e) noexcept;
550
551 // Local BTRole::Master
552 void mgmtEvLEEnableEncryptionCmdHCI(const MgmtEvent& e) noexcept;
553 void mgmtEvHCIEncryptionChangedHCI(const MgmtEvent& e) noexcept;
554 void mgmtEvHCIEncryptionKeyRefreshCompleteHCI(const MgmtEvent& e) noexcept;
555
556 void updateDeviceDiscoveringState(const ScanType eventScanType, const bool eventEnabled) noexcept;
557 void mgmtEvDeviceDiscoveringAny(const ScanType eventScanType, const bool eventEnabled, const uint64_t eventTimestamp,
558 const bool hciSourced) noexcept;
559
560 void mgmtEvPinCodeRequestMgmt(const MgmtEvent& e) noexcept;
561 void mgmtEvUserConfirmRequestMgmt(const MgmtEvent& e) noexcept;
562 void mgmtEvUserPasskeyRequestMgmt(const MgmtEvent& e) noexcept;
563 void mgmtEvPasskeyNotifyMgmt(const MgmtEvent& e) noexcept;
564 void mgmtEvAuthFailedMgmt(const MgmtEvent& e) noexcept;
565 void mgmtEvDeviceUnpairedMgmt(const MgmtEvent& e) noexcept;
566
567 void hciSMPMsgCallback(const BDAddressAndType & addressAndType,
568 const SMPPDUMsg& msg, const HCIACLData::l2cap_frame& source) noexcept;
569 void sendDevicePairingState(const BTDeviceRef& device, const SMPPairingState state, const PairingMode mode, uint64_t timestamp) noexcept;
570 void notifyPairingStageDone(const BTDeviceRef& device, uint64_t timestamp) noexcept;
571 void sendDeviceReady(BTDeviceRef device, uint64_t timestamp) noexcept;
572
573 jau::service_runner discovery_service;
574 void discoveryServerWork(jau::service_runner& sr) noexcept;
575 void checkDiscoveryState() noexcept;
576
577 void sendAdapterSettingsChanged(const AdapterSetting old_settings_, const AdapterSetting current_settings, AdapterSetting changes,
578 const uint64_t timestampMS) noexcept;
579 void sendAdapterSettingsInitial(AdapterStatusListener & asl, const uint64_t timestampMS) noexcept;
580
581 void sendDeviceUpdated(std::string cause, BTDeviceRef device, uint64_t timestamp, EIRDataType updateMask) noexcept;
582
583 size_type removeAllStatusListener(const BTDevice& d) noexcept;
584
585 public:
586
587 /** Private ctor for private BTAdapter::make_shared() intended for friends. */
588 BTAdapter(const BTAdapter::ctor_cookie& cc, BTManagerRef mgmt_, AdapterInfo adapterInfo_) noexcept;
589
590 BTAdapter(const BTAdapter&) = delete;
591 void operator=(const BTAdapter&) = delete;
592
593 /**
594 * Releases this instance.
595 */
596 ~BTAdapter() noexcept override;
597
598 /**
599 * Closes this instance, usually being called by destructor or when this adapter is being removed
600 * as recognized and handled by BTManager.
601 * <p>
602 * In case initialize() has powered-on this adapter and was not powered-on before,
603 * it will be powered-off.
604 * </p>
605 * <p>
606 * Renders this adapter's BTAdapter#isValid() state to false.
607 * </p>
608 * @see initialize()
609 * @see setPowered()
610 */
611 void close() noexcept;
612
613 std::string get_java_class() const noexcept override {
614 return java_class();
615 }
616 static std::string java_class() noexcept {
617 return std::string(JAVA_DBT_PACKAGE "DBTAdapter");
618 }
619
620 /**
621 * Returns whether the adapter is valid, plugged in and powered.
622 * @return true if BTAdapter::isValid(), HCIHandler::isOpen() and AdapterSetting::POWERED state is set.
623 * @see #isSuspended()
624 * @see #isValid()
625 */
626 bool isPowered() const noexcept {
627 return isValid() && hci.isOpen() && adapterInfo.isCurrentSettingBitSet(AdapterSetting::POWERED);
628 }
629
630 /**
631 * Returns whether the adapter is suspended, i.e. valid and plugged in, but not powered.
632 * @return true if BTAdapter::isValid(), HCIHandler::isOpen() and AdapterSetting::POWERED state is not set.
633 * @see #isPowered()
634 * @see #isValid()
635 */
636 bool isSuspended() const noexcept {
637 return isValid() && hci.isOpen() && !adapterInfo.isCurrentSettingBitSet(AdapterSetting::POWERED);
638 }
639
640 bool hasSecureConnections() const noexcept {
642 }
643
644 bool hasSecureSimplePairing() const noexcept {
646 }
647
648 /**
649 * Return LE_Features for this controller.
650 * <pre>
651 * BT Core Spec v5.2: Vol 6, Part B, 4.6 (LE LL) Feature Support
652 * </pre>
653 */
654 constexpr LE_Features getLEFeatures() const noexcept { return le_features; }
655
656 /** Returns the Bluetooth major version of this adapter. Currently either `4` or `5`. */
657 constexpr uint16_t getBTMajorVersion() const noexcept { return ( hci_uses_ext_scan && hci_uses_ext_conn && hci_uses_ext_adv ) ? 5 : 4; }
658
659 /**
660 * Returns whether the adapter is valid, i.e. reference is valid, plugged in and generally operational,
661 * but not necessarily BTAdapter::isPowered() powered.
662 * @return true if this adapter references are valid and hasn't been BTAdapter::close() 'ed
663 * @see #isPowered()
664 * @see #isSuspended()
665 */
666 bool isValid() const noexcept {
667 return BTObject::isValidInstance() && adapter_operational;
668 }
669
670 /**
671 * Return the current BTRole of this adapter.
672 * @see BTRole
673 * @see @ref BTAdapterRoles
674 * @since 2.4.0
675 */
676 BTRole getRole() const noexcept { return btRole; }
677
678 /**
679 * Returns the current BTMode of this adapter.
680 */
681 BTMode getBTMode() const noexcept { return adapterInfo.getCurrentBTMode(); }
682
683 /**
684 * Returns the adapter's public BDAddressAndType, i.e. BDAddressType::BDADDR_LE_PUBLIC.
685 * <p>
686 * The adapter's address as initially reported by the system is always its public address, i.e. BDAddressType::BDADDR_LE_PUBLIC.
687 * </p>
688 * @since 2.2.8
689 * @see #getVisibleAddressAndType()
690 */
691 BDAddressAndType const & getAddressAndType() const noexcept { return adapterInfo.addressAndType; }
692
693 /**
694 * Returns the adapter's currently visible BDAddressAndType, i.e. BDAddressType::BDADDR_LE_RANDOM or BDAddressType::BDADDR_LE_PUBLIC.
695 * <p>
696 * The adapter's address as initially reported by the system is always its public address, i.e. BDAddressType::BDADDR_LE_PUBLIC.
697 * </p>
698 * <p>
699 * The adapter's visible BDAddressAndType might be set to BDAddressType::BDADDR_LE_RANDOM before scanning / discovery mode via setPrivacy().
700 * </p>
701 * @since 3.2.8
702 * @see #getAddressAndType()
703 * @see #setPrivacy()
704 */
705 BDAddressAndType const & getVisibleAddressAndType() const noexcept { return visibleAddressAndType; }
706
707 /**
708 * Returns the name.
709 * <p>
710 * Can be changed via setName() while powered-off.
711 * </p>
712 * @see setName()
713 */
714 std::string getName() const noexcept { return adapterInfo.getName(); }
715
716 /**
717 * Returns the short name.
718 * <p>
719 * Can be changed via setName() while powered-off.
720 * </p>
721 * @see setName()
722 */
723 std::string getShortName() const noexcept { return adapterInfo.getShortName(); }
724
725 /**
726 * Sets the name and short-name.
727 *
728 * The corresponding management event will change the name and short-name.
729 *
730 * Shall be called while adapter is powered off, see setPowered().
731 * If adapter is powered, method returns HCIStatusCode::COMMAND_DISALLOWED.
732 *
733 * @param name
734 * @param short_name
735 * @return HCIStatusCode::SUCCESS or an error state on failure
736 * @see getName()
737 * @see getShortName()
738 * @see setPowered()
739 * @since 2.4.0
740 */
741 HCIStatusCode setName(const std::string &name, const std::string &short_name) noexcept;
742
743 /**
744 * Set the power state of the adapter.
745 *
746 * In case current power state is already as desired, method will not change the power state.
747 *
748 * @param power_on true will power on this adapter if it is powered-off and vice versa.
749 * @return true if successfully powered-on, -off or unchanged, false on failure
750 * @see isInitialized()
751 * @see close()
752 * @see initialize()
753 */
754 bool setPowered(const bool power_on) noexcept;
755
756 /**
757 * Toggle adapter privacy address mode, i.e. resolvable random address including IRK.
758 * @param enable toggle to enable or disable (default)
759 * @return HCIStatusCode::SUCCESS or an error state on failure
760 * @since 3.2.0
761 * @see #getVisibleAddressAndType()
762 */
763 HCIStatusCode setPrivacy(const bool enable) noexcept;
764
765 /**
766 * Returns whether Secure Connections (SC) is enabled.
767 * @see setSecureConnections()
768 * @since 2.4.0
769 */
770 bool getSecureConnectionsEnabled() const noexcept {
772 }
773
774 /**
775 * Enable or disable Secure Connections (SC) of the adapter.
776 *
777 * By default, Secure Connections (SC) is enabled if supported.
778 *
779 * Shall be called while adapter is powered off, see setPowered().
780 * If adapter is powered, method returns HCIStatusCode::COMMAND_DISALLOWED.
781 *
782 * @param enable
783 * @return HCIStatusCode::SUCCESS or an error state on failure
784 * @see getSecureConnectionsEnabled()
785 * @see setPowered()
786 * @since 2.5.3
787 */
788 HCIStatusCode setSecureConnections(const bool enable) noexcept;
789
790 /**
791 * Set default connection parameter of incoming connections for this adapter when in server mode, i.e. BTRole::Slave.
792 *
793 * In case the incoming connection's parameter don't lie within the given default values,
794 * a reconnect is being requested.
795 *
796 * Shall be called while adapter is powered off, see setPowered().
797 * If adapter is powered, method returns HCIStatusCode::COMMAND_DISALLOWED.
798 *
799 * BlueZ/Linux LE connection defaults are
800 * - conn_interval_min 24 -> 30ms
801 * - conn_interval_max 40 -> 50ms
802 * - conn_latency 0
803 * - supervision_timeout 42 -> 420ms
804 *
805 * Supported on GNU/Linux since kernel 5.9.
806 *
807 * @param dev_id
808 * @param conn_interval_min in units of 1.25ms, default value 8 for 10ms; Value range [6 .. 3200] for [7.5ms .. 4000ms].
809 * @param conn_interval_max in units of 1.25ms, default value 40 for 50ms; Value range [6 .. 3200] for [7.5ms .. 4000ms]
810 * @param conn_latency slave latency in units of connection events, default value 0; Value range [0 .. 0x01F3].
811 * @param supervision_timeout in units of 10ms, default value 500ms >= 10 x conn_interval_max, we use HCIConstInt::LE_CONN_MIN_TIMEOUT_MS minimum; Value range [0xA-0x0C80] for [100ms - 32s].
812 * @return HCIStatusCode::SUCCESS or an error state on failure
813 * @see setPowered()
814 * @since 2.5.3
815 */
816 HCIStatusCode setDefaultConnParam(const uint16_t conn_interval_min=8, const uint16_t conn_interval_max=40,
817 const uint16_t conn_latency=0, const uint16_t supervision_timeout=getHCIConnSupervisorTimeout(0, 50)) noexcept;
818
819 /**
820 * Sets the given ::BTSecurityLevel and ::SMPIOCapability for connecting device when in server (peripheral) mode, see [adapter's role](@ref BTAdapterRoles).
821 * <p>
822 * Method either changes both parameter for the upcoming connection or none at all.
823 * </p>
824 * @param[in] sec_level ::BTSecurityLevel to be applied.
825 * @param[in] io_cap ::SMPIOCapability to be applied.
826 * @see ::BTSecurityLevel
827 * @see ::SMPIOCapability
828 * @see BTDevice::setConnSecurity()
829 * @see startAdvertising()
830 */
831 void setServerConnSecurity(const BTSecurityLevel sec_level, const SMPIOCapability io_cap) noexcept;
832
833 /**
834 * Set the adapter's persistent storage directory for SMPKeyBin files.
835 * - if set, all SMPKeyBin instances will be managed and persistent.
836 * - if not set, all SMPKeyBin instances will be transient only.
837 *
838 * When called, all keys within the path will be loaded,
839 * i.e. issuing uploadKeys() for all keys belonging to this BTAdapter.
840 *
841 * Persistent SMPKeyBin management is only functional when BTAdapter is in BTRole::Slave peripheral mode.
842 *
843 * For each SMPKeyBin file one shared BTDevice in BTRole::Master will be instantiated
844 * when uploadKeys() is called.
845 *
846 * @param path persistent storage path to SMPKeyBin files
847 * @see uploadKeys()
848 */
849 void setSMPKeyPath(const std::string path) noexcept;
850
851 /**
852 * Associate the given SMPKeyBin with the contained remote address, i.e. SMPKeyBin::getRemoteAddrAndType().
853 *
854 * Further uploads the Long Term Key (LTK) and Link Key (LK) for a potential upcoming connection,
855 * if they are contained in the given SMPKeyBin file.
856 *
857 * This method is provided to support BTRole::Slave peripheral adapter mode,
858 * allowing user to inject all required keys after initialize()
859 *
860 * One shared BTDevice in BTRole::Master is instantiated.
861 *
862 * @param bin SMPKeyBin instance, might be persistent in filesystem
863 * @param write if true, write file to persistent storage, otherwise not
864 * @return HCIStatusCode::SUCCESS or an error state on failure
865 * @see setSMPKeyPath()
866 * @see BTDevice::uploadKeys()
867 */
868 HCIStatusCode uploadKeys(SMPKeyBin& bin, const bool write) noexcept;
869
870 /**
871 * Initialize the adapter with default values, including power-on.
872 * <p>
873 * Method shall be issued on the desired adapter found via ChangedAdapterSetFunc.
874 * </p>
875 * <p>
876 * While initialization, the adapter is first powered-off, setup and then powered-on.
877 * </p>
878 * <p>
879 * Calling the method will allow close() to power-off the adapter,
880 * if not powered on before.
881 * </p>
882 * @param btMode the desired adapter's BTMode, default is BTMode::DUAL
883 * @param powerOn true to leave adapter powered-on (default), otherwise leave it off *
884 * @return HCIStatusCode::SUCCESS or an error state on failure (e.g. power-on)
885 * @see isInitialized()
886 * @see close()
887 * @see setPowered()
888 * @since 3.2.0
889 */
890 HCIStatusCode initialize(const BTMode btMode, const bool powerOn) noexcept;
891
892 /**
893 * Returns true, if initialize() has already been called for this adapter, otherwise false.
894 *
895 * @see initialize()
896 * @since 2.4.0
897 */
898 bool isInitialized() const noexcept { return adapter_initialized.load(); }
899
900 /**
901 * Reset the adapter.
902 * <p>
903 * The semantics are specific to the HCI host implementation,
904 * however, it shall comply at least with the HCI Reset command
905 * and bring up the device from standby into a POWERED functional state afterwards.
906 * </p>
907 * <pre>
908 * BT Core Spec v5.2: Vol 4, Part E HCI: 7.3.2 Reset command
909 * </pre>
910 */
911 HCIStatusCode reset() noexcept;
912
913 /**
914 * Sets default preference of LE_PHYs.
915 *
916 * BT Core Spec v5.2: Vol 4, Part E, 7.8.49 LE Set PHY command
917 *
918 * @param Tx transmitter LE_PHYs bit mask of preference if not set to LE_PHYs::NONE (ignored).
919 * @param Rx receiver LE_PHYs bit mask of preference if not set to LE_PHYs::NONE (ignored).
920 * @return
921 * @see BTDevice::getTxPhys()
922 * @see BTDevice::getRxPhys()
923 * @see BTDevice::getConnectedLE_PHY()
924 * @see BTDevice::setConnectedLE_PHY()
925 * @since 2.4.0
926 */
927 HCIStatusCode setDefaultLE_PHY(const LE_PHYs Tx, const LE_PHYs Rx) noexcept;
928
929 /**
930 * Returns a reference to the used singleton BTManager instance, used to create this adapter.
931 */
932 const BTManagerRef& getManager() const noexcept { return mgmt; }
933
934 /**
935 * Returns a reference to the aggregated HCIHandler instance.
936 */
937 HCIHandler& getHCI() noexcept { return hci; }
938
939 /**
940 * Returns true, if the adapter's device is already whitelisted.
941 */
942 bool isDeviceWhitelisted(const BDAddressAndType & addressAndType) noexcept;
943
944 /**
945 * Add the given device to the adapter's autoconnect whitelist.
946 * <p>
947 * The given connection parameter will be uploaded to the kernel for the given device first.
948 * </p>
949 * <p>
950 * Method will reject duplicate devices, in which case it should be removed first.
951 * </p>
952 *
953 * @param address
954 * @param address_type
955 * @param ctype
956 * @param conn_interval_min in units of 1.25ms, default value 12 for 15ms; Value range [6 .. 3200] for [7.5ms .. 4000ms]
957 * @param conn_interval_max in units of 1.25ms, default value 12 for 15ms; Value range [6 .. 3200] for [7.5ms .. 4000ms]
958 * @param conn_latency slave latency in units of connection events, default value 0; Value range [0 .. 0x01F3].
959 * @param supervision_timeout in units of 10ms, default value >= 10 x conn_interval_max, we use HCIConstInt::LE_CONN_MIN_TIMEOUT_MS minimum; Value range [0xA-0x0C80] for [100ms - 32s].
960 * @return true if the device was already added or has been newly added to the adapter's whitelist.
961 */
962 bool addDeviceToWhitelist(const BDAddressAndType & addressAndType,
963 const HCIWhitelistConnectType ctype,
964 const uint16_t conn_interval_min=12, const uint16_t conn_interval_max=12,
965 const uint16_t conn_latency=0, const uint16_t supervision_timeout=getHCIConnSupervisorTimeout(0, 15));
966
967
968 /** Remove the given device from the adapter's autoconnect whitelist. */
969 bool removeDeviceFromWhitelist(const BDAddressAndType & addressAndType);
970
971 // device discovery aka device scanning
972
973 /**
974 * Add the given listener to the list if not already present.
975 * <p>
976 * In case the AdapterStatusListener's lifecycle and event delivery
977 * shall be constrained to this device, please use
978 * BTDevice::addStatusListener().
979 * </p>
980 * <p>
981 * Returns true if the given listener is not element of the list and has been newly added,
982 * otherwise false.
983 * </p>
984 * <p>
985 * The newly added AdapterStatusListener will receive an initial
986 * AdapterStatusListener::adapterSettingsChanged(..) event,
987 * passing an empty AdapterSetting::NONE oldMask and changedMask, as well as current AdapterSetting newMask. <br>
988 * This allows the receiver to be aware of this adapter's current settings.
989 * </p>
990 * @see BTDevice::addStatusListener()
991 * @see removeStatusListener()
992 * @see removeAllStatusListener()
993 */
994 bool addStatusListener(const AdapterStatusListenerRef& l) noexcept;
995
996 /**
997 * Please use BTDevice::addStatusListener() for clarity, merely existing here to allow JNI access.
998 */
999 bool addStatusListener(const BTDeviceRef& d, const AdapterStatusListenerRef& l) noexcept;
1000
1001 bool addStatusListener(const BTDevice& d, const AdapterStatusListenerRef& l) noexcept;
1002
1003 /**
1004 * Remove the given listener from the list.
1005 * <p>
1006 * Returns true if the given listener is an element of the list and has been removed,
1007 * otherwise false.
1008 * </p>
1009 * @see BTDevice::removeStatusListener()
1010 * @see addStatusListener()
1011 */
1012 bool removeStatusListener(const AdapterStatusListenerRef& l) noexcept;
1013
1014 /**
1015 * Remove the given listener from the list.
1016 * <p>
1017 * Returns true if the given listener is an element of the list and has been removed,
1018 * otherwise false.
1019 * </p>
1020 * @see BTDevice::removeStatusListener()
1021 * @see addStatusListener()
1022 */
1023 bool removeStatusListener(const AdapterStatusListener * l) noexcept;
1024
1025 /**
1026 * Remove all status listener from the list.
1027 * <p>
1028 * Returns the number of removed status listener.
1029 * </p>
1030 */
1032
1033 /**
1034 * Starts discovery.
1035 *
1036 * Returns HCIStatusCode::SUCCESS if successful, otherwise the HCIStatusCode error state;
1037 *
1038 * Depending on given DiscoveryPolicy `policy`, the discovery mode may be turned-off,
1039 * paused until a certain readiness stage has been reached or preserved at all times.
1040 * Default is DiscoveryPolicy::PAUSE_CONNECTED_UNTIL_READY.
1041 *
1042 * <pre>
1043 * + --+-------+--------+-----------+----------------------------------------------------+
1044 * | # | meta | native | keepAlive | Note
1045 * +---+-------+--------+-----------+----------------------------------------------------+
1046 * | 1 | true | true | false | -
1047 * | 2 | false | false | false | -
1048 * +---+-------+--------+-----------+----------------------------------------------------+
1049 * | 3 | true | true | true | -
1050 * | 4 | true | false | true | temporarily disabled -> startDiscoveryBackground()
1051 * | 5 | false | false | true | [4] -> [5] requires manual DISCOVERING event
1052 * +---+-------+--------+-----------+----------------------------------------------------+
1053 * </pre>
1054 *
1055 * Default parameter values are chosen for using public address resolution
1056 * and usual discovery intervals etc.
1057 *
1058 * Method will always clear previous discovered devices via removeDiscoveredDevices().
1059 *
1060 * Method fails if isAdvertising().
1061 *
1062 * If successful, method also changes [this adapter's role](@ref BTAdapterRoles) to ::BTRole::Master.
1063 *
1064 * This adapter's HCIHandler instance is used to initiate scanning,
1065 * see HCIHandler::le_start_scan().
1066 *
1067 * @param gattServerData_ optional DBGattServer data to be offered via GattHandler as ::GATTRole::Client, may be nullptr (default).
1068 * Its handles will be setup via DBGattServer::setServicesHandles().
1069 * Reference is held until next startDiscovery.
1070 * @param policy defaults to DiscoveryPolicy::PAUSE_CONNECTED_UNTIL_READY, see DiscoveryPolicy
1071 * @param le_scan_active true enables delivery of active scanning PDUs like EIR w/ device name (default), otherwise no scanning PDUs shall be sent.
1072 * @param le_scan_interval in units of 0.625ms, default value 24 for 15ms; Value range [4 .. 0x4000] for [2.5ms .. 10.24s]
1073 * @param le_scan_window in units of 0.625ms, default value 24 for 15ms; Value range [4 .. 0x4000] for [2.5ms .. 10.24s]. Shall be <= le_scan_interval
1074 * @param filter_policy 0x00 accepts all PDUs (default), 0x01 only of whitelisted, ...
1075 * @param filter_dup true to filter out duplicate AD PDUs (default), otherwise all will be reported.
1076 * @return HCIStatusCode::SUCCESS if successful, otherwise the HCIStatusCode error state
1077 * @see stopDiscovery()
1078 * @see isDiscovering()
1079 * @see isAdvertising()
1080 * @see DiscoveryPolicy
1081 * @see @ref BTAdapterRoles
1082 * @since 3.2.0
1083 */
1084 HCIStatusCode startDiscovery(const DBGattServerRef& gattServerData_=nullptr,
1085 const DiscoveryPolicy policy=DiscoveryPolicy::PAUSE_CONNECTED_UNTIL_READY,
1086 const bool le_scan_active=true,
1087 const uint16_t le_scan_interval=24, const uint16_t le_scan_window=24,
1088 const uint8_t filter_policy=0x00,
1089 const bool filter_dup=true) noexcept;
1090 private:
1091 HCIStatusCode stopDiscoveryImpl(const bool forceDiscoveringEvent, const bool temporary) noexcept;
1092
1093 public:
1094 /**
1095 * Ends discovery.
1096 * <p>
1097 * This adapter's HCIHandler instance is used to stop scanning,
1098 * see HCIHandler::le_enable_scan().
1099 * </p>
1100 * @return HCIStatusCode::SUCCESS if successful, otherwise the HCIStatusCode error state
1101 * @see startDiscovery()
1102 * @see isDiscovering()
1103 */
1104 HCIStatusCode stopDiscovery() noexcept;
1105
1106 /**
1107 * Return the current DiscoveryPolicy, set via startDiscovery().
1108 * @since 2.5.1
1109 */
1110 DiscoveryPolicy getCurrentDiscoveryPolicy() const noexcept { return discovery_policy; }
1111
1112 /**
1113 * Manual DiscoveryPolicy intervention point, allowing user to remove the ready device from
1114 * the queue of pausing-discovery devices.
1115 *
1116 * Manual intervention might be desired, if using DiscoveryPolicy::PAUSE_CONNECTED_UNTIL_DISCONNECTED,
1117 * but allowing discovery at an earlier processing step from AdapterStatusListener::deviceReady().
1118 *
1119 * Re-enabling discovery is performed on the current thread.
1120 *
1121 * @param device the BTDevice to remove from the pausing-discovery queue
1122 * @return true if this was the last BTDevice, re-enabling discovery. Otherwise false.
1123 * @since 2.5.1
1124 */
1125 bool removeDevicePausingDiscovery(const BTDevice & device) noexcept;
1126
1127 /**
1128 * Returns the current meta discovering ScanType. It can be modified through startDiscovery(..) and stopDiscovery().
1129 * <p>
1130 * Note that if startDiscovery(..) has been issued with keepAlive==true,
1131 * the meta ScanType will still keep the desired ScanType enabled
1132 * even if it has been temporarily disabled.
1133 * </p>
1134 * @see startDiscovery()
1135 * @see stopDiscovery()
1136 */
1137 ScanType getCurrentScanType() const noexcept {
1138 return currentMetaScanType;
1139 }
1140
1141 /**
1142 * Returns the adapter's current native discovering ScanType.
1143 * It can be modified through startDiscovery(..) and stopDiscovery().
1144 * @see startDiscovery()
1145 * @see stopDiscovery()
1146 */
1148 return hci.getCurrentScanType();
1149 }
1150
1151 /**
1152 * Returns true if the meta discovering state is not ::ScanType::NONE.
1153 * It can be modified through startDiscovery(..) and stopDiscovery().
1154 * @see startDiscovery()
1155 * @see stopDiscovery()
1156 * @since 2.4.0
1157 */
1158 bool isDiscovering() const noexcept {
1159 return ScanType::NONE != currentMetaScanType;
1160 }
1161
1162 /**
1163 * Returns discovered devices from the last discovery.
1164 * <p>
1165 * Note that this list will be cleared when a new discovery is started over via startDiscovery().
1166 * </p>
1167 * <p>
1168 * Note that devices in this list might be no more available,
1169 * use 'DeviceStatusListener::deviceFound(..)' callback.
1170 * </p>
1171 */
1173
1174 /** Discards all discovered devices. Returns number of removed discovered devices. */
1176
1177 /** Discards matching discovered devices. Returns `true` if found and removed, otherwise false. */
1178 bool removeDiscoveredDevice(const BDAddressAndType & addressAndType) noexcept;
1179
1180 /** Returns shared BTDevice if found, otherwise nullptr */
1181 BTDeviceRef findDiscoveredDevice (const EUI48 & address, const BDAddressType addressType) noexcept;
1182
1183 /** Returns shared BTDevice if found, otherwise nullptr */
1184 BTDeviceRef findSharedDevice (const EUI48 & address, const BDAddressType addressType) noexcept;
1185
1186 /**
1187 * Starts advertising
1188 * - BT Core Spec v5.2: Vol 4 HCI, Part E HCI Functional: 7.8.53 LE Set Extended Advertising Parameters command (Bluetooth 5.0)
1189 * - BT Core Spec v5.2: Vol 4 HCI, Part E HCI Functional: 7.8.54 LE Set Extended Advertising Data command (Bluetooth 5.0)
1190 * - BT Core Spec v5.2: Vol 4 HCI, Part E HCI Functional: 7.8.55 LE Set Extended Scan Response Data command (Bluetooth 5.0)
1191 * - BT Core Spec v5.2: Vol 4 HCI, Part E HCI Functional: 7.8.56 LE Set Extended Advertising Enable command (Bluetooth 5.0)
1192 *
1193 * if available, otherwise using
1194 *
1195 * - BT Core Spec v5.2: Vol 4 HCI, Part E HCI Functional: 7.8.5 LE Set Advertising Parameters command
1196 * - BT Core Spec v5.2: Vol 4 HCI, Part E HCI Functional: 7.8.7 LE Set Advertising Data command
1197 * - BT Core Spec v5.2: Vol 4 HCI, Part E HCI Functional: 7.8.8 LE Set Scan Response Data command
1198 * - BT Core Spec v5.2: Vol 4 HCI, Part E HCI Functional: 7.8.9 LE Set Advertising Enable command
1199 *
1200 * Method fails if isDiscovering() or has any open or pending connected remote {@link BTDevice}s.
1201 *
1202 * If successful, method also changes [this adapter's role](@ref BTAdapterRoles) to ::BTRole::Slave
1203 * and treat connected BTDevice as ::BTRole::Master while service ::GATTRole::Server.
1204 *
1205 * Advertising is active until either disabled via stopAdvertising() or a connection has been made, see isAdvertising().
1206 *
1207 * This adapter's HCIHandler instance is used to initiate scanning, see HCIHandler::le_start_adv().
1208 *
1209 * The given ADV EIR EInfoReport will be updated with getName() and at least GAPFlags::LE_Gen_Disc set.
1210 *
1211 * The given adv_mask and scanrsp_mask will be updated to have at least EIRDataType::FLAGS and EIRDataType::NAME
1212 * set in total.
1213 *
1214 * @param gattServerData_ the DBGattServer data to be advertised and offered via GattHandler as ::GATTRole::Server.
1215 * Its handles will be setup via DBGattServer::setServicesHandles().
1216 * Reference is held until next disconnect.
1217 * @param eir Full ADV EIR EInfoReport, will be updated with getName() and at least GAPFlags::LE_Gen_Disc set.
1218 * @param adv_mask EIRDataType mask for EInfoReport to select advertisement EIR PDU data, defaults to EIRDataType::FLAGS | EIRDataType::SERVICE_UUID
1219 * @param scanrsp_mask EIRDataType mask for EInfoReport to select scan-response (active scanning) EIR PDU data, defaults to EIRDataType::NAME | EIRDataType::CONN_IVAL
1220 * @param adv_interval_min in units of 0.625ms, default value 160 for 100ms; Value range [0x0020 .. 0x4000] for [20ms .. 10.24s]
1221 * @param adv_interval_max in units of 0.625ms, default value 480 for 300ms; Value range [0x0020 .. 0x4000] for [20ms .. 10.24s]
1222 * @param adv_type see AD_PDU_Type, default ::AD_PDU_Type::ADV_IND
1223 * @param adv_chan_map bit 0: chan 37, bit 1: chan 38, bit 2: chan 39, default is 0x07 (all 3 channels enabled)
1224 * @param filter_policy 0x00 accepts all PDUs (default), 0x01 only of whitelisted, ...
1225 * @return HCIStatusCode::SUCCESS if successful, otherwise the HCIStatusCode error state
1226 * @see stopAdvertising()
1227 * @see isAdvertising()
1228 * @see isDiscovering()
1229 * @see @ref BTAdapterRoles
1230 * @see DBGattServer::setServicesHandles()
1231 * @since 2.5.3
1232 */
1233 HCIStatusCode startAdvertising(const DBGattServerRef& gattServerData_,
1234 EInfoReport& eir,
1235 EIRDataType adv_mask = EIRDataType::FLAGS | EIRDataType::SERVICE_UUID,
1236 EIRDataType scanrsp_mask = EIRDataType::NAME | EIRDataType::CONN_IVAL,
1237 const uint16_t adv_interval_min=160, const uint16_t adv_interval_max=480,
1238 const AD_PDU_Type adv_type=AD_PDU_Type::ADV_IND,
1239 const uint8_t adv_chan_map=0x07,
1240 const uint8_t filter_policy=0x00) noexcept;
1241
1242 /**
1243 * Starts advertising
1244 * - BT Core Spec v5.2: Vol 4 HCI, Part E HCI Functional: 7.8.53 LE Set Extended Advertising Parameters command (Bluetooth 5.0)
1245 * - BT Core Spec v5.2: Vol 4 HCI, Part E HCI Functional: 7.8.54 LE Set Extended Advertising Data command (Bluetooth 5.0)
1246 * - BT Core Spec v5.2: Vol 4 HCI, Part E HCI Functional: 7.8.55 LE Set Extended Scan Response Data command (Bluetooth 5.0)
1247 * - BT Core Spec v5.2: Vol 4 HCI, Part E HCI Functional: 7.8.56 LE Set Extended Advertising Enable command (Bluetooth 5.0)
1248 *
1249 * if available, otherwise using
1250 *
1251 * - BT Core Spec v5.2: Vol 4 HCI, Part E HCI Functional: 7.8.5 LE Set Advertising Parameters command
1252 * - BT Core Spec v5.2: Vol 4 HCI, Part E HCI Functional: 7.8.7 LE Set Advertising Data command
1253 * - BT Core Spec v5.2: Vol 4 HCI, Part E HCI Functional: 7.8.8 LE Set Scan Response Data command
1254 * - BT Core Spec v5.2: Vol 4 HCI, Part E HCI Functional: 7.8.9 LE Set Advertising Enable command
1255 *
1256 * Method fails if isDiscovering() or has any open or pending connected remote {@link BTDevice}s.
1257 *
1258 * If successful, method also changes [this adapter's role](@ref BTAdapterRoles) to ::BTRole::Slave
1259 * and treat connected BTDevice as ::BTRole::Master while service ::GATTRole::Server.
1260 *
1261 * Advertising is active until either disabled via stopAdvertising() or a connection has been made, see isAdvertising().
1262 *
1263 * This adapter's HCIHandler instance is used to initiate scanning, see HCIHandler::le_start_adv().
1264 *
1265 * The ADV EIR EInfoReport will be generated on the default
1266 * EIRDataType adv_mask using EIRDataType::FLAGS | EIRDataType::SERVICE_UUID
1267 * and EIRDataType scanrsp_mask using scan-response (active scanning) EIRDataType::NAME | EIRDataType::CONN_IVAL.
1268 *
1269 * @param gattServerData_ the DBGattServer data to be advertised and offered via GattHandler as ::GATTRole::Server.
1270 * Its handles will be setup via DBGattServer::setServicesHandles().
1271 * Reference is held until next disconnect.
1272 * @param adv_interval_min in units of 0.625ms, default value 160 for 100ms; Value range [0x0020 .. 0x4000] for [20ms .. 10.24s]
1273 * @param adv_interval_max in units of 0.625ms, default value 480 for 300ms; Value range [0x0020 .. 0x4000] for [20ms .. 10.24s]
1274 * @param adv_type see AD_PDU_Type, default ::AD_PDU_Type::ADV_IND
1275 * @param adv_chan_map bit 0: chan 37, bit 1: chan 38, bit 2: chan 39, default is 0x07 (all 3 channels enabled)
1276 * @param filter_policy 0x00 accepts all PDUs (default), 0x01 only of whitelisted, ...
1277 * @return HCIStatusCode::SUCCESS if successful, otherwise the HCIStatusCode error state
1278 * @see stopAdvertising()
1279 * @see isAdvertising()
1280 * @see isDiscovering()
1281 * @see @ref BTAdapterRoles
1282 * @see DBGattServer::setServicesHandles()
1283 * @since 2.4.0
1284 */
1285 HCIStatusCode startAdvertising(const DBGattServerRef& gattServerData_,
1286 const uint16_t adv_interval_min=160, const uint16_t adv_interval_max=480,
1287 const AD_PDU_Type adv_type=AD_PDU_Type::ADV_IND,
1288 const uint8_t adv_chan_map=0x07,
1289 const uint8_t filter_policy=0x00) noexcept;
1290
1291 /**
1292 * Ends advertising.
1293 * - BT Core Spec v5.2: Vol 4 HCI, Part E HCI Functional: 7.8.56 LE Set Extended Advertising Enable command (Bluetooth 5.0)
1294 *
1295 * if available, otherwise using
1296 *
1297 * - BT Core Spec v5.2: Vol 4 HCI, Part E HCI Functional: 7.8.9 LE Set Advertising Enable command
1298 *
1299 * Advertising is active until either disabled via stopAdvertising() or a connection has been made, see isAdvertising().
1300 *
1301 * This adapter's HCIHandler instance is used to stop scanning, see HCIHandler::le_enable_adv().
1302 *
1303 * @return HCIStatusCode::SUCCESS if successful, otherwise the HCIStatusCode error state
1304 * @see startAdvertising()
1305 * @see isAdvertising()
1306 * @since 2.4.0
1307 */
1308 HCIStatusCode stopAdvertising() noexcept;
1309
1310 /**
1311 * Returns the adapter's current advertising state. It can be modified through startAdvertising(..) and stopAdvertising().
1312 *
1313 * Advertising is active until either disabled via stopAdvertising() or a connection has been made.
1314 *
1315 * @see startAdvertising()
1316 * @see stopAdvertising()
1317 * @since 2.4.0
1318 */
1319 bool isAdvertising() const noexcept {
1320 return hci.isAdvertising();
1321 }
1322
1323 /**
1324 * Return the user's DBGattServer shared reference if in ::BTRole::Slave mode
1325 * as set via startAdvertising() and valid until subsequent disconnect.
1326 *
1327 * Returns nullptr if in ::BTRole::Master mode.
1328 */
1329 DBGattServerRef getGATTServerData() { return gattServerData; }
1330
1331 std::string toString() const noexcept override { return toString(false); }
1332 std::string toString(bool includeDiscoveredDevices) const noexcept;
1333
1334 /**
1335 * Print the internally maintained BTDevice lists to stderr:
1336 * - sharedDevices
1337 * - connectedDevice
1338 * - discoveredDevices
1339 * - StatusListener
1340 *
1341 * This is intended as a debug facility.
1342 */
1343 void printDeviceLists() noexcept;
1344
1345 void printStatusListenerList() noexcept;
1346 };
1347
1348 inline bool operator==(const BTAdapter& lhs, const BTAdapter& rhs) noexcept
1349 { return lhs.getAddressAndType() == rhs.getAddressAndType(); }
1350
1351 inline bool operator!=(const BTAdapter& lhs, const BTAdapter& rhs) noexcept
1352 { return !(lhs == rhs); }
1353
1354 typedef std::shared_ptr<BTAdapter> BTAdapterRef;
1355
1356 /**@}*/
1357
1358} // namespace direct_bt
1359
1360#endif /* BT_ADAPTER_HPP_ */
#define JAVA_DBT_PACKAGE
Definition: BTTypes0.hpp:43
#define JAVA_MAIN_PACKAGE
Definition: BTTypes0.hpp:44
std::string getName() const noexcept
Definition: BTTypes1.hpp:288
BTMode getCurrentBTMode() const noexcept
Map getCurrentSettingMask() to BTMode.
Definition: BTTypes1.hpp:285
std::string getShortName() const noexcept
Definition: BTTypes1.hpp:289
const BDAddressAndType addressAndType
The adapter's address initially reported by the system is always its public address,...
Definition: BTTypes1.hpp:206
bool isCurrentSettingBitSet(const AdapterSetting bit) const noexcept
Definition: BTTypes1.hpp:282
BTAdapter status listener for remote BTDevice discovery events: Added, updated and removed; as well a...
Definition: BTAdapter.hpp:127
virtual void discoveringChanged(BTAdapter &adapter, const ScanType currentMeta, const ScanType changedType, const bool changedEnabled, const DiscoveryPolicy policy, const uint64_t timestamp)
BTAdapter's discovery state has changed, i.e.
Definition: BTAdapter.hpp:157
virtual void deviceUpdated(const BTDeviceRef &device, const EIRDataType updateMask, const uint64_t timestamp)
An already discovered remote BTDevice has been updated.
Definition: BTAdapter.hpp:199
virtual void adapterSettingsChanged(BTAdapter &adapter, const AdapterSetting oldmask, const AdapterSetting newmask, const AdapterSetting changedmask, const uint64_t timestamp)
BTAdapter setting(s) changed.
Definition: BTAdapter.hpp:137
virtual void deviceDisconnected(const BTDeviceRef &device, const HCIStatusCode reason, const uint16_t handle, const uint64_t timestamp)
Remote BTDevice got disconnected.
Definition: BTAdapter.hpp:267
std::string toString() const noexcept override
Definition: BTAdapter.hpp:276
~AdapterStatusListener() noexcept override=default
std::string get_java_class() const noexcept override
Definition: BTAdapter.hpp:278
bool operator!=(const AdapterStatusListener &rhs) const
Definition: BTAdapter.hpp:294
virtual bool deviceFound(const BTDeviceRef &device, const uint64_t timestamp)
A remote BTDevice has been newly discovered.
Definition: BTAdapter.hpp:185
virtual void devicePairingState(const BTDeviceRef &device, const SMPPairingState state, const PairingMode mode, const uint64_t timestamp)
An already connected remote BTDevice's SMPPairingState has changed.
Definition: BTAdapter.hpp:231
static std::string java_class() noexcept
Definition: BTAdapter.hpp:281
virtual void deviceReady(const BTDeviceRef &device, const uint64_t timestamp)
Remote BTDevice is ready for user (GATT) processing, i.e.
Definition: BTAdapter.hpp:251
virtual void deviceConnected(const BTDeviceRef &device, const bool discovered, const uint64_t timestamp)
Remote BTDevice got connected.
Definition: BTAdapter.hpp:216
virtual bool operator==(const AdapterStatusListener &rhs) const
Default comparison operator, merely testing for same memory reference.
Definition: BTAdapter.hpp:291
Unique Bluetooth EUI48 address and BDAddressType tuple.
Definition: BTAddress.hpp:175
BTAdapter represents one local Bluetooth Controller.
Definition: BTAdapter.hpp:324
BTMode getBTMode() const noexcept
Returns the current BTMode of this adapter.
Definition: BTAdapter.hpp:681
HCIStatusCode setName(const std::string &name, const std::string &short_name) noexcept
Sets the name and short-name.
Definition: BTAdapter.cpp:652
jau::nsize_t size_type
Definition: BTAdapter.hpp:355
HCIStatusCode stopAdvertising() noexcept
Ends advertising.
Definition: BTAdapter.cpp:1671
std::string get_java_class() const noexcept override
Definition: BTAdapter.hpp:613
constexpr LE_Features getLEFeatures() const noexcept
Return LE_Features for this controller.
Definition: BTAdapter.hpp:654
std::string getShortName() const noexcept
Returns the short name.
Definition: BTAdapter.hpp:723
HCIStatusCode setPrivacy(const bool enable) noexcept
Toggle adapter privacy address mode, i.e.
Definition: BTAdapter.cpp:674
bool isInitialized() const noexcept
Returns true, if initialize() has already been called for this adapter, otherwise false.
Definition: BTAdapter.hpp:898
BDAddressAndType const & getVisibleAddressAndType() const noexcept
Returns the adapter's currently visible BDAddressAndType, i.e.
Definition: BTAdapter.hpp:705
bool isDiscovering() const noexcept
Returns true if the meta discovering state is not ScanType::NONE.
Definition: BTAdapter.hpp:1158
void setSMPKeyPath(const std::string path) noexcept
Set the adapter's persistent storage directory for SMPKeyBin files.
Definition: BTAdapter.cpp:739
std::string toString() const noexcept override
Definition: BTAdapter.hpp:1331
HCIStatusCode setDefaultConnParam(const uint16_t conn_interval_min=8, const uint16_t conn_interval_max=40, const uint16_t conn_latency=0, const uint16_t supervision_timeout=getHCIConnSupervisorTimeout(0, 50)) noexcept
Set default connection parameter of incoming connections for this adapter when in server mode,...
Definition: BTAdapter.cpp:727
bool isAdvertising() const noexcept
Returns the adapter's current advertising state.
Definition: BTAdapter.hpp:1319
BTDeviceRef findSharedDevice(const EUI48 &address, const BDAddressType addressType) noexcept
Returns shared BTDevice if found, otherwise nullptr.
Definition: BTAdapter.cpp:1475
HCIHandler & getHCI() noexcept
Returns a reference to the aggregated HCIHandler instance.
Definition: BTAdapter.hpp:937
HCIStatusCode reset() noexcept
Reset the adapter.
Definition: BTAdapter.cpp:943
HCIStatusCode startDiscovery(const DBGattServerRef &gattServerData_=nullptr, const DiscoveryPolicy policy=DiscoveryPolicy::PAUSE_CONNECTED_UNTIL_READY, const bool le_scan_active=true, const uint16_t le_scan_interval=24, const uint16_t le_scan_window=24, const uint8_t filter_policy=0x00, const bool filter_dup=true) noexcept
Starts discovery.
Definition: BTAdapter.cpp:1150
bool isValid() const noexcept
Returns whether the adapter is valid, i.e.
Definition: BTAdapter.hpp:666
bool isSuspended() const noexcept
Returns whether the adapter is suspended, i.e.
Definition: BTAdapter.hpp:636
size_type removeDiscoveredDevices() noexcept
Discards all discovered devices.
Definition: BTAdapter.cpp:1415
void printStatusListenerList() noexcept
Definition: BTAdapter.cpp:644
bool hasSecureSimplePairing() const noexcept
Definition: BTAdapter.hpp:644
HCIStatusCode uploadKeys(SMPKeyBin &bin, const bool write) noexcept
Associate the given SMPKeyBin with the contained remote address, i.e.
Definition: BTAdapter.cpp:749
ScanType getCurrentNativeScanType() const noexcept
Returns the adapter's current native discovering ScanType.
Definition: BTAdapter.hpp:1147
BTDeviceRef findDiscoveredDevice(const EUI48 &address, const BDAddressType addressType) noexcept
Returns shared BTDevice if found, otherwise nullptr.
Definition: BTAdapter.cpp:1385
bool getSecureConnectionsEnabled() const noexcept
Returns whether Secure Connections (SC) is enabled.
Definition: BTAdapter.hpp:770
HCIStatusCode initialize(const BTMode btMode, const bool powerOn) noexcept
Initialize the adapter with default values, including power-on.
Definition: BTAdapter.cpp:794
void setServerConnSecurity(const BTSecurityLevel sec_level, const SMPIOCapability io_cap) noexcept
Sets the given BTSecurityLevel and SMPIOCapability for connecting device when in server (peripheral) ...
Definition: BTAdapter.cpp:735
HCIStatusCode stopDiscovery() noexcept
Ends discovery.
Definition: BTAdapter.cpp:1285
const uint16_t dev_id
Adapter's internal temporary device id.
Definition: BTAdapter.hpp:363
DiscoveryPolicy getCurrentDiscoveryPolicy() const noexcept
Return the current DiscoveryPolicy, set via startDiscovery().
Definition: BTAdapter.hpp:1110
bool removeDeviceFromWhitelist(const BDAddressAndType &addressAndType)
Remove the given device from the adapter's autoconnect whitelist.
Definition: BTAdapter.cpp:1010
bool isPowered() const noexcept
Returns whether the adapter is valid, plugged in and powered.
Definition: BTAdapter.hpp:626
bool isDeviceWhitelisted(const BDAddressAndType &addressAndType) noexcept
Returns true, if the adapter's device is already whitelisted.
Definition: BTAdapter.cpp:986
BTRole getRole() const noexcept
Return the current BTRole of this adapter.
Definition: BTAdapter.hpp:676
size_type removeAllStatusListener() noexcept
Remove all status listener from the list.
Definition: BTAdapter.cpp:1120
HCIStatusCode startAdvertising(const DBGattServerRef &gattServerData_, EInfoReport &eir, EIRDataType adv_mask=EIRDataType::FLAGS|EIRDataType::SERVICE_UUID, EIRDataType scanrsp_mask=EIRDataType::NAME|EIRDataType::CONN_IVAL, const uint16_t adv_interval_min=160, const uint16_t adv_interval_max=480, const AD_PDU_Type adv_type=AD_PDU_Type::ADV_IND, const uint8_t adv_chan_map=0x07, const uint8_t filter_policy=0x00) noexcept
Starts advertising.
Definition: BTAdapter.cpp:1557
BDAddressAndType const & getAddressAndType() const noexcept
Returns the adapter's public BDAddressAndType, i.e.
Definition: BTAdapter.hpp:691
ScanType getCurrentScanType() const noexcept
Returns the current meta discovering ScanType.
Definition: BTAdapter.hpp:1137
bool removeStatusListener(const AdapterStatusListenerRef &l) noexcept
Remove the given listener from the list.
Definition: BTAdapter.cpp:1059
void printDeviceLists() noexcept
Print the internally maintained BTDevice lists to stderr:
Definition: BTAdapter.cpp:618
HCIStatusCode setDefaultLE_PHY(const LE_PHYs Tx, const LE_PHYs Rx) noexcept
Sets default preference of LE_PHYs.
Definition: BTAdapter.cpp:978
bool removeDevicePausingDiscovery(const BTDevice &device) noexcept
Manual DiscoveryPolicy intervention point, allowing user to remove the ready device from the queue of...
Definition: BTAdapter.cpp:183
constexpr uint16_t getBTMajorVersion() const noexcept
Returns the Bluetooth major version of this adapter.
Definition: BTAdapter.hpp:657
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:990
std::string getName() const noexcept
Returns the name.
Definition: BTAdapter.hpp:714
BTAdapter(const BTAdapter::ctor_cookie &cc, BTManagerRef mgmt_, AdapterInfo adapterInfo_) noexcept
Private ctor for private BTAdapter::make_shared() intended for friends.
Definition: BTAdapter.cpp:419
static std::string java_class() noexcept
Definition: BTAdapter.hpp:616
bool addStatusListener(const AdapterStatusListenerRef &l) noexcept
Add the given listener to the list if not already present.
Definition: BTAdapter.cpp:1017
const BTManagerRef & getManager() const noexcept
Returns a reference to the used singleton BTManager instance, used to create this adapter.
Definition: BTAdapter.hpp:932
bool hasSecureConnections() const noexcept
Definition: BTAdapter.hpp:640
HCIStatusCode setSecureConnections(const bool enable) noexcept
Enable or disable Secure Connections (SC) of the adapter.
Definition: BTAdapter.cpp:710
jau::darray< BTDeviceRef > getDiscoveredDevices() const noexcept
Returns discovered devices from the last discovery.
Definition: BTAdapter.cpp:1440
bool setPowered(const bool power_on) noexcept
Set the power state of the adapter.
Definition: BTAdapter.cpp:660
bool removeDiscoveredDevice(const BDAddressAndType &addressAndType) noexcept
Discards matching discovered devices.
Definition: BTAdapter.cpp:1400
void close() noexcept
Closes this instance, usually being called by destructor or when this adapter is being removed as rec...
Definition: BTAdapter.cpp:472
DBGattServerRef getGATTServerData()
Return the user's DBGattServer shared reference if in BTRole::Slave mode as set via startAdvertising(...
Definition: BTAdapter.hpp:1329
BTDevice represents one remote Bluetooth device.
Definition: BTDevice.hpp:81
std::shared_ptr< BTDevice > getSharedInstance() const noexcept
Returns the shared pointer of this instance managed by the adapter.
Definition: BTDevice.cpp:100
A thread safe singleton handler of the BTAdapter manager, e.g.
Definition: BTManager.hpp:204
bool isValidInstance() const noexcept
Returns whether the object's reference is valid and in a general operational state.
Definition: BTTypes1.hpp:66
mgmt_addr_info { EUI48, uint8_t type }, int8_t rssi, int8_t tx_power, int8_t max_tx_power;
Definition: BTTypes1.hpp:83
Collection of 'Extended Advertising Data' (EAD), 'Advertising Data' (AD) or 'Extended Inquiry Respons...
Definition: BTTypes0.hpp:898
BT Core Spec v5.2: Vol 4, Part E HCI: 5.4.2 HCI ACL Data packets.
Definition: HCITypes.hpp:969
A thread safe singleton handler of the HCI control channel to one controller (BT adapter)
Definition: HCIHandler.hpp:179
bool isOpen() const noexcept
Returns true if this mgmt instance is open, connected and hence valid, otherwise false.
Definition: HCIHandler.hpp:405
bool isAdvertising() const noexcept
Advertising is enabled via le_start_adv() or le_enable_adv().
Definition: HCIHandler.hpp:443
ScanType getCurrentScanType() const noexcept
Definition: HCIHandler.hpp:433
L2CAP read/write communication channel to remote device.
Definition: L2CAPComm.hpp:195
L2CAP server socket to listen for connecting remote devices.
Definition: L2CAPComm.hpp:317
uint16_t opcode, uint16_t dev-id, uint16_t param_size
Definition: MgmtTypes.hpp:1402
Storage for SMP keys including required connection parameter per local adapter and remote device.
Definition: SMPKeyBin.hpp:79
Handles the Security Manager Protocol (SMP) using Protocol Data Unit (PDU) encoded messages over L2CA...
Definition: SMPTypes.hpp:842
bool(* equal_comparator)(const value_type &a, const value_type &b)
Generic value_type equal comparator to be user defined for e.g.
Definition: cow_darray.hpp:989
A simple timer for timeout and interval applications, using one dedicated service_runner thread per i...
static const uint8_t filter_policy
static const uint16_t le_scan_interval
static const uint16_t le_scan_window
static const bool filter_dup
static bool le_scan_active
static BTMode btMode
static const uint16_t adv_interval_max
static const uint8_t adv_chan_map
static const uint16_t adv_interval_min
static const AD_PDU_Type adv_type
SMPPairingState
SMP Pairing Process state definition.
Definition: SMPTypes.hpp:107
SMPIOCapability
Vol 3, Part H, 2.3.2 IO capabilities.
Definition: SMPTypes.hpp:209
@ UNSET
Denoting unset value, i.e.
std::shared_ptr< BTManager > BTManagerRef
Definition: BTAdapter.hpp:61
BTMode
Bluetooth adapter operating mode.
Definition: BTTypes0.hpp:112
std::shared_ptr< AdapterStatusListener > AdapterStatusListenerRef
Definition: BTAdapter.hpp:297
LE_Features
HCI Supported Commands.
Definition: BTTypes0.hpp:162
HCIWhitelistConnectType
HCI Whitelist connection type.
Definition: BTTypes0.hpp:471
DiscoveryPolicy
Discovery policy defines the BTAdapter discovery mode after connecting a remote BTDevice:
Definition: BTAdapter.hpp:82
std::shared_ptr< BTDevice > BTDeviceRef
Definition: BTDevice.hpp:1347
std::string to_string(const DiscoveryPolicy v) noexcept
Definition: BTAdapter.cpp:58
std::shared_ptr< BTAdapter > BTAdapterRef
Definition: BTAdapter.hpp:1354
LE_PHYs
LE Transport PHY bit values.
Definition: BTTypes0.hpp:231
ScanType
Meta ScanType as derived from BTMode, with defined value mask consisting of BDAddressType bits.
Definition: BTTypes0.hpp:350
AdapterSetting
Adapter Setting Bits.
Definition: BTTypes1.hpp:144
BDAddressType
BT Core Spec v5.2: Vol 3, Part C Generic Access Profile (GAP): 15.1.1.1 Public Bluetooth address.
Definition: BTAddress.hpp:60
BTRole
Bluetooth roles from the perspective of the link layer (connection initiator).
Definition: BTTypes0.hpp:69
BTSecurityLevel
Bluetooth Security Level.
Definition: BTTypes0.hpp:267
AD_PDU_Type
LE Advertising (AD) Protocol Data Unit (PDU) Types.
Definition: BTTypes0.hpp:397
PairingMode
Bluetooth secure pairing mode.
Definition: BTTypes0.hpp:317
bool operator!=(const BTAdapter &lhs, const BTAdapter &rhs) noexcept
Definition: BTAdapter.hpp:1351
constexpr DiscoveryPolicy to_DiscoveryPolicy(const uint8_t v) noexcept
Definition: BTAdapter.hpp:103
constexpr uint16_t getHCIConnSupervisorTimeout(const uint16_t conn_latency, const uint16_t conn_interval_max_ms, const uint16_t min_result_ms=number(HCIConstInt::LE_CONN_MIN_TIMEOUT_MS), const uint16_t multiplier=10) noexcept
Defining the supervising timeout for LE connections to be a multiple of the maximum connection interv...
Definition: HCITypes.hpp:102
HCIStatusCode
BT Core Spec v5.2: Vol 1, Part F Controller Error Codes: 1.3 List of Error Codes.
Definition: HCITypes.hpp:138
constexpr uint8_t number(const DiscoveryPolicy rhs) noexcept
Definition: BTAdapter.hpp:100
EIRDataType
Bit mask of 'Extended Inquiry Response' (EIR) data fields, indicating a set of related data.
Definition: BTTypes0.hpp:838
@ PAUSE_CONNECTED_UNTIL_PAIRED
Pause discovery until all connected BTDevice are optionally SMP paired (~120ms) without GATT service ...
@ PAUSE_CONNECTED_UNTIL_READY
Pause discovery until all connected BTDevice reach readiness inclusive optional SMP pairing (~120ms) ...
@ ALWAYS_ON
Always keep discovery enabled, i.e.
@ AUTO_OFF
Turn off discovery when connected and leave discovery disabled, if turned off by host system.
@ PAUSE_CONNECTED_UNTIL_DISCONNECTED
Pause discovery until all connected BTDevice become disconnected, effectively until AdapterStatusList...
@ UNSET
Security Level not set, value 0.
std::shared_ptr< BTGattService > BTGattServiceRef
Definition: BTGattChar.hpp:67
std::shared_ptr< DBGattServer > DBGattServerRef
bool remove(const std::string &path, const traverse_options topts=traverse_options::none) noexcept
Remove the given path.
Definition: file_util.cpp:1173
uint_fast32_t nsize_t
Natural 'size_t' alternative using uint_fast32_t as its natural sized type.
Definition: int_types.hpp:53
std::string to_hexstring(value_type const &v) noexcept
Produce a lower-case hexadecimal string representation of the given pointer.
__pack(...): Produces MSVC, clang and gcc compatible lead-in and -out macros.
Definition: backtrace.hpp:32
STL namespace.
Used for MgmtLoadIdentityResolvingKeyCmd and MgmtEvtNewIdentityResolvingKey.
Definition: MgmtTypes.hpp:289
A packed 48 bit EUI-48 identifier, formerly known as MAC-48 or simply network device MAC address (Med...
Definition: eui48.hpp:324
CXX_ALWAYS_INLINE _Tp load() const noexcept