diff options
author | Sven Gothel <[email protected]> | 2020-12-12 11:24:29 +0100 |
---|---|---|
committer | Sven Gothel <[email protected]> | 2020-12-12 11:24:29 +0100 |
commit | 4b8e48998989c07ea075f3aa9d9478c8046fae47 (patch) | |
tree | 5cb31358137ab2b0b12ce3e62f024445905e208a | |
parent | bc9d1c0d2942ce24019b432198f2d4c0d00aee19 (diff) |
Adopt new BDAddressAndType key value across project
See commit bc9d1c0d2942ce24019b432198f2d4c0d00aee19
34 files changed, 600 insertions, 630 deletions
diff --git a/api/direct_bt/DBTAdapter.hpp b/api/direct_bt/DBTAdapter.hpp index 3508a98d..66ec6d2d 100644 --- a/api/direct_bt/DBTAdapter.hpp +++ b/api/direct_bt/DBTAdapter.hpp @@ -231,9 +231,7 @@ namespace direct_bt { bool validateDevInfo() noexcept; - /** Returns index >= 0 if found, otherwise -1 */ - static int findDeviceIdx(std::vector<std::shared_ptr<DBTDevice>> & devices, EUI48 const & mac, const BDAddressType macType) noexcept; - static std::shared_ptr<DBTDevice> findDevice(std::vector<std::shared_ptr<DBTDevice>> & devices, EUI48 const & mac, const BDAddressType macType) noexcept; + static std::shared_ptr<DBTDevice> findDevice(std::vector<std::shared_ptr<DBTDevice>> & devices, const EUI48 & address, const BDAddressType addressType) noexcept; std::shared_ptr<DBTDevice> findDevice(std::vector<std::shared_ptr<DBTDevice>> & devices, DBTDevice const & device) noexcept; /** @@ -265,7 +263,7 @@ namespace direct_bt { bool addConnectedDevice(const std::shared_ptr<DBTDevice> & device) noexcept; bool removeConnectedDevice(const DBTDevice & device) noexcept; int disconnectAllDevices(const HCIStatusCode reason=HCIStatusCode::REMOTE_USER_TERMINATED_CONNECTION ) noexcept; - std::shared_ptr<DBTDevice> findConnectedDevice (EUI48 const & mac, const BDAddressType macType) noexcept; + std::shared_ptr<DBTDevice> findConnectedDevice (const EUI48 & address, const BDAddressType & addressType) noexcept; bool addDiscoveredDevice(std::shared_ptr<DBTDevice> const &device) noexcept; bool removeDiscoveredDevice(const DBTDevice & device) noexcept; @@ -275,7 +273,7 @@ namespace direct_bt { bool addSharedDevice(std::shared_ptr<DBTDevice> const &device) noexcept; std::shared_ptr<DBTDevice> getSharedDevice(const DBTDevice & device) noexcept; void removeSharedDevice(const DBTDevice & device) noexcept; - std::shared_ptr<DBTDevice> findSharedDevice (EUI48 const & mac, const BDAddressType macType) noexcept; + std::shared_ptr<DBTDevice> findSharedDevice (const EUI48 & address, const BDAddressType addressType) noexcept; bool mgmtEvNewSettingsMgmt(std::shared_ptr<MgmtEvent> e) noexcept; bool mgmtEvDeviceDiscoveringMgmt(std::shared_ptr<MgmtEvent> e) noexcept; @@ -302,7 +300,7 @@ namespace direct_bt { bool mgmtEvAuthFailedMgmt(std::shared_ptr<MgmtEvent> e) noexcept; bool mgmtEvDeviceUnpairedMgmt(std::shared_ptr<MgmtEvent> e) noexcept; - bool hciSMPMsgCallback(const EUI48& address, BDAddressType addressType, + bool hciSMPMsgCallback(const BDAddressAndType & addressAndType, std::shared_ptr<const SMPPDUMsg> msg, const HCIACLData::l2cap_frame& source) noexcept; void sendDevicePairingState(std::shared_ptr<DBTDevice> device, const SMPPairingState state, const PairingMode mode, uint64_t timestamp) noexcept; void sendDeviceReady(std::shared_ptr<DBTDevice> device, uint64_t timestamp) noexcept; @@ -482,7 +480,7 @@ namespace direct_bt { /** * Returns true, if the adapter's device is already whitelisted. */ - bool isDeviceWhitelisted(const EUI48 &address) noexcept; + bool isDeviceWhitelisted(const BDAddressAndType & addressAndType) noexcept; /** * Add the given device to the adapter's autoconnect whitelist. @@ -502,14 +500,14 @@ namespace direct_bt { * @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]. * @return true if the device was already added or has been newly added to the adapter's whitelist. */ - bool addDeviceToWhitelist(const EUI48 &address, const BDAddressType address_type, + 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)); /** Remove the given device from the adapter's autoconnect whitelist. */ - bool removeDeviceFromWhitelist(const EUI48 &address, const BDAddressType address_type); + bool removeDeviceFromWhitelist(const BDAddressAndType & addressAndType); // device discovery aka device scanning @@ -658,7 +656,7 @@ namespace direct_bt { int removeDiscoveredDevices() noexcept; /** Returns shared DBTDevice if found, otherwise nullptr */ - std::shared_ptr<DBTDevice> findDiscoveredDevice (EUI48 const & mac, const BDAddressType macType) noexcept; + std::shared_ptr<DBTDevice> findDiscoveredDevice (const EUI48 & address, const BDAddressType addressType) noexcept; std::string toString() const noexcept override { return toString(true); } std::string toString(bool includeDiscoveredDevices) const noexcept; diff --git a/api/direct_bt/DBTDevice.hpp b/api/direct_bt/DBTDevice.hpp index ae363599..4b504c56 100644 --- a/api/direct_bt/DBTDevice.hpp +++ b/api/direct_bt/DBTDevice.hpp @@ -206,10 +206,8 @@ namespace direct_bt { public: const uint64_t ts_creation; - /** Device mac address */ - const EUI48 address; // FIXME: Mutable for resolvable -> identity during pairing? - const BDAddressType addressType; - const BLERandomAddressType leRandomAddressType; + /** Device's unique mac address and type tuple. */ + const BDAddressAndType addressAndType; // FIXME: Mutable for resolvable -> identity during pairing? DBTDevice(const DBTDevice&) = delete; void operator=(const DBTDevice&) = delete; @@ -258,25 +256,11 @@ namespace direct_bt { */ uint64_t getLastUpdateAge(const uint64_t ts_now) const noexcept { return ts_now - ts_last_update; } - EUI48 const & getAddress() const noexcept { return address; } - std::string getAddressString() const noexcept { return address.toString(); } - constexpr BDAddressType getAddressType() const noexcept { return addressType; } - constexpr bool isLEAddressType() const noexcept { return direct_bt::isLEAddressType(addressType); } - constexpr bool isBREDRAddressType() const noexcept { return direct_bt::isBREDRAddressType(addressType); } - /** - * Returns the {@link BLERandomAddressType}. - * <p> - * If {@link #getAddressType()} is {@link BDAddressType::BDADDR_LE_RANDOM}, - * method shall return a valid value other than {@link BLERandomAddressType::UNDEFINED}. - * </p> - * <p> - * If {@link #getAddressType()} is not {@link BDAddressType::BDADDR_LE_RANDOM}, - * method shall return {@link BLERandomAddressType::UNDEFINED}. - * </p> - * @since 2.0.0 + * Returns the unique device EUI48 address and BDAddressType type. + * @since 2.2.0 */ - constexpr BLERandomAddressType getBLERandomAddressType() const noexcept { return leRandomAddressType; } + constexpr BDAddressAndType const & getAddressAndType() const noexcept { return addressAndType; } /** Return RSSI of device as recognized at discovery and connect. */ int8_t getRSSI() const noexcept { return rssi; } @@ -827,11 +811,8 @@ namespace direct_bt { int removeAllCharacteristicListener() noexcept; }; - inline bool operator<(const DBTDevice& lhs, const DBTDevice& rhs) noexcept - { return lhs.getAddress() < rhs.getAddress(); } - inline bool operator==(const DBTDevice& lhs, const DBTDevice& rhs) noexcept - { return lhs.getAddress() == rhs.getAddress() && lhs.getAddressType() == rhs.getAddressType(); } + { return lhs.getAddressAndType() == rhs.getAddressAndType(); } inline bool operator!=(const DBTDevice& lhs, const DBTDevice& rhs) noexcept { return !(lhs == rhs); } diff --git a/api/direct_bt/DBTManager.hpp b/api/direct_bt/DBTManager.hpp index 1697146e..8bea2eef 100644 --- a/api/direct_bt/DBTManager.hpp +++ b/api/direct_bt/DBTManager.hpp @@ -202,8 +202,7 @@ namespace direct_bt { struct WhitelistElem { uint16_t dev_id; - EUI48 address; - BDAddressType address_type; + BDAddressAndType address_and_type; HCIWhitelistConnectType ctype; }; std::vector<std::shared_ptr<WhitelistElem>> whitelist; @@ -403,14 +402,14 @@ namespace direct_bt { * @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]. * @return */ - bool uploadConnParam(const uint16_t dev_id, const EUI48 &address, const BDAddressType address_type, + bool uploadConnParam(const uint16_t dev_id, const BDAddressAndType & addressAndType, 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)) noexcept; /** * Returns true, if the adapter's device is already whitelisted. */ - bool isDeviceWhitelisted(const uint16_t dev_id, const EUI48 &address) noexcept; + bool isDeviceWhitelisted(const uint16_t dev_id, const BDAddressAndType & addressAndType) noexcept; /** * Add the given device to the adapter's autoconnect whitelist. @@ -421,19 +420,19 @@ namespace direct_bt { * Method will reject duplicate devices, in which case it should be removed first. * </p> */ - bool addDeviceToWhitelist(const uint16_t dev_id, const EUI48 &address, const BDAddressType address_type, const HCIWhitelistConnectType ctype) noexcept; + bool addDeviceToWhitelist(const uint16_t dev_id, const BDAddressAndType & addressAndType, const HCIWhitelistConnectType ctype) noexcept; /** Remove the given device from the adapter's autoconnect whitelist. */ - bool removeDeviceFromWhitelist(const uint16_t dev_id, const EUI48 &address, const BDAddressType address_type) noexcept; + bool removeDeviceFromWhitelist(const uint16_t dev_id, const BDAddressAndType & addressAndType) noexcept; /** Remove all previously added devices from the autoconnect whitelist. Returns number of removed devices. */ int removeAllDevicesFromWhitelist() noexcept; bool disconnect(const bool ioErrorCause, - const uint16_t dev_id, const EUI48 &peer_bdaddr, const BDAddressType peer_mac_type, + const uint16_t dev_id, const BDAddressAndType & addressAndType, const HCIStatusCode reason=HCIStatusCode::REMOTE_USER_TERMINATED_CONNECTION ) noexcept; - std::shared_ptr<ConnectionInfo> getConnectionInfo(const uint16_t dev_id, const EUI48 &address, const BDAddressType address_type) noexcept; + std::shared_ptr<ConnectionInfo> getConnectionInfo(const uint16_t dev_id, const BDAddressAndType& addressAndType) noexcept; std::shared_ptr<NameAndShortName> setLocalName(const uint16_t dev_id, const std::string & name, const std::string & short_name) noexcept; /** Security commands */ @@ -441,14 +440,14 @@ namespace direct_bt { MgmtStatus uploadLinkKey(const uint16_t dev_id, const bool debug_keys, const MgmtLinkKeyInfo &key) noexcept; HCIStatusCode uploadLongTermKey(const uint16_t dev_id, const MgmtLongTermKeyInfo &key) noexcept; - HCIStatusCode uploadLongTermKeyInfo(const uint16_t dev_id, const EUI48& address, BDAddressType address_type, const SMPLongTermKeyInfo& ltk) noexcept; + HCIStatusCode uploadLongTermKeyInfo(const uint16_t dev_id, const BDAddressAndType & addressAndType, const SMPLongTermKeyInfo& ltk) noexcept; - MgmtStatus userPasskeyReply(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType, const uint32_t passkey) noexcept; - MgmtStatus userPasskeyNegativeReply(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType) noexcept; - MgmtStatus userConfirmReply(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType, const bool positive) noexcept; + MgmtStatus userPasskeyReply(const uint16_t dev_id, const BDAddressAndType & addressAndType, const uint32_t passkey) noexcept; + MgmtStatus userPasskeyNegativeReply(const uint16_t dev_id, const BDAddressAndType & addressAndType) noexcept; + MgmtStatus userConfirmReply(const uint16_t dev_id, const BDAddressAndType & addressAndType, const bool positive) noexcept; - bool pairDevice(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType, const SMPIOCapability iocap) noexcept; - MgmtStatus unpairDevice(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType, const bool disconnect) noexcept; + bool pairDevice(const uint16_t dev_id, const BDAddressAndType & addressAndType, const SMPIOCapability iocap) noexcept; + MgmtStatus unpairDevice(const uint16_t dev_id, const BDAddressAndType & addressAndType, const bool disconnect) noexcept; /** MgmtEventCallback handling */ diff --git a/api/direct_bt/HCIHandler.hpp b/api/direct_bt/HCIHandler.hpp index ae37f0b6..e07b6350 100644 --- a/api/direct_bt/HCIHandler.hpp +++ b/api/direct_bt/HCIHandler.hpp @@ -147,7 +147,7 @@ namespace direct_bt { } }; - typedef jau::FunctionDef<bool, const EUI48& /* address */, BDAddressType /* addressType */, + typedef jau::FunctionDef<bool, const BDAddressAndType& /* addressAndType */, std::shared_ptr<const SMPPDUMsg>, const HCIACLData::l2cap_frame& /* source */> HCISMPMsgCallback; typedef jau::cow_vector<HCISMPMsgCallback> HCISMPMsgCallbackList; @@ -171,37 +171,43 @@ namespace direct_bt { private: class HCIConnection { private: - EUI48 address; // immutable - BDAddressType addressType; // immutable + BDAddressAndType addressAndType; // immutable uint16_t handle; // mutable public: - HCIConnection(const EUI48 &address_, const BDAddressType addressType_, const uint16_t handle_) - : address(address_), addressType(addressType_), handle(handle_) {} + HCIConnection(const BDAddressAndType& addressAndType_, const uint16_t handle_) + : addressAndType(addressAndType_), handle(handle_) {} HCIConnection(const HCIConnection &o) = default; HCIConnection(HCIConnection &&o) = default; HCIConnection& operator=(const HCIConnection &o) = default; HCIConnection& operator=(HCIConnection &&o) = default; - const EUI48 & getAddress() const { return address; } - BDAddressType getAddressType() const { return addressType; } + const BDAddressAndType & getAddressAndType() const { return addressAndType; } uint16_t getHandle() const { return handle; } void setHandle(uint16_t newHandle) { handle = newHandle; } - bool equals(const EUI48 & otherAddress, const BDAddressType otherAddressType) const - { return address == otherAddress && addressType == otherAddressType; } + bool equals(const BDAddressAndType & other) const + { return addressAndType == other; } - bool operator==(const HCIConnection& rhs) const - { return address == rhs.address && addressType == rhs.addressType; } + bool operator==(const HCIConnection& rhs) const { + if( this == &rhs ) { + return true; + } + return addressAndType == rhs.addressAndType; + } bool operator!=(const HCIConnection& rhs) const { return !(*this == rhs); } + std::size_t hash_code() const noexcept { + return addressAndType.hash_code(); + } + std::string toString() const { return "HCIConnection[handle "+jau::uint16HexString(handle)+ - ", address="+address.toString()+", addressType "+getBDAddressTypeString(addressType)+"]"; + ", address "+addressAndType.toString()+"]"; } }; typedef std::shared_ptr<HCIConnection> HCIConnectionRef; @@ -265,20 +271,20 @@ namespace direct_bt { * @param handle ignored for existing tracker _if_ invalid, i.e. zero. */ HCIConnectionRef addOrUpdateHCIConnection(std::vector<HCIConnectionRef> &list, - const EUI48 & address, BDAddressType addrType, const uint16_t handle) noexcept; - HCIConnectionRef addOrUpdateTrackerConnection(const EUI48 & address, BDAddressType addrType, const uint16_t handle) noexcept { - return addOrUpdateHCIConnection(connectionList, address, addrType, handle); + const BDAddressAndType& addressAndType, const uint16_t handle) noexcept; + HCIConnectionRef addOrUpdateTrackerConnection(const BDAddressAndType& addressAndType, const uint16_t handle) noexcept { + return addOrUpdateHCIConnection(connectionList, addressAndType, handle); } - HCIConnectionRef addOrUpdateDisconnectCmd(const EUI48 & address, BDAddressType addrType, const uint16_t handle) noexcept { - return addOrUpdateHCIConnection(disconnectCmdList, address, addrType, handle); + HCIConnectionRef addOrUpdateDisconnectCmd(const BDAddressAndType& addressAndType, const uint16_t handle) noexcept { + return addOrUpdateHCIConnection(disconnectCmdList, addressAndType, handle); } - HCIConnectionRef findHCIConnection(std::vector<HCIConnectionRef> &list, const EUI48 & address, BDAddressType addrType) noexcept; - HCIConnectionRef findTrackerConnection(const EUI48 & address, BDAddressType addrType) noexcept { - return findHCIConnection(connectionList, address, addrType); + HCIConnectionRef findHCIConnection(std::vector<HCIConnectionRef> &list, const BDAddressAndType& addressAndType) noexcept; + HCIConnectionRef findTrackerConnection(const BDAddressAndType& addressAndType) noexcept { + return findHCIConnection(connectionList, addressAndType); } - HCIConnectionRef findDisconnectCmd(const EUI48 & address, BDAddressType addrType) noexcept { - return findHCIConnection(disconnectCmdList, address, addrType); + HCIConnectionRef findDisconnectCmd(const BDAddressAndType& addressAndType) noexcept { + return findHCIConnection(disconnectCmdList, addressAndType); } HCIConnectionRef findTrackerConnection(const uint16_t handle) noexcept; @@ -526,7 +532,7 @@ namespace direct_bt { * BT Core Spec v5.2: Vol 4, Part E HCI: 7.1.6 Disconnect command * </p> */ - HCIStatusCode disconnect(const uint16_t conn_handle, const EUI48 &peer_bdaddr, const BDAddressType peer_mac_type, + HCIStatusCode disconnect(const uint16_t conn_handle, const BDAddressAndType& addressAndType, const HCIStatusCode reason=HCIStatusCode::REMOTE_USER_TERMINATED_CONNECTION) noexcept; /** @@ -602,5 +608,18 @@ namespace direct_bt { } // namespace direct_bt +#if 0 +// Injecting specialization of std::hash to namespace std of our types above +// Would need to make direct_bt::HCIHandler::HCIConnection accessible +namespace std +{ + template<> struct hash<direct_bt::HCIHandler::HCIConnection> { + std::size_t operator()(direct_bt::HCIHandler::HCIConnection const& a) const noexcept { + return a.hash_code(); + } + }; +} +#endif + #endif /* DBT_HANDLER_HPP_ */ diff --git a/api/direct_bt/L2CAPComm.hpp b/api/direct_bt/L2CAPComm.hpp index d16235ff..64979acf 100644 --- a/api/direct_bt/L2CAPComm.hpp +++ b/api/direct_bt/L2CAPComm.hpp @@ -132,9 +132,7 @@ namespace direct_bt { const uint16_t cid; std::recursive_mutex mtx_write; - std::string deviceString; - EUI48 deviceAddress; - BDAddressType deviceAddressType; + BDAddressAndType deviceAddressAndType; std::atomic<int> socket_descriptor; // the l2cap socket std::atomic<bool> is_open; // reflects state std::atomic<bool> has_ioerror; // reflects state diff --git a/api/direct_bt/MgmtTypes.hpp b/api/direct_bt/MgmtTypes.hpp index e0ed1f84..1bec74f4 100644 --- a/api/direct_bt/MgmtTypes.hpp +++ b/api/direct_bt/MgmtTypes.hpp @@ -680,11 +680,11 @@ namespace direct_bt { } public: - MgmtCmdAdressInfoMeta(const Opcode opc, const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType) + MgmtCmdAdressInfoMeta(const Opcode opc, const uint16_t dev_id, const BDAddressAndType& addressAndType) : MgmtCommand(opc, dev_id, 6+1) { - pdu.put_eui48_nc(MGMT_HEADER_SIZE, address); - pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressType)); + pdu.put_eui48_nc(MGMT_HEADER_SIZE, addressAndType.address); + pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressAndType.type)); } virtual ~MgmtCmdAdressInfoMeta() noexcept override {} @@ -699,8 +699,8 @@ namespace direct_bt { class MgmtDisconnectCmd : public MgmtCmdAdressInfoMeta { public: - MgmtDisconnectCmd(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType) - : MgmtCmdAdressInfoMeta(Opcode::DISCONNECT, dev_id, address, addressType) + MgmtDisconnectCmd(const uint16_t dev_id, const BDAddressAndType& addressAndType) + : MgmtCmdAdressInfoMeta(Opcode::DISCONNECT, dev_id, addressAndType) { } }; @@ -764,8 +764,8 @@ namespace direct_bt { class MgmtGetConnectionInfoCmd : public MgmtCmdAdressInfoMeta { public: - MgmtGetConnectionInfoCmd(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType) - : MgmtCmdAdressInfoMeta(Opcode::GET_CONN_INFO, dev_id, address, addressType) + MgmtGetConnectionInfoCmd(const uint16_t dev_id, const BDAddressAndType& addressAndType) + : MgmtCmdAdressInfoMeta(Opcode::GET_CONN_INFO, dev_id, addressAndType) { } }; @@ -784,12 +784,12 @@ namespace direct_bt { } public: - MgmtPinCodeReplyCmd(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType, + MgmtPinCodeReplyCmd(const uint16_t dev_id, const BDAddressAndType& addressAndType, const uint8_t pin_len, const TROOctets &pin_code) : MgmtCommand(Opcode::PIN_CODE_REPLY, dev_id, 6+1+1+16) { - pdu.put_eui48_nc(MGMT_HEADER_SIZE, address); - pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressType)); + pdu.put_eui48_nc(MGMT_HEADER_SIZE, addressAndType.address); + pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressAndType.type)); pdu.put_uint8_nc(MGMT_HEADER_SIZE+7, pin_len); pdu.put_octets_nc(MGMT_HEADER_SIZE+8, pin_code); } @@ -805,8 +805,8 @@ namespace direct_bt { class MgmtPinCodeNegativeReplyCmd : public MgmtCmdAdressInfoMeta { public: - MgmtPinCodeNegativeReplyCmd(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType) - : MgmtCmdAdressInfoMeta(Opcode::PIN_CODE_NEG_REPLY, dev_id, address, addressType) + MgmtPinCodeNegativeReplyCmd(const uint16_t dev_id, const BDAddressAndType& addressAndType) + : MgmtCmdAdressInfoMeta(Opcode::PIN_CODE_NEG_REPLY, dev_id, addressAndType) { } }; @@ -824,11 +824,11 @@ namespace direct_bt { } public: - MgmtPairDeviceCmd(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType, const SMPIOCapability iocap) + MgmtPairDeviceCmd(const uint16_t dev_id, const BDAddressAndType& addressAndType, const SMPIOCapability iocap) : MgmtCommand(Opcode::PAIR_DEVICE, dev_id, 6+1+1) { - pdu.put_eui48_nc(MGMT_HEADER_SIZE, address); - pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressType)); + pdu.put_eui48_nc(MGMT_HEADER_SIZE, addressAndType.address); + pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressAndType.type)); pdu.put_uint8_nc(MGMT_HEADER_SIZE+6+1, direct_bt::number(iocap)); } const EUI48& getAddress() const noexcept { return *reinterpret_cast<const EUI48 *>( pdu.get_ptr_nc(MGMT_HEADER_SIZE + 0) ); } // mgmt_addr_info @@ -842,8 +842,8 @@ namespace direct_bt { class MgmtCancelPairDevice : public MgmtCmdAdressInfoMeta { public: - MgmtCancelPairDevice(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType) - : MgmtCmdAdressInfoMeta(Opcode::CANCEL_PAIR_DEVICE, dev_id, address, addressType) + MgmtCancelPairDevice(const uint16_t dev_id, const BDAddressAndType& addressAndType) + : MgmtCmdAdressInfoMeta(Opcode::CANCEL_PAIR_DEVICE, dev_id, addressAndType) { } }; @@ -862,11 +862,11 @@ namespace direct_bt { } public: - MgmtUnpairDeviceCmd(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType, const bool disconnect) + MgmtUnpairDeviceCmd(const uint16_t dev_id, const BDAddressAndType& addressAndType, const bool disconnect) : MgmtCommand(Opcode::UNPAIR_DEVICE, dev_id, 6+1+1) { - pdu.put_eui48_nc(MGMT_HEADER_SIZE, address); - pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressType)); + pdu.put_eui48_nc(MGMT_HEADER_SIZE, addressAndType.address); + pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressAndType.type)); pdu.put_uint8_nc(MGMT_HEADER_SIZE+6+1, disconnect ? 0x01 : 0x00); } const EUI48& getAddress() const noexcept { return *reinterpret_cast<const EUI48 *>( pdu.get_ptr_nc(MGMT_HEADER_SIZE + 0) ); } // mgmt_addr_info @@ -880,8 +880,8 @@ namespace direct_bt { class MgmtUserConfirmReplyCmd : public MgmtCmdAdressInfoMeta { public: - MgmtUserConfirmReplyCmd(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType) - : MgmtCmdAdressInfoMeta(Opcode::USER_CONFIRM_REPLY, dev_id, address, addressType) + MgmtUserConfirmReplyCmd(const uint16_t dev_id, const BDAddressAndType& addressAndType) + : MgmtCmdAdressInfoMeta(Opcode::USER_CONFIRM_REPLY, dev_id, addressAndType) { } }; @@ -891,8 +891,8 @@ namespace direct_bt { class MgmtUserConfirmNegativeReplyCmd : public MgmtCmdAdressInfoMeta { public: - MgmtUserConfirmNegativeReplyCmd(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType) - : MgmtCmdAdressInfoMeta(Opcode::USER_CONFIRM_NEG_REPLY, dev_id, address, addressType) + MgmtUserConfirmNegativeReplyCmd(const uint16_t dev_id, const BDAddressAndType& addressAndType) + : MgmtCmdAdressInfoMeta(Opcode::USER_CONFIRM_NEG_REPLY, dev_id, addressAndType) { } }; @@ -910,11 +910,11 @@ namespace direct_bt { } public: - MgmtUserPasskeyReplyCmd(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType, const uint32_t passkey) + MgmtUserPasskeyReplyCmd(const uint16_t dev_id, const BDAddressAndType& addressAndType, const uint32_t passkey) : MgmtCommand(Opcode::USER_PASSKEY_REPLY, dev_id, 6+1+4) { - pdu.put_eui48_nc(MGMT_HEADER_SIZE, address); - pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressType)); + pdu.put_eui48_nc(MGMT_HEADER_SIZE, addressAndType.address); + pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressAndType.type)); pdu.put_uint32_nc(MGMT_HEADER_SIZE+6+1, passkey); } const EUI48& getAddress() const noexcept { return *reinterpret_cast<const EUI48 *>( pdu.get_ptr_nc(MGMT_HEADER_SIZE + 0) ); } // mgmt_addr_info @@ -928,8 +928,8 @@ namespace direct_bt { class MgmtUserPasskeyNegativeReplyCmd : public MgmtCmdAdressInfoMeta { public: - MgmtUserPasskeyNegativeReplyCmd(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType) - : MgmtCmdAdressInfoMeta(Opcode::USER_PASSKEY_NEG_REPLY, dev_id, address, addressType) + MgmtUserPasskeyNegativeReplyCmd(const uint16_t dev_id, const BDAddressAndType& addressAndType) + : MgmtCmdAdressInfoMeta(Opcode::USER_PASSKEY_NEG_REPLY, dev_id, addressAndType) { } }; @@ -951,11 +951,11 @@ namespace direct_bt { } public: - MgmtAddDeviceToWhitelistCmd(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType, const HCIWhitelistConnectType ctype) + MgmtAddDeviceToWhitelistCmd(const uint16_t dev_id, const BDAddressAndType& addressAndType, const HCIWhitelistConnectType ctype) : MgmtCommand(Opcode::ADD_DEVICE_WHITELIST, dev_id, 6+1+1) { - pdu.put_eui48_nc(MGMT_HEADER_SIZE, address); - pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressType)); + pdu.put_eui48_nc(MGMT_HEADER_SIZE, addressAndType.address); + pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressAndType.type)); pdu.put_uint8_nc(MGMT_HEADER_SIZE+6+1, direct_bt::number(ctype)); } const EUI48& getAddress() const noexcept { return *reinterpret_cast<const EUI48 *>( pdu.get_ptr_nc(MGMT_HEADER_SIZE + 0) ); } // mgmt_addr_info @@ -969,8 +969,8 @@ namespace direct_bt { class MgmtRemoveDeviceFromWhitelistCmd : public MgmtCmdAdressInfoMeta { public: - MgmtRemoveDeviceFromWhitelistCmd(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType) - : MgmtCmdAdressInfoMeta(Opcode::REMOVE_DEVICE_WHITELIST, dev_id, address, addressType) + MgmtRemoveDeviceFromWhitelistCmd(const uint16_t dev_id, const BDAddressAndType& addressAndType) + : MgmtCmdAdressInfoMeta(Opcode::REMOVE_DEVICE_WHITELIST, dev_id, addressAndType) { } }; @@ -1491,11 +1491,11 @@ namespace direct_bt { { checkOpcode(getOpcode(), Opcode::DEVICE_CONNECTED); } - MgmtEvtDeviceConnected(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType, const uint16_t hci_conn_handle_) + MgmtEvtDeviceConnected(const uint16_t dev_id, const BDAddressAndType& addressAndType, const uint16_t hci_conn_handle_) : MgmtEvent(Opcode::DEVICE_CONNECTED, dev_id, 6+1+4+2), hci_conn_handle(hci_conn_handle_) { - pdu.put_eui48_nc(MGMT_HEADER_SIZE, address); - pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressType)); + pdu.put_eui48_nc(MGMT_HEADER_SIZE, addressAndType.address); + pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressAndType.type)); pdu.put_uint32_nc(MGMT_HEADER_SIZE+6+1, 0); // flags pdu.put_uint16_nc(MGMT_HEADER_SIZE+6+1+4, 0); // eir-len } @@ -1565,13 +1565,13 @@ namespace direct_bt { { checkOpcode(getOpcode(), Opcode::DEVICE_DISCONNECTED); } - MgmtEvtDeviceDisconnected(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType, + MgmtEvtDeviceDisconnected(const uint16_t dev_id, const BDAddressAndType& addressAndType, HCIStatusCode hciReason_, const uint16_t hci_conn_handle_) : MgmtEvent(Opcode::DEVICE_DISCONNECTED, dev_id, 6+1+1), hciReason(hciReason_), hci_conn_handle(hci_conn_handle_) { DisconnectReason disconnectReason = getDisconnectReason(hciReason_); - pdu.put_eui48_nc(MGMT_HEADER_SIZE, address); - pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressType)); + pdu.put_eui48_nc(MGMT_HEADER_SIZE, addressAndType.address); + pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressAndType.type)); pdu.put_uint8_nc(MGMT_HEADER_SIZE+6+1, static_cast<uint8_t>(disconnectReason)); } @@ -1619,11 +1619,11 @@ namespace direct_bt { { checkOpcode(getOpcode(), Opcode::CONNECT_FAILED); } - MgmtEvtDeviceConnectFailed(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType, const HCIStatusCode status) + MgmtEvtDeviceConnectFailed(const uint16_t dev_id, const BDAddressAndType& addressAndType, const HCIStatusCode status) : MgmtEvent(Opcode::CONNECT_FAILED, dev_id, 6+1+1), hciStatus(status) { - pdu.put_eui48_nc(MGMT_HEADER_SIZE, address); - pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressType)); + pdu.put_eui48_nc(MGMT_HEADER_SIZE, addressAndType.address); + pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressAndType.type)); pdu.put_uint8_nc(MGMT_HEADER_SIZE+6+1, static_cast<uint8_t>(MgmtStatus::CONNECT_FAILED)); } const EUI48& getAddress() const noexcept { return *reinterpret_cast<const EUI48 *>( pdu.get_ptr_nc(MGMT_HEADER_SIZE + 0) ); } // mgmt_addr_info @@ -2089,11 +2089,11 @@ namespace direct_bt { } public: - MgmtEvtHCIEncryptionChanged(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType, const HCIStatusCode hci_status, uint8_t hci_enc_enabled) + MgmtEvtHCIEncryptionChanged(const uint16_t dev_id, const BDAddressAndType& addressAndType, const HCIStatusCode hci_status, uint8_t hci_enc_enabled) : MgmtEvent(Opcode::HCI_ENC_CHANGED, dev_id, 6+1+1+1) { - pdu.put_eui48_nc(MGMT_HEADER_SIZE, address); - pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressType)); + pdu.put_eui48_nc(MGMT_HEADER_SIZE, addressAndType.address); + pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressAndType.type)); pdu.put_uint8_nc(MGMT_HEADER_SIZE+6+1, direct_bt::number(hci_status)); pdu.put_uint8_nc(MGMT_HEADER_SIZE+6+1+1, hci_enc_enabled); } @@ -2128,11 +2128,11 @@ namespace direct_bt { } public: - MgmtEvtHCIEncryptionKeyRefreshComplete(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType, const HCIStatusCode hci_status) + MgmtEvtHCIEncryptionKeyRefreshComplete(const uint16_t dev_id, const BDAddressAndType& addressAndType, const HCIStatusCode hci_status) : MgmtEvent(Opcode::HCI_ENC_KEY_REFRESH_COMPLETE, dev_id, 6+1+1) { - pdu.put_eui48_nc(MGMT_HEADER_SIZE, address); - pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressType)); + pdu.put_eui48_nc(MGMT_HEADER_SIZE, addressAndType.address); + pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressAndType.type)); pdu.put_uint8_nc(MGMT_HEADER_SIZE+6+1, direct_bt::number(hci_status)); } @@ -2162,11 +2162,11 @@ namespace direct_bt { } public: - MgmtEvtHCILERemoteUserFeatures(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType, const LEFeatures features_) + MgmtEvtHCILERemoteUserFeatures(const uint16_t dev_id, const BDAddressAndType& addressAndType, const LEFeatures features_) : MgmtEvent(Opcode::HCI_LE_REMOTE_USR_FEATURES, dev_id, 6+1+8) { - pdu.put_eui48_nc(MGMT_HEADER_SIZE, address); - pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressType)); + pdu.put_eui48_nc(MGMT_HEADER_SIZE, addressAndType.address); + pdu.put_uint8_nc(MGMT_HEADER_SIZE+6, direct_bt::number(addressAndType.type)); pdu.put_uint64_nc(MGMT_HEADER_SIZE+6+1, direct_bt::number(features_)); } diff --git a/examples/direct_bt_scanner00/dbt_scanner00.cpp b/examples/direct_bt_scanner00/dbt_scanner00.cpp index 1781f096..1580b96b 100644 --- a/examples/direct_bt_scanner00/dbt_scanner00.cpp +++ b/examples/direct_bt_scanner00/dbt_scanner00.cpp @@ -157,7 +157,7 @@ int main(int argc, char *argv[]) bool ok = true, foundDevice=false; int dev_id = 0; // default bool waitForEnter=false; - EUI48 waitForDevice = EUI48_ANY_DEVICE; + BDAddressAndType waitForDevice = BDAddressAndType::ANY_DEVICE; bool forever = false; /** @@ -182,7 +182,7 @@ int main(int argc, char *argv[]) doHCI_Connect = false; } else if( !strcmp("-mac", argv[i]) && argc > (i+1) ) { std::string macstr = std::string(argv[++i]); - waitForDevice = EUI48(macstr); + waitForDevice = BDAddressAndType(EUI48(macstr), BDAddressType::BDADDR_UNDEFINED); } } fprintf(stderr, "dev_id %d\n", dev_id); @@ -228,8 +228,8 @@ int main(int argc, char *argv[]) while( nullptr == device ) { // FIXME deadlock, waiting forever! cvDeviceFound.wait(lockRead); if( nullptr != deviceFound ) { - foundDevice = deviceFound->getAddress() == waitForDevice; // match - if( foundDevice || ( EUI48_ANY_DEVICE == waitForDevice && deviceFound->isLEAddressType() ) ) { + foundDevice = deviceFound->getAddressAndType().matches(waitForDevice); // match + if( foundDevice || ( BDAddressAndType::ANY_DEVICE == waitForDevice && deviceFound->getAddressAndType().isLEAddress() ) ) { // match or any LE device device.swap(deviceFound); // take over deviceFound } diff --git a/examples/direct_bt_scanner01/dbt_scanner01.cpp b/examples/direct_bt_scanner01/dbt_scanner01.cpp index e139ae78..88939551 100644 --- a/examples/direct_bt_scanner01/dbt_scanner01.cpp +++ b/examples/direct_bt_scanner01/dbt_scanner01.cpp @@ -155,7 +155,7 @@ int main(int argc, char *argv[]) bool ok = true, foundDevice=false; int dev_id = 0; // default bool waitForEnter=false; - EUI48 waitForDevice = EUI48_ANY_DEVICE; + BDAddressAndType waitForDevice = BDAddressAndType::ANY_DEVICE; bool forever = false; /** @@ -180,7 +180,7 @@ int main(int argc, char *argv[]) doHCI_Connect = false; } else if( !strcmp("-mac", argv[i]) && argc > (i+1) ) { std::string macstr = std::string(argv[++i]); - waitForDevice = EUI48(macstr); + waitForDevice = BDAddressAndType(EUI48(macstr), BDAddressType::BDADDR_UNDEFINED); } } fprintf(stderr, "dev_id %d\n", dev_id); @@ -226,8 +226,8 @@ int main(int argc, char *argv[]) while( nullptr == device ) { // FIXME deadlock, waiting forever! cvDeviceFound.wait(lockRead); if( nullptr != deviceFound ) { - foundDevice = deviceFound->getAddress() == waitForDevice; // match - if( foundDevice || ( EUI48_ANY_DEVICE == waitForDevice && deviceFound->isLEAddressType() ) ) { + foundDevice = deviceFound->getAddressAndType().matches(waitForDevice); // match + if( foundDevice || ( BDAddressAndType::ANY_DEVICE == waitForDevice && deviceFound->getAddressAndType().isLEAddress() ) ) { // match or any LE device device.swap(deviceFound); // take over deviceFound } diff --git a/examples/direct_bt_scanner10/dbt_scanner10.cpp b/examples/direct_bt_scanner10/dbt_scanner10.cpp index 99b85e89..803d86e7 100644 --- a/examples/direct_bt_scanner10/dbt_scanner10.cpp +++ b/examples/direct_bt_scanner10/dbt_scanner10.cpp @@ -71,7 +71,7 @@ static bool GATT_PING_ENABLED = false; static bool REMOVE_DEVICE = true; static bool USE_WHITELIST = false; -static std::vector<EUI48> WHITELIST; +static std::vector<BDAddressAndType> WHITELIST; static std::string charIdentifier = ""; static int charValue = 0; @@ -79,7 +79,7 @@ static int charValue = 0; static bool SHOW_UPDATE_EVENTS = false; static bool QUIET = false; -static std::vector<EUI48> waitForDevices; +static std::vector<BDAddressAndType> waitForDevices; const static int NO_PASSKEY = -1; static int pairing_passkey = NO_PASSKEY; @@ -94,28 +94,34 @@ static void removeDevice(std::shared_ptr<DBTDevice> device); static void resetAdapter(DBTAdapter *a, int mode); static bool startDiscovery(DBTAdapter *a, std::string msg); -static std::vector<EUI48> devicesInProcessing; +static std::vector<BDAddressAndType> devicesInProcessing; static std::recursive_mutex mtx_devicesProcessing; static std::recursive_mutex mtx_devicesProcessed; -static std::vector<EUI48> devicesProcessed; +static std::vector<BDAddressAndType> devicesProcessed; -bool contains(std::vector<EUI48> &cont, const EUI48 &mac) { +bool matches(std::vector<BDAddressAndType> &cont, const BDAddressAndType &mac) { + return cont.end() != find_if(cont.begin(), cont.end(), [&](const BDAddressAndType & it)->bool { + return it.matches(mac); + }); +} + +bool contains(std::vector<BDAddressAndType> &cont, const BDAddressAndType &mac) { return cont.end() != find(cont.begin(), cont.end(), mac); } -void printList(const std::string &msg, std::vector<EUI48> &cont) { +void printList(const std::string &msg, std::vector<BDAddressAndType> &cont) { fprintf(stderr, "%s ", msg.c_str()); std::for_each(cont.begin(), cont.end(), - [](const EUI48 &mac) { fprintf(stderr, "%s, ", mac.toString().c_str()); }); + [](const BDAddressAndType &mac) { fprintf(stderr, "%s, ", mac.toString().c_str()); }); fprintf(stderr, "\n"); } -static void addToDevicesProcessed(const EUI48 &a) { +static void addToDevicesProcessed(const BDAddressAndType &a) { const std::lock_guard<std::recursive_mutex> lock(mtx_devicesProcessed); // RAII-style acquire and relinquish via destructor devicesProcessed.push_back(a); } -static bool isDeviceProcessed(const EUI48 & a) { +static bool isDeviceProcessed(const BDAddressAndType & a) { const std::lock_guard<std::recursive_mutex> lock(mtx_devicesProcessed); // RAII-style acquire and relinquish via destructor return contains(devicesProcessed, a); } @@ -123,7 +129,7 @@ static size_t getDeviceProcessedCount() { const std::lock_guard<std::recursive_mutex> lock(mtx_devicesProcessed); // RAII-style acquire and relinquish via destructor return devicesProcessed.size(); } -static bool allDevicesProcessed(std::vector<EUI48> &cont) { +static bool allDevicesProcessed(std::vector<BDAddressAndType> &cont) { const std::lock_guard<std::recursive_mutex> lock(mtx_devicesProcessed); // RAII-style acquire and relinquish via destructor for (auto it = cont.begin(); it != cont.end(); ++it) { if( !contains(devicesProcessed, *it) ) { @@ -137,11 +143,11 @@ static void printDevicesProcessed(const std::string &msg) { printList(msg, devicesProcessed); } -static void addToDevicesProcessing(const EUI48 &a) { +static void addToDevicesProcessing(const BDAddressAndType &a) { const std::lock_guard<std::recursive_mutex> lock(mtx_devicesProcessing); // RAII-style acquire and relinquish via destructor devicesInProcessing.push_back(a); } -static bool removeFromDevicesProcessing(const EUI48 &a) { +static bool removeFromDevicesProcessing(const BDAddressAndType &a) { const std::lock_guard<std::recursive_mutex> lock(mtx_devicesProcessing); // RAII-style acquire and relinquish via destructor for (auto it = devicesInProcessing.begin(); it != devicesInProcessing.end(); ++it) { if ( a == *it ) { @@ -151,7 +157,7 @@ static bool removeFromDevicesProcessing(const EUI48 &a) { } return false; } -static bool isDeviceProcessing(const EUI48 & a) { +static bool isDeviceProcessing(const BDAddressAndType & a) { const std::lock_guard<std::recursive_mutex> lock(mtx_devicesProcessing); // RAII-style acquire and relinquish via destructor return contains(devicesInProcessing, a); } @@ -160,23 +166,24 @@ static size_t getDeviceProcessingCount() { return devicesInProcessing.size(); } -__pack( struct MyLongTermKeyInfo { - EUI48 address; - BDAddressType address_type; +struct MyLongTermKeyInfo { + BDAddressAndType address_and_type; SMPLongTermKeyInfo smp_ltk; bool write(const std::string filename) { if( !smp_ltk.isValid() ) { - fprintf(stderr, "****** WRITE LTK [%s %s, invalid, skipped]: %s\n", - address.toString().c_str(), getBDAddressTypeString(address_type).c_str(), + fprintf(stderr, "****** WRITE LTK [%s, invalid, skipped]: %s\n", + address_and_type.toString().c_str(), smp_ltk.toString().c_str()); return false; } std::ofstream file(filename, std::ios::binary | std::ios::trunc); - file.write((char*)this, sizeof(*this)); + file.write((char*)&address_and_type.address, sizeof(address_and_type.address)); + file.write((char*)&address_and_type.type, sizeof(address_and_type.type)); + file.write((char*)&smp_ltk, sizeof(smp_ltk)); file.close(); - fprintf(stderr, "****** WRITE LTK [%s %s, valid, written]: %s\n", - address.toString().c_str(), getBDAddressTypeString(address_type).c_str(), + fprintf(stderr, "****** WRITE LTK [%s, valid, written]: %s\n", + address_and_type.toString().c_str(), smp_ltk.toString().c_str()); return true; } @@ -186,26 +193,30 @@ __pack( struct MyLongTermKeyInfo { if (!file.is_open() ) { return false; } - file.read((char*)this, sizeof(*this)); + file.read((char*)&address_and_type.address, sizeof(address_and_type.address)); + file.read((char*)&address_and_type.type, sizeof(address_and_type.type)); + file.read((char*)&smp_ltk, sizeof(smp_ltk)); file.close(); - fprintf(stderr, "****** READ LTK [%s %s, valid %d]: %s\n", - address.toString().c_str(), getBDAddressTypeString(address_type).c_str(), + address_and_type.clearHash(); + fprintf(stderr, "****** READ LTK [%s, valid %d]: %s\n", + address_and_type.toString().c_str(), smp_ltk.isValid(), smp_ltk.toString().c_str()); return smp_ltk.isValid(); } -} ); +}; -__pack( struct MySignatureResolvingKeyInfo { - EUI48 address; - BDAddressType address_type; +struct MySignatureResolvingKeyInfo { + BDAddressAndType address_and_type; SMPSignatureResolvingKeyInfo smp_csrk; bool write(const std::string filename) { std::ofstream file(filename, std::ios::binary | std::ios::trunc); - file.write((char*)this, sizeof(*this)); + file.write((char*)&address_and_type.address, sizeof(address_and_type.address)); + file.write((char*)&address_and_type.type, sizeof(address_and_type.type)); + file.write((char*)&smp_csrk, sizeof(smp_csrk)); file.close(); - fprintf(stderr, "****** WRITE CSRK [%s %s, written]: %s\n", - address.toString().c_str(), getBDAddressTypeString(address_type).c_str(), + fprintf(stderr, "****** WRITE CSRK [%s, written]: %s\n", + address_and_type.toString().c_str(), smp_csrk.toString().c_str()); return true; } @@ -215,14 +226,17 @@ __pack( struct MySignatureResolvingKeyInfo { if (!file.is_open() ) { return false; } - file.read((char*)this, sizeof(*this)); + file.read((char*)&address_and_type.address, sizeof(address_and_type.address)); + file.read((char*)&address_and_type.type, sizeof(address_and_type.type)); + file.read((char*)&smp_csrk, sizeof(smp_csrk)); file.close(); - fprintf(stderr, "****** READ CSRK [%s %s]: %s\n", - address.toString().c_str(), getBDAddressTypeString(address_type).c_str(), + address_and_type.clearHash(); + fprintf(stderr, "****** READ CSRK %s: %s\n", + address_and_type.toString().c_str(), smp_csrk.toString().c_str()); return true; } -} ); +}; class MyAdapterStatusListener : public AdapterStatusListener { @@ -258,16 +272,16 @@ class MyAdapterStatusListener : public AdapterStatusListener { void deviceFound(std::shared_ptr<DBTDevice> device, const uint64_t timestamp) override { (void)timestamp; - if( BDAddressType::BDADDR_LE_PUBLIC != device->getAddressType() - && BLERandomAddressType::STATIC_PUBLIC != device->getBLERandomAddressType() ) { + if( BDAddressType::BDADDR_LE_PUBLIC != device->getAddressAndType().type + && BLERandomAddressType::STATIC_PUBLIC != device->getAddressAndType().getBLERandomAddressType() ) { // Requires BREDR or LE Secure Connection support: WIP fprintf(stderr, "****** FOUND__-2: Skip non 'public LE' and non 'random static public LE' %s\n", device->toString(true).c_str()); return; } - if( !isDeviceProcessing( device->getAddress() ) && + if( !isDeviceProcessing( device->getAddressAndType() ) && ( waitForDevices.empty() || - ( contains(waitForDevices, device->getAddress()) && - ( 0 < MULTI_MEASUREMENTS || !isDeviceProcessed(device->getAddress()) ) + ( matches(waitForDevices, device->getAddressAndType()) && + ( 0 < MULTI_MEASUREMENTS || !isDeviceProcessed(device->getAddressAndType()) ) ) ) ) @@ -348,17 +362,17 @@ class MyAdapterStatusListener : public AdapterStatusListener { void deviceReady(std::shared_ptr<DBTDevice> device, const uint64_t timestamp) override { (void)timestamp; - if( !isDeviceProcessing( device->getAddress() ) && + if( !isDeviceProcessing( device->getAddressAndType() ) && ( waitForDevices.empty() || - ( contains(waitForDevices, device->getAddress()) && - ( 0 < MULTI_MEASUREMENTS || !isDeviceProcessed(device->getAddress()) ) + ( matches(waitForDevices, device->getAddressAndType()) && + ( 0 < MULTI_MEASUREMENTS || !isDeviceProcessed(device->getAddressAndType()) ) ) ) ) { deviceReadyCount++; fprintf(stderr, "****** READY-0: Processing[%d] %s\n", deviceReadyCount.load(), device->toString(true).c_str()); - addToDevicesProcessing(device->getAddress()); + addToDevicesProcessing(device->getAddressAndType()); processReadyDevice(device); // AdapterStatusListener::deviceReady() explicitly allows prolonged and complex code execution! } else { fprintf(stderr, "****** READY-1: NOP %s\n", device->toString(true).c_str()); @@ -375,7 +389,7 @@ class MyAdapterStatusListener : public AdapterStatusListener { std::thread dc(::removeDevice, device); // @suppress("Invalid arguments") dc.detach(); } else { - removeFromDevicesProcessing(device->getAddress()); + removeFromDevicesProcessing(device->getAddressAndType()); } if( 0 < RESET_ADAPTER_EACH_CONN && 0 == deviceReadyCount % RESET_ADAPTER_EACH_CONN ) { std::thread dc(::resetAdapter, &device->getAdapter(), 1); // @suppress("Invalid arguments") @@ -442,8 +456,8 @@ static void connectDiscoveredDevice(std::shared_ptr<DBTDevice> device) { { MyLongTermKeyInfo my_ltk_resp; MyLongTermKeyInfo my_ltk_init; - if( my_ltk_init.read(device->getAddress().toString()+".init.ltk") && - my_ltk_resp.read(device->getAddress().toString()+".resp.ltk") && + if( my_ltk_init.read(device->getAddressAndType().toString()+".init.ltk") && + my_ltk_resp.read(device->getAddressAndType().toString()+".resp.ltk") && HCIStatusCode::SUCCESS == device->setLongTermKeyInfo(my_ltk_init.smp_ltk) && HCIStatusCode::SUCCESS == device->setLongTermKeyInfo(my_ltk_resp.smp_ltk) ) { fprintf(stderr, "****** Connecting Device: Loaded LTKs from file successfully\n"); @@ -481,25 +495,25 @@ static void processReadyDevice(std::shared_ptr<DBTDevice> device) { const SMPKeyType keys_init = device->getAvailableSMPKeys(false /* responder */); if( ( SMPKeyType::ENC_KEY & keys_init ) != SMPKeyType::NONE ) { - MyLongTermKeyInfo my_ltk { device->getAddress(), device->getAddressType(), + MyLongTermKeyInfo my_ltk { device->getAddressAndType(), device->getLongTermKeyInfo(false /* responder */) }; - my_ltk.write(my_ltk.address.toString()+".init.ltk"); + my_ltk.write(my_ltk.address_and_type.toString()+".init.ltk"); } if( ( SMPKeyType::ENC_KEY & keys_resp ) != SMPKeyType::NONE ) { - MyLongTermKeyInfo my_ltk { device->getAddress(), device->getAddressType(), + MyLongTermKeyInfo my_ltk { device->getAddressAndType(), device->getLongTermKeyInfo(true /* responder */) }; - my_ltk.write(my_ltk.address.toString()+".resp.ltk"); + my_ltk.write(my_ltk.address_and_type.toString()+".resp.ltk"); } if( ( SMPKeyType::SIGN_KEY & keys_init ) != SMPKeyType::NONE ) { - MySignatureResolvingKeyInfo my_csrk { device->getAddress(), device->getAddressType(), + MySignatureResolvingKeyInfo my_csrk { device->getAddressAndType(), device->getSignatureResolvingKeyInfo(false /* responder */) }; - my_csrk.write(my_csrk.address.toString()+".init.csrk"); + my_csrk.write(my_csrk.address_and_type.toString()+".init.csrk"); } if( ( SMPKeyType::SIGN_KEY & keys_resp ) != SMPKeyType::NONE ) { - MySignatureResolvingKeyInfo my_csrk { device->getAddress(), device->getAddressType(), + MySignatureResolvingKeyInfo my_csrk { device->getAddressAndType(), device->getSignatureResolvingKeyInfo(true /* responder */) }; - my_csrk.write(my_csrk.address.toString()+".resp.csrk"); + my_csrk.write(my_csrk.address_and_type.toString()+".resp.csrk"); } } } @@ -507,7 +521,7 @@ static void processReadyDevice(std::shared_ptr<DBTDevice> device) { // // GATT Service Processing // - fprintf(stderr, "****** Processing Ready Device: GATT start: %s\n", device->getAddressString().c_str()); + fprintf(stderr, "****** Processing Ready Device: GATT start: %s\n", device->getAddressAndType().toString().c_str()); if( !QUIET ) { device->getAdapter().printSharedPtrListOfDevices(); } @@ -626,10 +640,10 @@ exit: if( KEEP_CONNECTED && GATT_PING_ENABLED && success ) { while( device->pingGATT() ) { - fprintf(stderr, "****** Processing Ready Device: pingGATT OK: %s\n", device->getAddressString().c_str()); + fprintf(stderr, "****** Processing Ready Device: pingGATT OK: %s\n", device->getAddressAndType().toString().c_str()); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } - fprintf(stderr, "****** Processing Ready Device: pingGATT failed, waiting for disconnect: %s\n", device->getAddressString().c_str()); + fprintf(stderr, "****** Processing Ready Device: pingGATT failed, waiting for disconnect: %s\n", device->getAddressAndType().toString().c_str()); // Even w/ GATT_PING_ENABLED, we utilize disconnect event to clean up -> remove } @@ -643,11 +657,11 @@ exit: success, device->toString().c_str(), getDeviceProcessingCount()); if( success ) { - addToDevicesProcessed(device->getAddress()); + addToDevicesProcessed(device->getAddressAndType()); } if( !KEEP_CONNECTED ) { - removeFromDevicesProcessing(device->getAddress()); + removeFromDevicesProcessing(device->getAddressAndType()); if( UNPAIR_DEVICE_POST ) { const HCIStatusCode unpair_res = device->unpair(); @@ -665,15 +679,15 @@ exit: if( 0 < MULTI_MEASUREMENTS ) { MULTI_MEASUREMENTS--; - fprintf(stderr, "****** Processing Ready Device: MULTI_MEASUREMENTS left %d: %s\n", MULTI_MEASUREMENTS.load(), device->getAddressString().c_str()); + fprintf(stderr, "****** Processing Ready Device: MULTI_MEASUREMENTS left %d: %s\n", MULTI_MEASUREMENTS.load(), device->getAddressAndType().toString().c_str()); } } static void removeDevice(std::shared_ptr<DBTDevice> device) { - fprintf(stderr, "****** Remove Device: removing: %s\n", device->getAddressString().c_str()); + fprintf(stderr, "****** Remove Device: removing: %s\n", device->getAddressAndType().toString().c_str()); device->getAdapter().stopDiscovery(); - removeFromDevicesProcessing(device->getAddress()); + removeFromDevicesProcessing(device->getAddressAndType()); device->remove(); @@ -728,7 +742,7 @@ static std::shared_ptr<DBTAdapter> createAdapter(const int dev_id0, const bool v if( USE_WHITELIST ) { for (auto it = WHITELIST.begin(); it != WHITELIST.end(); ++it) { - bool res = adapter->addDeviceToWhitelist(*it, BDAddressType::BDADDR_LE_PUBLIC, HCIWhitelistConnectType::HCI_AUTO_CONN_ALWAYS); + bool res = adapter->addDeviceToWhitelist(*it, HCIWhitelistConnectType::HCI_AUTO_CONN_ALWAYS); fprintf(stderr, "Added to WHITELIST: res %d, address %s\n", res, it->toString().c_str()); } } else { @@ -869,12 +883,13 @@ int main(int argc, char *argv[]) QUIET = true; } else if( !strcmp("-mac", argv[i]) && argc > (i+1) ) { std::string macstr = std::string(argv[++i]); - waitForDevices.push_back( EUI48(macstr) ); + BDAddressAndType mac(EUI48(macstr), BDAddressType::BDADDR_UNDEFINED); + waitForDevices.push_back( mac ); } else if( !strcmp("-wl", argv[i]) && argc > (i+1) ) { std::string macstr = std::string(argv[++i]); - EUI48 wlmac(macstr); - fprintf(stderr, "Whitelist + %s\n", wlmac.toString().c_str()); - WHITELIST.push_back( wlmac ); + BDAddressAndType wle(EUI48(macstr), BDAddressType::BDADDR_LE_PUBLIC); + fprintf(stderr, "Whitelist + %s\n", wle.toString().c_str()); + WHITELIST.push_back( wle ); USE_WHITELIST = true; } else if( !strcmp("-passkey", argv[i]) && argc > (i+1) ) { pairing_passkey = atoi(argv[++i]); diff --git a/examples/java/AsyncTinyB.java b/examples/java/AsyncTinyB.java index ed0d49be..04607852 100644 --- a/examples/java/AsyncTinyB.java +++ b/examples/java/AsyncTinyB.java @@ -16,7 +16,7 @@ public class AsyncTinyB { static boolean running = true; static void printDevice(final BluetoothDevice device) { - System.out.print("Address = " + device.getAddress()); + System.out.print("Address = " + device.getAddressAndType()); System.out.print(" Name = " + device.getName()); System.out.print(" Connected = " + device.getConnected()); System.out.println(); diff --git a/examples/java/DBTScanner10.java b/examples/java/DBTScanner10.java index c5b1ebeb..a2860fe8 100644 --- a/examples/java/DBTScanner10.java +++ b/examples/java/DBTScanner10.java @@ -43,9 +43,10 @@ import java.util.function.Predicate; import org.tinyb.AdapterSettings; import org.tinyb.BluetoothAdapter; -import org.tinyb.BluetoothAddressType; +import org.tinyb.BDAddressType; import org.tinyb.BluetoothDevice; import org.tinyb.AdapterStatusListener; +import org.tinyb.BDAddressAndType; import org.tinyb.BLERandomAddressType; import org.tinyb.BTMode; import org.tinyb.BTSecurityLevel; @@ -82,7 +83,7 @@ import direct_bt.tinyb.DBTManager; * </p> */ public class DBTScanner10 { - final List<EUI48> waitForDevices = new ArrayList<EUI48>(); + final List<BDAddressAndType> waitForDevices = new ArrayList<BDAddressAndType>(); static final int NO_PASSKEY = -1; int pairing_passkey = NO_PASSKEY; @@ -102,7 +103,7 @@ public class DBTScanner10 { boolean GATT_PING_ENABLED = false; boolean REMOVE_DEVICE = true; boolean USE_WHITELIST = false; - final List<EUI48> whitelist = new ArrayList<EUI48>(); + final List<BDAddressAndType> whitelist = new ArrayList<BDAddressAndType>(); String charIdentifier = null; int charValue = 0; @@ -142,24 +143,21 @@ public class DBTScanner10 { } static public class MyLongTermKeyInfo { - EUI48 address; - BluetoothAddressType address_type; + BDAddressAndType address_and_type; SMPLongTermKeyInfo smp_ltk; - MyLongTermKeyInfo(final EUI48 address, final BluetoothAddressType address_type, final SMPLongTermKeyInfo smp_ltk) { - this.address = address; - this.address_type = address_type; + MyLongTermKeyInfo(final BDAddressAndType address_and_type, final SMPLongTermKeyInfo smp_ltk) { + this.address_and_type = address_and_type; this.smp_ltk = smp_ltk; } MyLongTermKeyInfo() { - address = new EUI48(); - address_type = BluetoothAddressType.BDADDR_UNDEFINED; + address_and_type = new BDAddressAndType(); smp_ltk = new SMPLongTermKeyInfo(); } boolean write(final String filename) { if( !smp_ltk.isValid() ) { - println("****** WRITE LTK ["+address+" "+address_type+", invalid, skipped]: "+smp_ltk+" (write)"); + println("****** WRITE LTK ["+address_and_type+", invalid, skipped]: "+smp_ltk+" (write)"); return false; } final File file = new File(filename); @@ -167,12 +165,12 @@ public class DBTScanner10 { try { file.delete(); // alternative to truncate, if existing out = new FileOutputStream(file); - out.write(address.b); - out.write(address_type.value); + out.write(address_and_type.address.b); + out.write(address_and_type.type.value); final byte[] smp_ltk_b = new byte[SMPLongTermKeyInfo.byte_size]; smp_ltk.getStream(smp_ltk_b, 0); out.write(smp_ltk_b); - println("****** WRITE LTK ["+address+" "+address_type+", valid, written]: "+smp_ltk); + println("****** WRITE LTK ["+address_and_type+", valid, written]: "+smp_ltk); return true; } catch (final Exception ex) { ex.printStackTrace(); @@ -198,10 +196,10 @@ public class DBTScanner10 { if( read_count != buffer.length ) { throw new IOException("Couldn't read "+buffer.length+" bytes, only "+read_count+" from "+filename); } - address.putStream(buffer, 0); - address_type = BluetoothAddressType.get(buffer[6]); + address_and_type.address.putStream(buffer, 0); + address_and_type.type = BDAddressType.get(buffer[6]); smp_ltk.putStream(buffer, 6+1); - println("****** READ LTK ["+address+" "+address_type+", valid "+smp_ltk.isValid()+"]: "+smp_ltk); + println("****** READ LTK ["+address_and_type+", valid "+smp_ltk.isValid()+"]: "+smp_ltk); return smp_ltk.isValid(); } catch (final Exception ex) { ex.printStackTrace(); @@ -218,18 +216,15 @@ public class DBTScanner10 { } } static public class MySignatureResolvingKeyInfo { - EUI48 address; - BluetoothAddressType address_type; + BDAddressAndType address_and_type; SMPSignatureResolvingKeyInfo smp_csrk; - MySignatureResolvingKeyInfo(final EUI48 address, final BluetoothAddressType address_type, final SMPSignatureResolvingKeyInfo smp_csrk) { - this.address = address; - this.address_type = address_type; + MySignatureResolvingKeyInfo(final BDAddressAndType address_and_type, final SMPSignatureResolvingKeyInfo smp_csrk) { + this.address_and_type = address_and_type; this.smp_csrk = smp_csrk; } MySignatureResolvingKeyInfo() { - address = new EUI48(); - address_type = BluetoothAddressType.BDADDR_UNDEFINED; + address_and_type = new BDAddressAndType(); smp_csrk = new SMPSignatureResolvingKeyInfo(); } @@ -239,12 +234,12 @@ public class DBTScanner10 { try { file.delete(); // alternative to truncate, if existing out = new FileOutputStream(file); - out.write(address.b); - out.write(address_type.value); + out.write(address_and_type.address.b); + out.write(address_and_type.type.value); final byte[] smp_ltk_b = new byte[SMPSignatureResolvingKeyInfo.byte_size]; smp_csrk.getStream(smp_ltk_b, 0); out.write(smp_ltk_b); - println("****** WRITE CSRK ["+address+" "+address_type+", written]: "+smp_csrk); + println("****** WRITE CSRK ["+address_and_type+", written]: "+smp_csrk); return true; } catch (final Exception ex) { ex.printStackTrace(); @@ -270,10 +265,10 @@ public class DBTScanner10 { if( read_count != buffer.length ) { throw new IOException("Couldn't read "+buffer.length+" bytes, only "+read_count+" from "+filename); } - address.putStream(buffer, 0); - address_type = BluetoothAddressType.get(buffer[6]); + address_and_type.address.putStream(buffer, 0); + address_and_type.type = BDAddressType.get(buffer[6]); smp_csrk.putStream(buffer, 6+1); - println("****** READ CSRK ["+address+" "+address_type+"]: "+smp_csrk); + println("****** READ CSRK ["+address_and_type+"]: "+smp_csrk); return true; } catch (final Exception ex) { ex.printStackTrace(); @@ -289,8 +284,8 @@ public class DBTScanner10 { return false; } } - Collection<EUI48> devicesInProcessing = Collections.synchronizedCollection(new ArrayList<>()); - Collection<EUI48> devicesProcessed = Collections.synchronizedCollection(new ArrayList<>()); + Collection<BDAddressAndType> devicesInProcessing = Collections.synchronizedCollection(new ArrayList<>()); + Collection<BDAddressAndType> devicesProcessed = Collections.synchronizedCollection(new ArrayList<>()); final AdapterStatusListener statusListener = new AdapterStatusListener() { @Override @@ -323,16 +318,16 @@ public class DBTScanner10 { public void deviceFound(final BluetoothDevice device, final long timestamp) { println("****** FOUND__: "+device.toString()); - if( BluetoothAddressType.BDADDR_LE_PUBLIC != device.getAddressType() - && BLERandomAddressType.STATIC_PUBLIC != device.getBLERandomAddressType() ) { + if( BDAddressType.BDADDR_LE_PUBLIC != device.getAddressAndType().type + && BLERandomAddressType.STATIC_PUBLIC != device.getAddressAndType().getBLERandomAddressType() ) { // Requires BREDR or LE Secure Connection support: WIP println("****** FOUND__-2: Skip non 'public LE' and non 'random static public LE' "+device.toString()); return; } - if( !devicesInProcessing.contains( device.getAddress() ) && + if( !devicesInProcessing.contains( device.getAddressAndType() ) && ( waitForDevices.isEmpty() || - ( waitForDevices.contains( device.getAddress() ) && - ( 0 < MULTI_MEASUREMENTS.get() || !devicesProcessed.contains( device.getAddress() ) ) + ( waitForDevices.contains( device.getAddressAndType() ) && + ( 0 < MULTI_MEASUREMENTS.get() || !devicesProcessed.contains( device.getAddressAndType() ) ) ) ) ) @@ -343,7 +338,7 @@ public class DBTScanner10 { println("PERF: adapter-init -> FOUND__-0 " + td + " ms"); } executeOffThread( () -> { connectDiscoveredDevice(device); }, - "DBT-Connect-"+device.getAddress(), true /* detach */); + "DBT-Connect-"+device.getAddressAndType(), true /* detach */); } else { println("****** FOUND__-1: NOP "+device.toString()); } @@ -382,12 +377,12 @@ public class DBTScanner10 { break; case PASSKEY_EXPECTED: { if( pairing_passkey != NO_PASSKEY ) { - executeOffThread( () -> { device.setPairingPasskey(pairing_passkey); }, "DBT-SetPasskey-"+device.getAddress(), true /* detach */); + executeOffThread( () -> { device.setPairingPasskey(pairing_passkey); }, "DBT-SetPasskey-"+device.getAddressAndType(), true /* detach */); } // next: KEY_DISTRIBUTION or FAILED } break; case NUMERIC_COMPARE_EXPECTED: { - executeOffThread( () -> { device.setPairingNumericComparison(true); }, "DBT-SetNumericComp-"+device.getAddress(), true /* detach */); + executeOffThread( () -> { device.setPairingNumericComparison(true); }, "DBT-SetNumericComp-"+device.getAddressAndType(), true /* detach */); // next: KEY_DISTRIBUTION or FAILED } break; case OOB_EXPECTED: @@ -406,10 +401,10 @@ public class DBTScanner10 { @Override public void deviceReady(final BluetoothDevice device, final long timestamp) { - if( !devicesInProcessing.contains( device.getAddress() ) && + if( !devicesInProcessing.contains( device.getAddressAndType() ) && ( waitForDevices.isEmpty() || - ( waitForDevices.contains( device.getAddress() ) && - ( 0 < MULTI_MEASUREMENTS.get() || !devicesProcessed.contains( device.getAddress() ) ) + ( waitForDevices.contains( device.getAddressAndType() ) && + ( 0 < MULTI_MEASUREMENTS.get() || !devicesProcessed.contains( device.getAddressAndType() ) ) ) ) ) @@ -420,7 +415,7 @@ public class DBTScanner10 { final long td = BluetoothUtils.currentTimeMillis() - timestamp_t0; // adapter-init -> now println("PERF: adapter-init -> READY-0 " + td + " ms"); } - devicesInProcessing.add(device.getAddress()); + devicesInProcessing.add(device.getAddressAndType()); processReadyDevice(device); // AdapterStatusListener::deviceReady() explicitly allows prolonged and complex code execution! } else { println("****** READY-1: NOP " + device.toString()); @@ -432,9 +427,9 @@ public class DBTScanner10 { println("****** DISCONNECTED: Reason "+reason+", old handle 0x"+Integer.toHexString(handle)+": "+device+" on "+device.getAdapter()); if( REMOVE_DEVICE ) { - executeOffThread( () -> { removeDevice(device); }, "DBT-Remove-"+device.getAddress(), true /* detach */); + executeOffThread( () -> { removeDevice(device); }, "DBT-Remove-"+device.getAddressAndType(), true /* detach */); } else { - devicesInProcessing.remove(device.getAddress()); + devicesInProcessing.remove(device.getAddressAndType()); } if( 0 < RESET_ADAPTER_EACH_CONN && 0 == deviceReadyCount.get() % RESET_ADAPTER_EACH_CONN ) { executeOffThread( () -> { resetAdapter(device.getAdapter(), 1); }, @@ -459,8 +454,8 @@ public class DBTScanner10 { { final MyLongTermKeyInfo my_ltk_resp = new MyLongTermKeyInfo(); final MyLongTermKeyInfo my_ltk_init = new MyLongTermKeyInfo(); - if( my_ltk_init.read(device.getAddress().toString()+".init.ltk") && - my_ltk_resp.read(device.getAddress().toString()+".resp.ltk") && + if( my_ltk_init.read(device.getAddressAndType().toString()+".init.ltk") && + my_ltk_resp.read(device.getAddressAndType().toString()+".resp.ltk") && HCIStatusCode.SUCCESS == device.setLongTermKeyInfo(my_ltk_init.smp_ltk) && HCIStatusCode.SUCCESS == device.setLongTermKeyInfo(my_ltk_resp.smp_ltk) ) { println("****** Connecting Device: Loaded LTKs from file successfully\n"); @@ -525,25 +520,25 @@ public class DBTScanner10 { final SMPKeyMask keys_init = device.getAvailableSMPKeys(false /* responder */); if( keys_init.isSet(SMPKeyMask.KeyType.ENC_KEY) ) { - final MyLongTermKeyInfo my_ltk = new MyLongTermKeyInfo(device.getAddress(), device.getAddressType(), + final MyLongTermKeyInfo my_ltk = new MyLongTermKeyInfo(device.getAddressAndType(), device.getLongTermKeyInfo(false /* responder */)); - my_ltk.write(my_ltk.address.toString()+".init.ltk"); + my_ltk.write(my_ltk.address_and_type.toString()+".init.ltk"); } if( keys_resp.isSet(SMPKeyMask.KeyType.ENC_KEY) ) { - final MyLongTermKeyInfo my_ltk = new MyLongTermKeyInfo(device.getAddress(), device.getAddressType(), + final MyLongTermKeyInfo my_ltk = new MyLongTermKeyInfo(device.getAddressAndType(), device.getLongTermKeyInfo(true /* responder */)); - my_ltk.write(my_ltk.address.toString()+".resp.ltk"); + my_ltk.write(my_ltk.address_and_type.toString()+".resp.ltk"); } if( keys_init.isSet(SMPKeyMask.KeyType.SIGN_KEY) ) { - final MySignatureResolvingKeyInfo my_csrk = new MySignatureResolvingKeyInfo(device.getAddress(), device.getAddressType(), + final MySignatureResolvingKeyInfo my_csrk = new MySignatureResolvingKeyInfo(device.getAddressAndType(), device.getSignatureResolvingKeyInfo(false /* responder */)); - my_csrk.write(my_csrk.address.toString()+".init.csrk"); + my_csrk.write(my_csrk.address_and_type.toString()+".init.csrk"); } if( keys_resp.isSet(SMPKeyMask.KeyType.SIGN_KEY) ) { - final MySignatureResolvingKeyInfo my_csrk = new MySignatureResolvingKeyInfo(device.getAddress(), device.getAddressType(), + final MySignatureResolvingKeyInfo my_csrk = new MySignatureResolvingKeyInfo(device.getAddressAndType(), device.getSignatureResolvingKeyInfo(true /* responder */)); - my_csrk.write(my_csrk.address.toString()+".resp.csrk"); + my_csrk.write(my_csrk.address_and_type.toString()+".resp.csrk"); } } } @@ -692,25 +687,25 @@ public class DBTScanner10 { if( KEEP_CONNECTED && GATT_PING_ENABLED && success ) { while( device.pingGATT() ) { - println("****** Processing Ready Device: pingGATT OK: "+device.getAddress()); + println("****** Processing Ready Device: pingGATT OK: "+device.getAddressAndType()); try { Thread.sleep(1000); } catch (final InterruptedException e) { e.printStackTrace(); } } - println("****** Processing Ready Device: pingGATT failed, waiting for disconnect: "+device.getAddress()); + println("****** Processing Ready Device: pingGATT failed, waiting for disconnect: "+device.getAddressAndType()); // Even w/ GATT_PING_ENABLED, we utilize disconnect event to clean up -> remove } println("****** Processing Ready Device: End: Success " + success + " on " + device.toString() + "; devInProc "+devicesInProcessing.size()); if( success ) { - devicesProcessed.add(device.getAddress()); + devicesProcessed.add(device.getAddressAndType()); } if( !KEEP_CONNECTED ) { - devicesInProcessing.remove(device.getAddress()); + devicesInProcessing.remove(device.getAddressAndType()); if( UNPAIR_DEVICE_POST ) { final HCIStatusCode unpair_res = device.unpair(); @@ -728,15 +723,15 @@ public class DBTScanner10 { if( 0 < MULTI_MEASUREMENTS.get() ) { MULTI_MEASUREMENTS.decrementAndGet(); - println("****** Processing Ready Device: MULTI_MEASUREMENTS left "+MULTI_MEASUREMENTS.get()+": "+device.getAddress()); + println("****** Processing Ready Device: MULTI_MEASUREMENTS left "+MULTI_MEASUREMENTS.get()+": "+device.getAddressAndType()); } } private void removeDevice(final BluetoothDevice device) { - println("****** Remove Device: removing: "+device.getAddress()); + println("****** Remove Device: removing: "+device.getAddressAndType()); device.getAdapter().stopDiscovery(); - devicesInProcessing.remove(device.getAddress()); + devicesInProcessing.remove(device.getAddressAndType()); device.remove(); @@ -774,9 +769,9 @@ public class DBTScanner10 { adapter.enablePoweredNotifications(new BooleanNotification("Powered", timestamp_t0)); if( USE_WHITELIST ) { - for(final Iterator<EUI48> wliter = whitelist.iterator(); wliter.hasNext(); ) { - final EUI48 addr = wliter.next(); - final boolean res = adapter.addDeviceToWhitelist(addr, BluetoothAddressType.BDADDR_LE_PUBLIC, HCIWhitelistConnectType.HCI_AUTO_CONN_ALWAYS); + for(final Iterator<BDAddressAndType> wliter = whitelist.iterator(); wliter.hasNext(); ) { + final BDAddressAndType addr = wliter.next(); + final boolean res = adapter.addDeviceToWhitelist(addr, HCIWhitelistConnectType.HCI_AUTO_CONN_ALWAYS); println("Added to whitelist: res "+res+", address "+addr); } } else { @@ -936,11 +931,12 @@ public class DBTScanner10 { } 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) ) { - test.waitForDevices.add(new EUI48(args[++i])); + final BDAddressAndType a = new BDAddressAndType(new EUI48(args[++i]), BDAddressType.BDADDR_LE_PUBLIC); + test.waitForDevices.add(a); } else if( arg.equals("-wl") && args.length > (i+1) ) { - final EUI48 addr = new EUI48(args[++i]); - println("Whitelist + "+addr); - test.whitelist.add(addr); + final BDAddressAndType wle = new BDAddressAndType(new EUI48(args[++i]), BDAddressType.BDADDR_LE_PUBLIC); + println("Whitelist + "+wle); + test.whitelist.add(wle); test.USE_WHITELIST = true; } else if( arg.equals("-passkey") && args.length > (i+1) ) { test.pairing_passkey = Integer.valueOf(args[++i]).intValue(); diff --git a/examples/java/HelloTinyB.java b/examples/java/HelloTinyB.java index 6ea6a493..1aa738c2 100644 --- a/examples/java/HelloTinyB.java +++ b/examples/java/HelloTinyB.java @@ -5,19 +5,22 @@ import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; +import org.tinyb.BDAddressAndType; +import org.tinyb.BDAddressType; import org.tinyb.BluetoothDevice; import org.tinyb.BluetoothException; import org.tinyb.BluetoothFactory; import org.tinyb.BluetoothGattCharacteristic; import org.tinyb.BluetoothGattService; import org.tinyb.BluetoothManager; +import org.tinyb.EUI48; import org.tinyb.HCIStatusCode; public class HelloTinyB { static boolean running = true; static void printDevice(final BluetoothDevice device) { - System.out.print("Address = " + device.getAddress()); + System.out.print("Address = " + device.getAddressAndType()); System.out.print(" Name = " + device.getName()); System.out.print(" Connected = " + device.getConnected()); System.out.println(); @@ -32,7 +35,7 @@ public class HelloTinyB { * getDevices method. We can the look through the list of devices to find the device with the MAC which we provided * as a parameter. We continue looking until we find it, or we try 15 times (1 minutes). */ - static BluetoothDevice getDevice(final BluetoothManager manager, final String address) throws InterruptedException { + static BluetoothDevice getDevice(final BluetoothManager manager, final BDAddressAndType addressAndType) throws InterruptedException { BluetoothDevice sensor = null; for (int i = 0; (i < 15) && running; ++i) { final List<BluetoothDevice> list = manager.getDevices(); @@ -44,8 +47,9 @@ public class HelloTinyB { /* * Here we check if the address matches. */ - if (device.getAddress().equals(address)) + if (device.getAddressAndType().matches(addressAndType)) { sensor = device; + } } if (sensor != null) { @@ -132,7 +136,7 @@ public class HelloTinyB { final boolean discoveryStarted = manager.startDiscovery(); System.out.println("The discovery started: " + (discoveryStarted ? "true" : "false")); - final BluetoothDevice sensor = getDevice(manager, args[0]); + final BluetoothDevice sensor = getDevice(manager, new BDAddressAndType(new EUI48(args[0]), BDAddressType.BDADDR_UNDEFINED)); /* * After we find the device we can stop looking for other devices. diff --git a/examples/java/Notification.java b/examples/java/Notification.java index 8d54017d..d39fb75d 100644 --- a/examples/java/Notification.java +++ b/examples/java/Notification.java @@ -79,7 +79,7 @@ public class Notification { static boolean running = true; static void printDevice(final BluetoothDevice device) { - System.out.print("Address = " + device.getAddress()); + System.out.print("Address = " + device.getAddressAndType()); System.out.print(" Name = " + device.getName()); System.out.print(" Connected = " + device.getConnected()); System.out.println(); diff --git a/examples/java/ScannerTinyB00.java b/examples/java/ScannerTinyB00.java index b36bc0c9..3c125c18 100644 --- a/examples/java/ScannerTinyB00.java +++ b/examples/java/ScannerTinyB00.java @@ -27,6 +27,8 @@ import java.lang.reflect.InvocationTargetException; import java.util.Iterator; import java.util.List; +import org.tinyb.BDAddressAndType; +import org.tinyb.BDAddressType; import org.tinyb.BluetoothAdapter; import org.tinyb.BluetoothDevice; import org.tinyb.BluetoothException; @@ -57,7 +59,7 @@ public class ScannerTinyB00 { public static void main(final String[] args) throws InterruptedException { String bluetoothManagerClazzName = BluetoothFactory.DirectBTImplementationID.BluetoothManagerClassName; int dev_id = 0; // default - EUI48 mac = null; + BDAddressAndType mac = null; int mode = 0; boolean forever = false; @@ -67,7 +69,7 @@ public class ScannerTinyB00 { if( arg.equals("-dev_id") && args.length > (i+1) ) { dev_id = Integer.valueOf(args[++i]).intValue(); } else if( arg.equals("-mac") ) { - mac = new EUI48( args[++i] ); + mac = new BDAddressAndType(new EUI48(args[++i]), BDAddressType.BDADDR_LE_PUBLIC); } else if( arg.equals("-mode") ) { mode = Integer.valueOf(args[++i]).intValue(); } else if( arg.equals("-bluetoothManager") && args.length > (i+1) ) { @@ -155,7 +157,7 @@ public class ScannerTinyB00 { final List<BluetoothDevice> devices = useAdapter ? adapter.getDevices() : manager.getDevices(); for(final Iterator<BluetoothDevice> id = devices.iterator(); id.hasNext() && !timeout; ) { final BluetoothDevice d = id.next(); - if(d.getAddress().equals(mac)) { + if(d.getAddressAndType().equals(mac)) { sensor = d; break; } @@ -222,7 +224,7 @@ public class ScannerTinyB00 { } while( forever ); } private static void printDevice(final BluetoothDevice device) { - System.err.println("Address = " + device.getAddress()); + System.err.println("Address = " + device.getAddressAndType()); System.err.println(" Name = " + device.getName()); System.err.println(" Connected = " + device.getConnected()); System.err.println(); diff --git a/examples/java/ScannerTinyB01.java b/examples/java/ScannerTinyB01.java index 57683900..c0fa198d 100644 --- a/examples/java/ScannerTinyB01.java +++ b/examples/java/ScannerTinyB01.java @@ -33,6 +33,8 @@ import org.tinyb.AdapterSettings; import org.tinyb.BluetoothAdapter; import org.tinyb.BluetoothDevice; import org.tinyb.AdapterStatusListener; +import org.tinyb.BDAddressAndType; +import org.tinyb.BDAddressType; import org.tinyb.BluetoothException; import org.tinyb.BluetoothFactory; import org.tinyb.BluetoothGattCharacteristic; @@ -65,7 +67,7 @@ public class ScannerTinyB01 { /** 20000 milliseconds */ static long TO_CONNECT_AND_RESOLVE = 20000; - static EUI48 waitForDevice = EUI48.ANY_DEVICE; + static BDAddressAndType waitForDevice = BDAddressAndType.ANY_DEVICE; static List<String> characteristicList = new ArrayList<String>(); public static void main(final String[] args) throws InterruptedException { @@ -83,7 +85,7 @@ public class ScannerTinyB01 { if( arg.equals("-dev_id") && args.length > (i+1) ) { dev_id = Integer.valueOf(args[++i]).intValue(); } else if( arg.equals("-mac") && args.length > (i+1) ) { - waitForDevice = new EUI48(args[++i]); + waitForDevice = new BDAddressAndType(new EUI48(args[++i]), BDAddressType.BDADDR_LE_PUBLIC); } else if( arg.equals("-char") && args.length > (i+1) ) { characteristicList.add(args[++i]); } else if( arg.equals("-mode") && args.length > (i+1) ) { @@ -176,7 +178,7 @@ public class ScannerTinyB01 { @Override public void deviceFound(final BluetoothDevice device, final long timestamp) { - final boolean matches = EUI48.ANY_DEVICE.equals(waitForDevice) || device.getAddress().equals(waitForDevice); + final boolean matches = BDAddressAndType.ANY_DEVICE.matches(waitForDevice) || device.getAddressAndType().matches(waitForDevice); System.err.println("****** FOUND__: "+device.toString()+" - match "+matches); System.err.println("Status Adapter:"); System.err.println(device.getAdapter().toString()); @@ -191,13 +193,13 @@ public class ScannerTinyB01 { @Override public void deviceUpdated(final BluetoothDevice device, final EIRDataTypeSet updateMask, final long timestamp) { - final boolean matches = EUI48.ANY_DEVICE.equals(waitForDevice) || device.getAddress().equals(waitForDevice); + final boolean matches = BDAddressAndType.ANY_DEVICE.matches(waitForDevice) || device.getAddressAndType().equals(waitForDevice); System.err.println("****** UPDATED: "+updateMask+" of "+device+" - match "+matches); } @Override public void deviceConnected(final BluetoothDevice device, final short handle, final long timestamp) { - final boolean matches = EUI48.ANY_DEVICE.equals(waitForDevice) || device.getAddress().equals(waitForDevice); + final boolean matches = BDAddressAndType.ANY_DEVICE.matches(waitForDevice) || device.getAddressAndType().equals(waitForDevice); System.err.println("****** CONNECTED: "+device+" - matches "+matches); } @@ -261,7 +263,7 @@ public class ScannerTinyB01 { final List<BluetoothDevice> devices = adapter.getDevices(); for(final Iterator<BluetoothDevice> id = devices.iterator(); id.hasNext() && !timeout; ) { final BluetoothDevice d = id.next(); - if( EUI48.ANY_DEVICE.equals(waitForDevice) || d.getAddress().equals(waitForDevice) ) { + if( BDAddressAndType.ANY_DEVICE.matches(waitForDevice) || d.getAddressAndType().equals(waitForDevice) ) { sensor = d; break; } @@ -408,7 +410,7 @@ public class ScannerTinyB01 { System.err.println("ScannerTinyB01 XX"); } private static void printDevice(final BluetoothDevice device) { - System.err.println("Address = " + device.getAddress()); + System.err.println("Address = " + device.getAddressAndType()); System.err.println(" Name = " + device.getName()); System.err.println(" Connected = " + device.getConnected()); System.err.println(); diff --git a/examples/java/ScannerTinyB02.java b/examples/java/ScannerTinyB02.java index 9ad79cff..261467f9 100644 --- a/examples/java/ScannerTinyB02.java +++ b/examples/java/ScannerTinyB02.java @@ -31,6 +31,8 @@ import org.tinyb.AdapterSettings; import org.tinyb.BluetoothAdapter; import org.tinyb.BluetoothDevice; import org.tinyb.AdapterStatusListener; +import org.tinyb.BDAddressAndType; +import org.tinyb.BDAddressType; import org.tinyb.BluetoothException; import org.tinyb.BluetoothFactory; import org.tinyb.BluetoothManager; @@ -57,7 +59,7 @@ public class ScannerTinyB02 { /** 300 milliseconds */ static long TO_CONNECT = 300; - static EUI48 waitForDevice = EUI48.ANY_DEVICE; + static BDAddressAndType waitForDevice = BDAddressAndType.ANY_DEVICE; public static void main(final String[] args) throws InterruptedException { final boolean waitForEnter=false; @@ -74,7 +76,7 @@ public class ScannerTinyB02 { if( arg.equals("-dev_id") && args.length > (i+1) ) { dev_id = Integer.valueOf(args[++i]).intValue(); } else if( arg.equals("-mac") && args.length > (i+1) ) { - waitForDevice = new EUI48( args[++i] ); + waitForDevice = new BDAddressAndType(new EUI48(args[++i]), BDAddressType.BDADDR_LE_PUBLIC); } else if( arg.equals("-mode") && args.length > (i+1) ) { mode = Integer.valueOf(args[++i]).intValue(); } else if( arg.equals("-factory") && args.length > (i+1) ) { @@ -152,7 +154,7 @@ public class ScannerTinyB02 { @Override public void deviceFound(final BluetoothDevice device, final long timestamp) { - final boolean matches = EUI48.ANY_DEVICE.equals(waitForDevice) || device.getAddress().equals(waitForDevice); + final boolean matches = BDAddressAndType.ANY_DEVICE.matches(waitForDevice) || device.getAddressAndType().equals(waitForDevice); System.err.println("****** FOUND__: "+device.toString()+" - match "+matches); System.err.println("Status Adapter:"); System.err.println(device.getAdapter().toString()); @@ -167,13 +169,13 @@ public class ScannerTinyB02 { @Override public void deviceUpdated(final BluetoothDevice device, final EIRDataTypeSet updateMask, final long timestamp) { - final boolean matches = EUI48.ANY_DEVICE.equals(waitForDevice) || device.getAddress().equals(waitForDevice); + final boolean matches = BDAddressAndType .ANY_DEVICE.matches(waitForDevice) || device.getAddressAndType().equals(waitForDevice); System.err.println("****** UPDATED: "+updateMask+" of "+device+" - match "+matches); } @Override public void deviceConnected(final BluetoothDevice device, final short handle, final long timestamp) { - final boolean matches = EUI48.ANY_DEVICE.equals(waitForDevice) || device.getAddress().equals(waitForDevice); + final boolean matches = BDAddressAndType .ANY_DEVICE.matches(waitForDevice) || device.getAddressAndType().equals(waitForDevice); System.err.println("****** CONNECTED: "+device+" - matches "+matches); } @@ -240,7 +242,7 @@ public class ScannerTinyB02 { int i=0; for(final Iterator<BluetoothDevice> id = devices.iterator(); id.hasNext() && !timeout; ) { final BluetoothDevice d = id.next(); - final boolean match = EUI48.ANY_DEVICE.equals(waitForDevice) || d.getAddress().equals(waitForDevice); + final boolean match = BDAddressAndType .ANY_DEVICE.matches(waitForDevice) || d.getAddressAndType().equals(waitForDevice); System.err.println("****** Has "+i+"/"+devices.size()+": match "+match+": "+d.toString()); i++; if( match ) { @@ -346,7 +348,7 @@ public class ScannerTinyB02 { System.err.println("ScannerTinyB01 XX"); } private static void printDevice(final BluetoothDevice device) { - System.err.println("Address = " + device.getAddress()); + System.err.println("Address = " + device.getAddressAndType()); System.err.println(" Name = " + device.getName()); System.err.println(" Connected = " + device.getConnected()); System.err.println(); diff --git a/java/direct_bt/tinyb/DBTAdapter.java b/java/direct_bt/tinyb/DBTAdapter.java index efe3216a..b8ae955d 100644 --- a/java/direct_bt/tinyb/DBTAdapter.java +++ b/java/direct_bt/tinyb/DBTAdapter.java @@ -36,7 +36,6 @@ import java.util.concurrent.atomic.AtomicReference; import org.tinyb.AdapterSettings; import org.tinyb.BluetoothAdapter; -import org.tinyb.BluetoothAddressType; import org.tinyb.BluetoothDevice; import org.tinyb.BluetoothException; import org.tinyb.BluetoothGattCharacteristic; @@ -54,6 +53,7 @@ import org.tinyb.PairingMode; import org.tinyb.SMPPairingState; import org.tinyb.ScanType; import org.tinyb.AdapterStatusListener; +import org.tinyb.BDAddressAndType; import org.tinyb.TransportType; public class DBTAdapter extends DBTObject implements BluetoothAdapter @@ -169,25 +169,25 @@ public class DBTAdapter extends DBTObject implements BluetoothAdapter static BluetoothType class_type() { return BluetoothType.ADAPTER; } @Override - public BluetoothDevice find(final String name, final EUI48 address, final long timeoutMS) { - return findDeviceInCache(name, address); + public BluetoothDevice find(final String name, final BDAddressAndType addressAndType, final long timeoutMS) { + return findDeviceInCache(name, addressAndType); } @Override - public BluetoothDevice find(final String name, final EUI48 address) { - return find(name, address, 0); + public BluetoothDevice find(final String name, final BDAddressAndType addressAndType) { + return find(name, addressAndType, 0); } @Override - public final boolean isDeviceWhitelisted(final EUI48 address) { return isDeviceWhitelistedImpl(address.b); } - private final native boolean isDeviceWhitelistedImpl(final byte[] address); + public final boolean isDeviceWhitelisted(final BDAddressAndType addressAndType) { return isDeviceWhitelistedImpl(addressAndType.address.b, addressAndType.type.value); } + private final native boolean isDeviceWhitelistedImpl(final byte[] address, byte address_type); @Override - public boolean addDeviceToWhitelist(final EUI48 address, final BluetoothAddressType address_type, + public boolean addDeviceToWhitelist(final BDAddressAndType addressAndType, final HCIWhitelistConnectType ctype, final short conn_interval_min, final short conn_interval_max, final short conn_latency, final short timeout) { - return addDeviceToWhitelistImpl1(address.b, address_type.value, ctype.value, + return addDeviceToWhitelistImpl1(addressAndType.address.b, addressAndType.type.value, ctype.value, conn_interval_min, conn_interval_max, conn_latency, timeout); } private native boolean addDeviceToWhitelistImpl1(final byte[] address, final byte address_type, final int ctype, @@ -195,15 +195,15 @@ public class DBTAdapter extends DBTObject implements BluetoothAdapter final short conn_latency, final short timeout); @Override - public boolean addDeviceToWhitelist(final EUI48 address, final BluetoothAddressType address_type, + public boolean addDeviceToWhitelist(final BDAddressAndType addressAndType, final HCIWhitelistConnectType ctype) { - return addDeviceToWhitelistImpl2(address.b, address_type.value, ctype.value); + return addDeviceToWhitelistImpl2(addressAndType.address.b, addressAndType.type.value, ctype.value); } private native boolean addDeviceToWhitelistImpl2(final byte[] address, final byte address_type, final int ctype); @Override - public boolean removeDeviceFromWhitelist(final EUI48 address, final BluetoothAddressType address_type) { - return removeDeviceFromWhitelistImpl(address.b, address_type.value); + public boolean removeDeviceFromWhitelist(final BDAddressAndType addressAndType) { + return removeDeviceFromWhitelistImpl(addressAndType.address.b, addressAndType.type.value); } private native boolean removeDeviceFromWhitelistImpl(final byte[] address, final byte address_type); @@ -344,8 +344,8 @@ public class DBTAdapter extends DBTObject implements BluetoothAdapter public native boolean setDiscoverable(boolean value); @Override - public final BluetoothDevice connectDevice(final EUI48 address, final BluetoothAddressType addressType) { - return connectDeviceImpl(address.b, addressType.value); + public final BluetoothDevice connectDevice(final BDAddressAndType addressAndType) { + return connectDeviceImpl(addressAndType.address.b, addressAndType.type.value); } private native BluetoothDevice connectDeviceImpl(byte[] address, byte addressType); @@ -668,9 +668,9 @@ public class DBTAdapter extends DBTObject implements BluetoothAdapter } } - /* pp */ DBTDevice findDeviceInCache(final String name, final EUI48 address) { + /* pp */ DBTDevice findDeviceInCache(final String name, final BDAddressAndType addressAndType) { synchronized(discoveredDevicesLock) { - if( null == name && null == address ) { + if( null == name && null == addressAndType ) { // special case for 1st valid device if( discoveredDevices.size() > 0 ) { return (DBTDevice) discoveredDevices.get(0); @@ -679,15 +679,15 @@ public class DBTAdapter extends DBTObject implements BluetoothAdapter } for(int devIdx = discoveredDevices.size() - 1; devIdx >= 0; devIdx-- ) { final DBTDevice device = (DBTDevice) discoveredDevices.get(devIdx); - if( null != name && null != address && + if( null != name && null != addressAndType && device.getName().equals(name) && - device.getAddress().equals(address) + device.getAddressAndType().equals(addressAndType) ) { return device; } - if( null != address && - device.getAddress().equals(address) + if( null != addressAndType && + device.getAddressAndType().equals(addressAndType) ) { return device; diff --git a/java/direct_bt/tinyb/DBTDevice.java b/java/direct_bt/tinyb/DBTDevice.java index 3a07b144..a3f87ac8 100644 --- a/java/direct_bt/tinyb/DBTDevice.java +++ b/java/direct_bt/tinyb/DBTDevice.java @@ -32,9 +32,9 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import org.tinyb.AdapterStatusListener; -import org.tinyb.BLERandomAddressType; +import org.tinyb.BDAddressAndType; import org.tinyb.BTSecurityLevel; -import org.tinyb.BluetoothAddressType; +import org.tinyb.BDAddressType; import org.tinyb.BluetoothDevice; import org.tinyb.BluetoothException; import org.tinyb.BluetoothGattCharacteristic; @@ -61,9 +61,7 @@ public class DBTDevice extends DBTObject implements BluetoothDevice /** Device's adapter weak back-reference */ private final WeakReference<DBTAdapter> wbr_adapter; - private final EUI48 address; - private final BluetoothAddressType addressType; - private final BLERandomAddressType leRandomAddressType; + private final BDAddressAndType addressAndType; private final long ts_creation; private volatile String name; volatile long ts_last_discovery; @@ -213,14 +211,12 @@ public class DBTDevice extends DBTObject implements BluetoothDevice final byte byteAddressType, final String name, final long ts_creation) { - super(nativeInstance, java.util.Arrays.hashCode(byteAddress)); + super(nativeInstance, compHash(java.util.Arrays.hashCode(byteAddress), 31+byteAddressType)); this.wbr_adapter = new WeakReference<DBTAdapter>(adptr); - this.address = new EUI48(byteAddress); - this.addressType = BluetoothAddressType.get(byteAddressType); - if( BluetoothAddressType.BDADDR_UNDEFINED == addressType ) { + this.addressAndType = new BDAddressAndType(new EUI48(byteAddress), BDAddressType.get(byteAddressType)); + if( BDAddressType.BDADDR_UNDEFINED == addressAndType.type ) { throw new IllegalArgumentException("Unsupported given native addresstype "+byteAddressType); } - this.leRandomAddressType = address.getBLERandomAddressType(addressType); this.ts_creation = ts_creation; this.name = name; ts_last_discovery = ts_creation; @@ -275,7 +271,7 @@ public class DBTDevice extends DBTObject implements BluetoothDevice return false; } final DBTDevice other = (DBTDevice)obj; - return address.equals(other.address) && addressType.equals(other.addressType); + return addressAndType.equals(other.addressAndType); } @Override @@ -291,16 +287,10 @@ public class DBTDevice extends DBTObject implements BluetoothDevice public DBTAdapter getAdapter() { return wbr_adapter.get(); } @Override - public EUI48 getAddress() { return address; } + public String getAddressString() { return addressAndType.address.toString(); } @Override - public String getAddressString() { return address.toString(); } - - @Override - public BluetoothAddressType getAddressType() { return addressType; } - - @Override - public BLERandomAddressType getBLERandomAddressType() { return leRandomAddressType; } + public BDAddressAndType getAddressAndType() { return addressAndType; } @Override public String getName() { return name; } @@ -650,13 +640,7 @@ public class DBTDevice extends DBTObject implements BluetoothDevice public final String toString() { if( !isValid() ) { // UTF-8 271D = Cross - final String leRandomStr; - if( BLERandomAddressType.UNDEFINED != this.leRandomAddressType ) { - leRandomStr = ", random "+leRandomAddressType.toString(); - } else { - leRandomStr = ""; - } - return "Device" + "\u271D" + "[address["+address+", "+addressType.toString()+leRandomStr+"], '"+name+ + return "Device" + "\u271D" + "[address"+addressAndType+", '"+name+ "', connected["+isConnected.get()+", 0x"+Integer.toHexString(hciConnHandle)+"]]"; } return toStringImpl(); diff --git a/java/jni/direct_bt/DBTAdapter.cxx b/java/jni/direct_bt/DBTAdapter.cxx index 1fb853eb..4e362910 100644 --- a/java/jni/direct_bt/DBTAdapter.cxx +++ b/java/jni/direct_bt/DBTAdapter.cxx @@ -115,7 +115,7 @@ class JNIAdapterStatusListener : public AdapterStatusListener { public: std::string toString() const override { - const std::string devMatchAddr = nullptr != deviceMatchRef ? deviceMatchRef->getAddress().toString() : "nil"; + const std::string devMatchAddr = nullptr != deviceMatchRef ? deviceMatchRef->getAddressAndType().toString() : "nil"; return "JNIAdapterStatusListener[this "+jau::aptrHexString(this)+", iname "+std::to_string(iname)+", devMatchAddr "+devMatchAddr+"]"; } @@ -358,7 +358,7 @@ class JNIAdapterStatusListener : public AdapterStatusListener { } else { // New Java instance // Device(final long nativeInstance, final Adapter adptr, final String address, final int intAddressType, final String name) - const EUI48 addr = device->getAddress(); + const EUI48 addr = device->getAddressAndType().address; jbyteArray jaddr = env->NewByteArray(sizeof(addr)); env->SetByteArrayRegion(jaddr, 0, sizeof(addr), (const jbyte*)(addr.b)); jau::java_exception_check_and_throw(env, E_FILE_LINE); @@ -366,7 +366,7 @@ class JNIAdapterStatusListener : public AdapterStatusListener { jau::java_exception_check_and_throw(env, E_FILE_LINE); jobject tmp_jdevice = env->NewObject(deviceClazzRef.getClass(), deviceClazzCtor, (jlong)device.get(), jau::JavaGlobalObj::GetObject(adapterObjRef), - jaddr, device->getAddressType(), name, (jlong)timestamp); + jaddr, device->getAddressAndType().type, name, (jlong)timestamp); jau::java_exception_check_and_throw(env, E_FILE_LINE); JNIGlobalRef::check(tmp_jdevice, E_FILE_LINE); std::shared_ptr<jau::JavaAnon> jDeviceRef1 = device->getJavaObject(); @@ -411,7 +411,7 @@ class JNIAdapterStatusListener : public AdapterStatusListener { } else { // New Java instance // Device(final long nativeInstance, final Adapter adptr, final String address, final int intAddressType, final String name) - const EUI48 addr = device->getAddress(); + const EUI48 addr = device->getAddressAndType().address; jbyteArray jaddr = env->NewByteArray(sizeof(addr)); env->SetByteArrayRegion(jaddr, 0, sizeof(addr), (const jbyte*)(addr.b)); jau::java_exception_check_and_throw(env, E_FILE_LINE); @@ -419,7 +419,7 @@ class JNIAdapterStatusListener : public AdapterStatusListener { jau::java_exception_check_and_throw(env, E_FILE_LINE); jobject tmp_jdevice = env->NewObject(deviceClazzRef.getClass(), deviceClazzCtor, (jlong)device.get(), jau::JavaGlobalObj::GetObject(adapterObjRef), - jaddr, device->getAddressType(), name, (jlong)timestamp); + jaddr, device->getAddressAndType().type, name, (jlong)timestamp); jau::java_exception_check_and_throw(env, E_FILE_LINE); JNIGlobalRef::check(tmp_jdevice, E_FILE_LINE); std::shared_ptr<jau::JavaAnon> jDeviceRef1 = device->getJavaObject(); @@ -598,7 +598,7 @@ jint Java_direct_1bt_tinyb_DBTAdapter_removeAllStatusListener(JNIEnv *env, jobje return 0; } -jboolean Java_direct_1bt_tinyb_DBTAdapter_isDeviceWhitelisted(JNIEnv *env, jobject obj, jbyteArray jaddress) { +jboolean Java_direct_1bt_tinyb_DBTAdapter_isDeviceWhitelisted(JNIEnv *env, jobject obj, jbyteArray jaddress, jbyte jaddressType) { try { DBTAdapter *adapter = jau::getJavaUplinkObject<DBTAdapter>(env, obj); jau::JavaGlobalObj::check(adapter->getJavaObject(), E_FILE_LINE); @@ -616,8 +616,9 @@ jboolean Java_direct_1bt_tinyb_DBTAdapter_isDeviceWhitelisted(JNIEnv *env, jobje throw jau::InternalError("GetPrimitiveArrayCritical(address byte array) is null", E_FILE_LINE); } const EUI48& address = *reinterpret_cast<EUI48 *>(address_ptr); + const BDAddressAndType addressAndType(address, static_cast<BDAddressType>( jaddressType )); - return adapter->isDeviceWhitelisted(address); + return adapter->isDeviceWhitelisted(addressAndType); } catch(...) { rethrow_and_raise_java_exception(env); } @@ -645,9 +646,9 @@ jboolean Java_direct_1bt_tinyb_DBTAdapter_addDeviceToWhitelistImpl1(JNIEnv *env, } const EUI48& address = *reinterpret_cast<EUI48 *>(address_ptr); - const BDAddressType addressType = static_cast<BDAddressType>( jaddressType ); + const BDAddressAndType addressAndType(address, static_cast<BDAddressType>( jaddressType )); const HCIWhitelistConnectType ctype = static_cast<HCIWhitelistConnectType>( jctype ); - return adapter->addDeviceToWhitelist(address, addressType, ctype, (uint16_t)min_interval, (uint16_t)max_interval, (uint16_t)latency, (uint16_t)timeout); + return adapter->addDeviceToWhitelist(addressAndType, ctype, (uint16_t)min_interval, (uint16_t)max_interval, (uint16_t)latency, (uint16_t)timeout); } catch(...) { rethrow_and_raise_java_exception(env); } @@ -673,9 +674,9 @@ jboolean Java_direct_1bt_tinyb_DBTAdapter_addDeviceToWhitelistImpl2(JNIEnv *env, } const EUI48& address = *reinterpret_cast<EUI48 *>(address_ptr); - const BDAddressType addressType = static_cast<BDAddressType>( jaddressType ); + const BDAddressAndType addressAndType(address, static_cast<BDAddressType>( jaddressType )); const HCIWhitelistConnectType ctype = static_cast<HCIWhitelistConnectType>( jctype ); - return adapter->addDeviceToWhitelist(address, addressType, ctype); + return adapter->addDeviceToWhitelist(addressAndType, ctype); } catch(...) { rethrow_and_raise_java_exception(env); } @@ -700,8 +701,8 @@ jboolean Java_direct_1bt_tinyb_DBTAdapter_removeDeviceFromWhitelistImpl(JNIEnv * } const EUI48& address = *reinterpret_cast<EUI48 *>(address_ptr); - const BDAddressType addressType = static_cast<BDAddressType>( jaddressType ); - return adapter->removeDeviceFromWhitelist(address, addressType); + const BDAddressAndType addressAndType(address, static_cast<BDAddressType>( jaddressType )); + return adapter->removeDeviceFromWhitelist(addressAndType); } catch(...) { rethrow_and_raise_java_exception(env); } diff --git a/java/jni/direct_bt/DBTDevice.cxx b/java/jni/direct_bt/DBTDevice.cxx index ea821818..e447edec 100644 --- a/java/jni/direct_bt/DBTDevice.cxx +++ b/java/jni/direct_bt/DBTDevice.cxx @@ -794,7 +794,7 @@ jshort Java_direct_1bt_tinyb_DBTDevice_getTxPower(JNIEnv *env, jobject obj) // struct BooleanDeviceCBContext { - EUI48 deviceAddress; + BDAddressAndType addressAndType; JNIGlobalRef javaCallback_ref; jmethodID mRun; JNIGlobalRef boolean_cls_ref; @@ -805,7 +805,7 @@ struct BooleanDeviceCBContext { if( &rhs == this ) { return true; } - return rhs.deviceAddress == deviceAddress && + return rhs.addressAndType == addressAndType && rhs.javaCallback_ref == javaCallback_ref; } @@ -864,13 +864,13 @@ void Java_direct_1bt_tinyb_DBTDevice_enableBlockedNotificationsImpl(JNIEnv *env, bool isBlocked = false; if( MgmtEvent::Opcode::DEVICE_BLOCKED == e->getOpcode() ) { const MgmtEvtDeviceBlocked &event = *static_cast<const MgmtEvtDeviceBlocked *>(e.get()); - if( event.getAddress() != ctx_ref->deviceAddress ) { + if( event.getAddress() != ctx_ref->addressAndType.address || event.getAddressType() != ctx_ref->addressAndType.type ) { return false; // not this device } isBlocked = true; } else if( MgmtEvent::Opcode::DEVICE_UNBLOCKED == e->getOpcode() ) { const MgmtEvtDeviceUnblocked &event = *static_cast<const MgmtEvtDeviceUnblocked *>(e.get()); - if( event.getAddress() != ctx_ref->deviceAddress ) { + if( event.getAddress() != ctx_ref->addressAndType.address || event.getAddressType() != ctx_ref->addressAndType.type ) { return false; // not this device } isBlocked = false; @@ -893,7 +893,7 @@ void Java_direct_1bt_tinyb_DBTDevice_enableBlockedNotificationsImpl(JNIEnv *env, java_exception_check_and_throw(env, E_FILE_LINE); BooleanDeviceCBContext * ctx = new BooleanDeviceCBContext{ - device->getAddress(), JNIGlobalRef(javaCallback), mRun, JNIGlobalRef(boolean_cls), boolean_ctor }; + device->getAddressAndType(), JNIGlobalRef(javaCallback), mRun, JNIGlobalRef(boolean_cls), boolean_ctor }; jni_env->DeleteLocalRef(boolean_cls); // move BooleanDeviceCBContextRef into CaptureInvocationFunc and operator== includes javaCallback comparison @@ -949,7 +949,7 @@ void Java_direct_1bt_tinyb_DBTDevice_enablePairedNotificationsImpl(JNIEnv *env, bool(*nativeCallback)(BooleanDeviceCBContextRef&, std::shared_ptr<MgmtEvent>) = [](BooleanDeviceCBContextRef& ctx_ref, std::shared_ptr<MgmtEvent> e)->bool { const MgmtEvtDeviceUnpaired &event = *static_cast<const MgmtEvtDeviceUnpaired *>(e.get()); - if( event.getAddress() != ctx_ref->deviceAddress ) { + if( event.getAddress() != ctx_ref->addressAndType.address || event.getAddressType() != ctx_ref->addressAndType.type ) { return false; // not this device } jobject result = jni_env->NewObject(ctx_ref->boolean_cls_ref.getClass(), ctx_ref->boolean_ctor, JNI_FALSE); @@ -967,7 +967,7 @@ void Java_direct_1bt_tinyb_DBTDevice_enablePairedNotificationsImpl(JNIEnv *env, java_exception_check_and_throw(env, E_FILE_LINE); BooleanDeviceCBContext * ctx = new BooleanDeviceCBContext{ - device->getAddress(), JNIGlobalRef(javaCallback), mRun, JNIGlobalRef(boolean_cls), boolean_ctor }; + device->getAddressAndType(), JNIGlobalRef(javaCallback), mRun, JNIGlobalRef(boolean_cls), boolean_ctor }; jni_env->DeleteLocalRef(boolean_cls); // move BooleanDeviceCBContextRef into CaptureInvocationFunc and operator== includes javaCallback comparison diff --git a/java/org/tinyb/BLERandomAddressType.java b/java/org/tinyb/BLERandomAddressType.java index eedcd302..808789aa 100644 --- a/java/org/tinyb/BLERandomAddressType.java +++ b/java/org/tinyb/BLERandomAddressType.java @@ -38,11 +38,11 @@ package org.tinyb; * Table 1.2, address bits [47:46] * </p> * <p> - * If {@link BluetoothAddressType} is {@link BluetoothAddressType#BDADDR_LE_RANDOM}, + * If {@link BDAddressType} is {@link BDAddressType#BDADDR_LE_RANDOM}, * its value shall be different than {@link BLERandomAddressType#UNDEFINED}. * </p> * <p> - * If {@link BluetoothAddressType} is not {@link BluetoothAddressType#BDADDR_LE_RANDOM}, + * If {@link BDAddressType} is not {@link BDAddressType#BDADDR_LE_RANDOM}, * its value shall be {@link BLERandomAddressType#UNDEFINED}. * </p> * @since 2.0.0 diff --git a/java/org/tinyb/BluetoothAdapter.java b/java/org/tinyb/BluetoothAdapter.java index 502f4f94..b8a8d26c 100644 --- a/java/org/tinyb/BluetoothAdapter.java +++ b/java/org/tinyb/BluetoothAdapter.java @@ -58,7 +58,7 @@ public interface BluetoothAdapter extends BluetoothObject * @return An object matching the name and address or null if not found before * timeout expires. */ - public BluetoothDevice find(String name, EUI48 address, long timeoutMS); + public BluetoothDevice find(String name, BDAddressAndType addressAndType, long timeoutMS); /** Find a BluetoothDevice. If parameters name and address are not null, * the returned object will have to match them. @@ -70,7 +70,7 @@ public interface BluetoothAdapter extends BluetoothObject * waiting for * @return An object matching the name and address. */ - public BluetoothDevice find(String name, EUI48 address); + public BluetoothDevice find(String name, BDAddressAndType addressAndType); /* Bluetooth specific API */ @@ -79,13 +79,13 @@ public interface BluetoothAdapter extends BluetoothObject * @since 2.0.0 * @implNote not implemented in tinyb.dbus */ - public boolean isDeviceWhitelisted(final EUI48 address); + public boolean isDeviceWhitelisted(final BDAddressAndType addressAndType); /** * Add the given device to the adapter's autoconnect whitelist. * <p> * The given LE connection parameter will be uploaded to the kernel for the given device first, - * if the device is of type {@link BluetoothAddressType#BDADDR_LE_PUBLIC} or {@link BluetoothAddressType#BDADDR_LE_RANDOM}. + * if the device is of type {@link BDAddressType#BDADDR_LE_PUBLIC} or {@link BDAddressType#BDADDR_LE_RANDOM}. * </p> * <p> * Method will reject duplicate devices, in which case it should be removed first. @@ -100,11 +100,11 @@ public interface BluetoothAdapter extends BluetoothObject * @param timeout in units of 10ms, default value 1000 for 10000ms or 10s. * @return {@code true} if successful, otherwise {@code false}. * - * @see #addDeviceToWhitelist(String, BluetoothAddressType, HCIWhitelistConnectType) + * @see #addDeviceToWhitelist(String, BDAddressType, HCIWhitelistConnectType) * @since 2.0.0 * @implNote not implemented in tinyb.dbus */ - public boolean addDeviceToWhitelist(final EUI48 address, final BluetoothAddressType address_type, + public boolean addDeviceToWhitelist(final BDAddressAndType addressAndType, final HCIWhitelistConnectType ctype, final short conn_interval_min, final short conn_interval_max, final short conn_latency, final short timeout); @@ -112,7 +112,7 @@ public interface BluetoothAdapter extends BluetoothObject /** * Add the given device to the adapter's autoconnect whitelist. * <p> - * This variant of {@link #addDeviceToWhitelist(String, BluetoothAddressType, HCIWhitelistConnectType, short, short, short, short)} + * This variant of {@link #addDeviceToWhitelist(String, BDAddressType, HCIWhitelistConnectType, short, short, short, short)} * uses default connection parameter, which will be uploaded to the kernel for the given device first. * </p> * <p> @@ -124,11 +124,11 @@ public interface BluetoothAdapter extends BluetoothObject * @param ctype * @return {@code true} if successful, otherwise {@code false}. * - * @see #addDeviceToWhitelist(String, BluetoothAddressType, HCIWhitelistConnectType, short, short, short, short) + * @see #addDeviceToWhitelist(String, BDAddressType, HCIWhitelistConnectType, short, short, short, short) * @since 2.0.0 * @implNote not implemented in tinyb.dbus */ - public boolean addDeviceToWhitelist(final EUI48 address, final BluetoothAddressType address_type, + public boolean addDeviceToWhitelist(final BDAddressAndType addressAndType, final HCIWhitelistConnectType ctype); @@ -137,7 +137,7 @@ public interface BluetoothAdapter extends BluetoothObject * @since 2.0.0 * @implNote not implemented in tinyb.dbus */ - public boolean removeDeviceFromWhitelist(final EUI48 address, final BluetoothAddressType address_type); + public boolean removeDeviceFromWhitelist(final BDAddressAndType addressAndType); /** Turns on device discovery if it is disabled. @@ -211,7 +211,9 @@ public interface BluetoothAdapter extends BluetoothObject * Returns the hardware address of this adapter in its string representation. * @return The hardware address of this adapter as a string. * @since 2.2.0 + * @deprecated Use {@link #getAddress()} */ + @Deprecated String getAddressString(); /** Returns the system name of this adapter. @@ -385,7 +387,7 @@ public interface BluetoothAdapter extends BluetoothObject * <li>{@code random} - Random address</li> * </ul> */ - public BluetoothDevice connectDevice(EUI48 address, BluetoothAddressType addressType); + public BluetoothDevice connectDevice(BDAddressAndType addressAndType); /** Returns the pairable state the adapter. * @return The pairable state of the adapter. diff --git a/java/org/tinyb/BluetoothDevice.java b/java/org/tinyb/BluetoothDevice.java index b1bcdc8d..710d9c16 100644 --- a/java/org/tinyb/BluetoothDevice.java +++ b/java/org/tinyb/BluetoothDevice.java @@ -567,44 +567,21 @@ public interface BluetoothDevice extends BluetoothObject long getLastUpdateTimestamp(); /** - * Returns the hardware address of this device. - * @return The hardware address of this device. - * @implNote Changed to EUI48 since version 2.2.0 + * Returns the unique device {@link EUI48} address and {@link BDAddressType} type. * @since 2.2.0 + * @implNote not fully implemented in <b>tinyb.dbus</b>, uses {@link BDAddressType#BDADDR_LE_PUBLIC} */ - EUI48 getAddress(); + BDAddressAndType getAddressAndType(); /** * Returns the hardware address of this device in its string representation. * @return The hardware address of this device as a string. * @since 2.2.0 + * @deprecated Use {@link #getAddressAndType()} */ + @Deprecated String getAddressString(); - /** - * Returns the {@link BluetoothAddressType}, - * determining whether the device is {@link BluetoothAddressType#BDADDR_BREDR} - * or an LE device, {@link BluetoothAddressType#BDADDR_LE_PUBLIC} or {@link BluetoothAddressType#BDADDR_LE_RANDOM}. - * @since 2.0.0 - * @implNote not implemented in <b>tinyb.dbus</b>, returns {@link BluetoothAddressType#BDADDR_LE_PUBLIC} - */ - BluetoothAddressType getAddressType(); - - /** - * Returns the {@link BLERandomAddressType}. - * <p> - * If {@link #getAddressType()} is {@link BluetoothAddressType#BDADDR_LE_RANDOM}, - * method shall return a valid value other than {@link BLERandomAddressType#UNDEFINED}. - * </p> - * <p> - * If {@link #getAddressType()} is not {@link BluetoothAddressType#BDADDR_LE_RANDOM}, - * method shall return {@link BLERandomAddressType#UNDEFINED}. - * </p> - * @since 2.0.0 - * @implNote not implemented in <b>tinyb.dbus</b>, returns {@link BLERandomAddressType#UNDEFINED} - */ - BLERandomAddressType getBLERandomAddressType(); - /** Returns the remote friendly name of this device. * @return The remote friendly name of this device, or NULL if not set. */ diff --git a/java/org/tinyb/ScanType.java b/java/org/tinyb/ScanType.java index c240dfad..9b9502fe 100644 --- a/java/org/tinyb/ScanType.java +++ b/java/org/tinyb/ScanType.java @@ -26,7 +26,7 @@ package org.tinyb; /** * Meta ScanType as derived from {@link BTMode} - * with defined value mask consisting of {@link BluetoothAddressType} bits. + * with defined value mask consisting of {@link BDAddressType} bits. * <p> * This ScanType is natively compatible with DBTManager's implementation * for start and stop discovery. diff --git a/java/tinyb/dbus/DBusAdapter.java b/java/tinyb/dbus/DBusAdapter.java index f540f84d..e5521373 100644 --- a/java/tinyb/dbus/DBusAdapter.java +++ b/java/tinyb/dbus/DBusAdapter.java @@ -34,9 +34,9 @@ import java.util.List; import java.util.UUID; import org.tinyb.BluetoothAdapter; -import org.tinyb.BluetoothAddressType; import org.tinyb.BluetoothDevice; import org.tinyb.AdapterStatusListener; +import org.tinyb.BDAddressAndType; import org.tinyb.BluetoothException; import org.tinyb.BluetoothManager; import org.tinyb.BluetoothNotification; @@ -58,14 +58,14 @@ public class DBusAdapter extends DBusObject implements BluetoothAdapter static BluetoothType class_type() { return BluetoothType.ADAPTER; } @Override - public BluetoothDevice find(final String name, final EUI48 address, final long timeoutMS) { + public BluetoothDevice find(final String name, final BDAddressAndType addressAndType, final long timeoutMS) { final BluetoothManager manager = DBusManager.getManager(); - return (BluetoothDevice) manager.find(BluetoothType.DEVICE, name, address.toString(), this, timeoutMS); + return (BluetoothDevice) manager.find(BluetoothType.DEVICE, name, addressAndType.address.toString(), this, timeoutMS); } @Override - public BluetoothDevice find(final String name, final EUI48 address) { - return find(name, address, 0); + public BluetoothDevice find(final String name, final BDAddressAndType addressAndType) { + return find(name, addressAndType, 0); } @Override @@ -78,12 +78,12 @@ public class DBusAdapter extends DBusObject implements BluetoothAdapter public final boolean isValid() { return super.isValid(); } @Override - public boolean isDeviceWhitelisted(final EUI48 address) { + public boolean isDeviceWhitelisted(final BDAddressAndType addressAndType) { return false; // FIXME } @Override - public boolean addDeviceToWhitelist(final EUI48 address, final BluetoothAddressType address_type, + public boolean addDeviceToWhitelist(final BDAddressAndType addressAndType, final HCIWhitelistConnectType ctype, final short min_interval, final short max_interval, final short latency, final short timeout) { @@ -91,13 +91,13 @@ public class DBusAdapter extends DBusObject implements BluetoothAdapter } @Override - public boolean addDeviceToWhitelist(final EUI48 address, final BluetoothAddressType address_type, + public boolean addDeviceToWhitelist(final BDAddressAndType addressAndType, final HCIWhitelistConnectType ctype) { return false; // FIXME } @Override - public boolean removeDeviceFromWhitelist(final EUI48 address, final BluetoothAddressType address_type) { + public boolean removeDeviceFromWhitelist(final BDAddressAndType addressAndType) { return false; // FIXME } @@ -184,8 +184,8 @@ public class DBusAdapter extends DBusObject implements BluetoothAdapter public native boolean setDiscoverableTimout(long value); @Override - public BluetoothDevice connectDevice(final EUI48 address, final BluetoothAddressType addressType) { - return connectDeviceImpl(address.toString(), addressType.toDbusString()); + public BluetoothDevice connectDevice(final BDAddressAndType addressAndType) { + return connectDeviceImpl(addressAndType.address.toString(), addressAndType.type.toDbusString()); } private native BluetoothDevice connectDeviceImpl(String address, String addressType); diff --git a/java/tinyb/dbus/DBusDevice.java b/java/tinyb/dbus/DBusDevice.java index b066e0e8..34cf5647 100644 --- a/java/tinyb/dbus/DBusDevice.java +++ b/java/tinyb/dbus/DBusDevice.java @@ -33,7 +33,8 @@ import java.util.Map; import org.tinyb.BLERandomAddressType; import org.tinyb.BTSecurityLevel; -import org.tinyb.BluetoothAddressType; +import org.tinyb.BDAddressAndType; +import org.tinyb.BDAddressType; import org.tinyb.BluetoothDevice; import org.tinyb.BluetoothException; import org.tinyb.BluetoothGattCharacteristic; @@ -173,18 +174,12 @@ public class DBusDevice extends DBusObject implements BluetoothDevice /* D-Bus property accessors: */ @Override - public EUI48 getAddress() { return new EUI48(getAddressString()); } + public BDAddressAndType getAddressAndType() { return new BDAddressAndType(new EUI48(getAddressString()), BDAddressType.BDADDR_LE_PUBLIC /* FIXME */); } @Override public native String getAddressString(); @Override - public BluetoothAddressType getAddressType() { return BluetoothAddressType.BDADDR_LE_PUBLIC; /* FIXME */} - - @Override - public BLERandomAddressType getBLERandomAddressType() { return BLERandomAddressType.UNDEFINED; /* FIXME */ } - - @Override public native String getName(); @Override @@ -330,6 +325,6 @@ public class DBusDevice extends DBusObject implements BluetoothDevice @Override public String toString() { - return "Device[address["+getAddress()+", "+getAddressType()+"], '"+getName()+"']"; + return "Device[address"+getAddressAndType()+", '"+getName()+"']"; } } diff --git a/src/direct_bt/BTTypes.cpp b/src/direct_bt/BTTypes.cpp index 894219b1..ac10e8ad 100644 --- a/src/direct_bt/BTTypes.cpp +++ b/src/direct_bt/BTTypes.cpp @@ -180,11 +180,23 @@ EUI48::EUI48(const uint8_t * _b) noexcept { memcpy(b, _b, sizeof(b)); } -const EUI48 direct_bt::EUI48_ANY_DEVICE; // default ctor is zero bytes! +const EUI48 direct_bt::EUI48::ANY_DEVICE; // default ctor is zero bytes! static uint8_t _EUI48_ALL_DEVICE[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; static uint8_t _EUI48_LOCAL_DEVICE[] = {0x00, 0x00, 0x00, 0xff, 0xff, 0xff}; -const EUI48 direct_bt::EUI48_ALL_DEVICE( _EUI48_ALL_DEVICE ); -const EUI48 direct_bt::EUI48_LOCAL_DEVICE( _EUI48_LOCAL_DEVICE ); +const EUI48 direct_bt::EUI48::ALL_DEVICE( _EUI48_ALL_DEVICE ); +const EUI48 direct_bt::EUI48::LOCAL_DEVICE( _EUI48_LOCAL_DEVICE ); + +const BDAddressAndType direct_bt::BDAddressAndType::ANY_BREDR_DEVICE(EUI48::ANY_DEVICE, BDAddressType::BDADDR_BREDR); +const BDAddressAndType direct_bt::BDAddressAndType::ANY_DEVICE(EUI48::ANY_DEVICE, BDAddressType::BDADDR_UNDEFINED); + +std::string BDAddressAndType::toString() const { + const BLERandomAddressType leRandomAddressType = getBLERandomAddressType(); + std::string leaddrtype; + if( BLERandomAddressType::UNDEFINED != leRandomAddressType ) { + leaddrtype = ", random "+getBLERandomAddressTypeString(leRandomAddressType); + } + return "["+address.toString()+", "+getBDAddressTypeString(type)+leaddrtype+"]"; +} // ************************************************* // ************************************************* diff --git a/src/direct_bt/DBTAdapter.cpp b/src/direct_bt/DBTAdapter.cpp index e607f892..85a71f51 100644 --- a/src/direct_bt/DBTAdapter.cpp +++ b/src/direct_bt/DBTAdapter.cpp @@ -50,22 +50,11 @@ extern "C" { using namespace direct_bt; -int DBTAdapter::findDeviceIdx(std::vector<std::shared_ptr<DBTDevice>> & devices, EUI48 const & mac, const BDAddressType macType) noexcept { +std::shared_ptr<DBTDevice> DBTAdapter::findDevice(std::vector<std::shared_ptr<DBTDevice>> & devices, const EUI48 & address, const BDAddressType addressType) noexcept { const size_t size = devices.size(); for (size_t i = 0; i < size; i++) { std::shared_ptr<DBTDevice> & e = devices[i]; - if ( nullptr != e && mac == e->getAddress() && macType == e->getAddressType() ) { - return i; - } - } - return -1; -} - -std::shared_ptr<DBTDevice> DBTAdapter::findDevice(std::vector<std::shared_ptr<DBTDevice>> & devices, EUI48 const & mac, const BDAddressType macType) noexcept { - const size_t size = devices.size(); - for (size_t i = 0; i < size; i++) { - std::shared_ptr<DBTDevice> & e = devices[i]; - if ( nullptr != e && mac == e->getAddress() && macType == e->getAddressType() ) { + if ( nullptr != e && address == e->getAddressAndType().address && addressType == e->getAddressAndType().type) { return e; } } @@ -120,12 +109,11 @@ int DBTAdapter::disconnectAllDevices(const HCIStatusCode reason) noexcept { return count; } -std::shared_ptr<DBTDevice> DBTAdapter::findConnectedDevice (EUI48 const & mac, const BDAddressType macType) noexcept { +std::shared_ptr<DBTDevice> DBTAdapter::findConnectedDevice (const EUI48 & address, const BDAddressType & addressType) noexcept { const std::lock_guard<std::mutex> lock(mtx_connectedDevices); // RAII-style acquire and relinquish via destructor - return findDevice(connectedDevices, mac, macType); + return findDevice(connectedDevices, address, addressType); } - // ************************************************* // ************************************************* // ************************************************* @@ -216,7 +204,7 @@ bool DBTAdapter::validateDevInfo() noexcept { return true; errout0: - adapterInfo = std::shared_ptr<AdapterInfo>( new AdapterInfo(dev_id, EUI48_ANY_DEVICE, 0, 0, + adapterInfo = std::shared_ptr<AdapterInfo>( new AdapterInfo(dev_id, EUI48::ANY_DEVICE, 0, 0, AdapterSetting::NONE, AdapterSetting::NONE, 0, "invalid", "invalid")); return false; } @@ -509,31 +497,31 @@ HCIStatusCode DBTAdapter::reset() noexcept { #endif } -bool DBTAdapter::isDeviceWhitelisted(const EUI48 &address) noexcept { - return mgmt.isDeviceWhitelisted(dev_id, address); +bool DBTAdapter::isDeviceWhitelisted(const BDAddressAndType & addressAndType) noexcept { + return mgmt.isDeviceWhitelisted(dev_id, addressAndType); } -bool DBTAdapter::addDeviceToWhitelist(const EUI48 &address, const BDAddressType address_type, const HCIWhitelistConnectType ctype, +bool DBTAdapter::addDeviceToWhitelist(const BDAddressAndType & addressAndType, const HCIWhitelistConnectType ctype, const uint16_t conn_interval_min, const uint16_t conn_interval_max, const uint16_t conn_latency, const uint16_t timeout) { if( !isPowered() ) { ERR_PRINT("DBTAdapter::startDiscovery: Adapter not powered: %s", toString().c_str()); return false; } - if( mgmt.isDeviceWhitelisted(dev_id, address) ) { - ERR_PRINT("DBTAdapter::addDeviceToWhitelist: device already listed: dev_id %d, address %s", dev_id, address.toString().c_str()); + if( mgmt.isDeviceWhitelisted(dev_id, addressAndType) ) { + ERR_PRINT("DBTAdapter::addDeviceToWhitelist: device already listed: dev_id %d, address%s", dev_id, addressAndType.toString().c_str()); return true; } - if( !mgmt.uploadConnParam(dev_id, address, address_type, conn_interval_min, conn_interval_max, conn_latency, timeout) ) { - ERR_PRINT("DBTAdapter::addDeviceToWhitelist: uploadConnParam(dev_id %d, address %s, interval[%u..%u], latency %u, timeout %u): Failed", - dev_id, address.toString().c_str(), conn_interval_min, conn_interval_max, conn_latency, timeout); + if( !mgmt.uploadConnParam(dev_id, addressAndType, conn_interval_min, conn_interval_max, conn_latency, timeout) ) { + ERR_PRINT("DBTAdapter::addDeviceToWhitelist: uploadConnParam(dev_id %d, address%s, interval[%u..%u], latency %u, timeout %u): Failed", + dev_id, addressAndType.toString().c_str(), conn_interval_min, conn_interval_max, conn_latency, timeout); } - return mgmt.addDeviceToWhitelist(dev_id, address, address_type, ctype); + return mgmt.addDeviceToWhitelist(dev_id, addressAndType, ctype); } -bool DBTAdapter::removeDeviceFromWhitelist(const EUI48 &address, const BDAddressType address_type) { - return mgmt.removeDeviceFromWhitelist(dev_id, address, address_type); +bool DBTAdapter::removeDeviceFromWhitelist(const BDAddressAndType & addressAndType) { + return mgmt.removeDeviceFromWhitelist(dev_id, addressAndType); } static jau::cow_vector<std::shared_ptr<AdapterStatusListener>>::equal_comparator _adapterStatusListenerRefEqComparator = @@ -760,9 +748,9 @@ exit: // ************************************************* -std::shared_ptr<DBTDevice> DBTAdapter::findDiscoveredDevice (EUI48 const & mac, const BDAddressType macType) noexcept { +std::shared_ptr<DBTDevice> DBTAdapter::findDiscoveredDevice (const EUI48 & address, const BDAddressType addressType) noexcept { const std::lock_guard<std::mutex> lock(const_cast<DBTAdapter*>(this)->mtx_discoveredDevices); // RAII-style acquire and relinquish via destructor - return findDevice(discoveredDevices, mac, macType); + return findDevice(discoveredDevices, address, addressType); } bool DBTAdapter::addDiscoveredDevice(std::shared_ptr<DBTDevice> const &device) noexcept { @@ -829,9 +817,9 @@ void DBTAdapter::removeSharedDevice(const DBTDevice & device) noexcept { } } -std::shared_ptr<DBTDevice> DBTAdapter::findSharedDevice (EUI48 const & mac, const BDAddressType macType) noexcept { +std::shared_ptr<DBTDevice> DBTAdapter::findSharedDevice (const EUI48 & address, const BDAddressType addressType) noexcept { const std::lock_guard<std::mutex> lock(mtx_sharedDevices); // RAII-style acquire and relinquish via destructor - return findDevice(sharedDevices, mac, macType); + return findDevice(sharedDevices, address, addressType); } void DBTAdapter::removeDevice(DBTDevice & device) noexcept { @@ -1322,7 +1310,7 @@ bool DBTAdapter::mgmtEvDeviceFoundHCI(std::shared_ptr<MgmtEvent> e) noexcept { // EIRDataType updateMask = dev->update(*eir); COND_PRINT(debug_event, "DBTAdapter:hci:DeviceFound: Drop already discovered %s, %s", - dev->getAddressString().c_str(), eir->toString().c_str()); + dev->getAddressAndType().toString().c_str(), eir->toString().c_str()); if( EIRDataType::NONE != updateMask ) { sendDeviceUpdated("DiscoveredDeviceFound", dev, eir->getTimestamp(), updateMask); } @@ -1341,7 +1329,7 @@ bool DBTAdapter::mgmtEvDeviceFoundHCI(std::shared_ptr<MgmtEvent> e) noexcept { addDiscoveredDevice(dev); // re-add to discovered devices! dev->ts_last_discovery = eir->getTimestamp(); COND_PRINT(debug_event, "DBTAdapter:hci:DeviceFound: Use already shared %s, %s", - dev->getAddressString().c_str(), eir->toString().c_str()); + dev->getAddressAndType().toString().c_str(), eir->toString().c_str()); int i=0; jau::for_each_cow(statusListenerList, [&](std::shared_ptr<AdapterStatusListener> &l) { @@ -1369,7 +1357,7 @@ bool DBTAdapter::mgmtEvDeviceFoundHCI(std::shared_ptr<MgmtEvent> e) noexcept { addDiscoveredDevice(dev); addSharedDevice(dev); COND_PRINT(debug_event, "DBTAdapter:hci:DeviceFound: Use new %s, %s", - dev->getAddressString().c_str(), eir->toString().c_str()); + dev->getAddressAndType().toString().c_str(), eir->toString().c_str()); int i=0; jau::for_each_cow(statusListenerList, [&](std::shared_ptr<AdapterStatusListener> &l) { @@ -1440,18 +1428,18 @@ bool DBTAdapter::mgmtEvUserPasskeyRequestMgmt(std::shared_ptr<MgmtEvent> e) noex return true; } -bool DBTAdapter::hciSMPMsgCallback(const EUI48& address, BDAddressType addressType, +bool DBTAdapter::hciSMPMsgCallback(const BDAddressAndType & addressAndType, std::shared_ptr<const SMPPDUMsg> msg, const HCIACLData::l2cap_frame& source) noexcept { - std::shared_ptr<DBTDevice> device = findConnectedDevice(address, addressType); + std::shared_ptr<DBTDevice> device = findConnectedDevice(addressAndType.address, addressAndType.type); if( nullptr == device ) { - WORDY_PRINT("DBTAdapter:hci:SMP: dev_id %d: Device not tracked: address[%s, %s]: %s, %s", - dev_id, address.toString().c_str(), getBDAddressTypeString(addressType).c_str(), + WORDY_PRINT("DBTAdapter:hci:SMP: dev_id %d: Device not tracked: address%s: %s, %s", + dev_id, addressAndType.toString().c_str(), msg->toString().c_str(), source.toString().c_str()); return true; } if( device->getConnectionHandle() != source.handle ) { - WORDY_PRINT("DBTAdapter:hci:SMP: dev_id %d: ConnHandle mismatch address[%s, %s]: %s, %s\n -> %s", - dev_id, address.toString().c_str(), getBDAddressTypeString(addressType).c_str(), + WORDY_PRINT("DBTAdapter:hci:SMP: dev_id %d: ConnHandle mismatch address%s: %s, %s\n -> %s", + dev_id, addressAndType.toString().c_str(), msg->toString().c_str(), source.toString().c_str(), device->toString().c_str()); return true; } diff --git a/src/direct_bt/DBTDevice.cpp b/src/direct_bt/DBTDevice.cpp index f8e889a2..0dfd3715 100644 --- a/src/direct_bt/DBTDevice.cpp +++ b/src/direct_bt/DBTDevice.cpp @@ -47,8 +47,7 @@ DBTDevice::DBTDevice(DBTAdapter & a, EInfoReport const & r) : adapter(a), l2cap_att(adapter.getAddress(), L2CAP_PSM_UNDEF, L2CAP_CID_ATT), ts_creation(r.getTimestamp()), - address(r.getAddress()), addressType(r.getAddressType()), - leRandomAddressType(address.getBLERandomAddressType(addressType)) + addressAndType{r.getAddress(), r.getAddressType()} { ts_last_discovery = ts_creation; hciConnHandle = 0; @@ -63,7 +62,8 @@ DBTDevice::DBTDevice(DBTAdapter & a, EInfoReport const & r) } update(r); - if( BDAddressType::BDADDR_LE_RANDOM == addressType ) { + const BLERandomAddressType leRandomAddressType = addressAndType.getBLERandomAddressType(); + if( BDAddressType::BDADDR_LE_RANDOM == addressAndType.type ) { if( BLERandomAddressType::UNDEFINED == leRandomAddressType ) { throw jau::IllegalArgumentException("BDADDR_LE_RANDOM: Invalid BLERandomAddressType "+ getBLERandomAddressTypeString(leRandomAddressType)+": "+toString(false), E_FILE_LINE); @@ -77,10 +77,10 @@ DBTDevice::DBTDevice(DBTAdapter & a, EInfoReport const & r) } DBTDevice::~DBTDevice() noexcept { - DBG_PRINT("DBTDevice::dtor: ... %p %s", this, getAddressString().c_str()); + DBG_PRINT("DBTDevice::dtor: ... %p %s", this, addressAndType.toString().c_str()); advServices.clear(); advMSD = nullptr; - DBG_PRINT("DBTDevice::dtor: XXX %p %s", this, getAddressString().c_str()); + DBG_PRINT("DBTDevice::dtor: XXX %p %s", this, addressAndType.toString().c_str()); } std::shared_ptr<DBTDevice> DBTDevice::getSharedInstance() const noexcept { @@ -135,13 +135,9 @@ std::vector<std::shared_ptr<uuid_t>> DBTDevice::getAdvertisedServices() const no std::string DBTDevice::toString(bool includeDiscoveredServices) const noexcept { const std::lock_guard<std::recursive_mutex> lock(const_cast<DBTDevice*>(this)->mtx_data); // RAII-style acquire and relinquish via destructor const uint64_t t0 = jau::getCurrentMilliseconds(); - std::string leaddrtype; - if( BLERandomAddressType::UNDEFINED != leRandomAddressType ) { - leaddrtype = ", random "+getBLERandomAddressTypeString(leRandomAddressType); - } jau::sc_atomic_critical sync(const_cast<DBTDevice*>(this)->sync_pairing); std::string msdstr = nullptr != advMSD ? advMSD->toString() : "MSD[null]"; - std::string out("Device[address["+getAddressString()+", "+getBDAddressTypeString(getAddressType())+leaddrtype+"], name['"+name+ + std::string out("Device["+addressAndType.toString()+", name['"+name+ "'], age[total "+std::to_string(t0-ts_creation)+", ldisc "+std::to_string(t0-ts_last_discovery)+", lup "+std::to_string(t0-ts_last_update)+ "]ms, connected["+std::to_string(allowDisconnect)+"/"+std::to_string(isConnected)+", handle "+jau::uint16HexString(hciConnHandle)+ ", sec[lvl "+getBTSecurityLevelString(pairing_data.sec_level_conn).c_str()+", io "+getSMPIOCapabilityString(pairing_data.ioCap_conn).c_str()+ @@ -169,13 +165,13 @@ EIRDataType DBTDevice::update(EInfoReport const & data) noexcept { EIRDataType res = EIRDataType::NONE; ts_last_update = data.getTimestamp(); if( data.isSet(EIRDataType::BDADDR) ) { - if( data.getAddress() != this->address ) { + if( data.getAddress() != this->addressAndType.address ) { WARN_PRINT("DBTDevice::update:: BDADDR update not supported: %s for %s", data.toString().c_str(), this->toString(false).c_str()); } } if( data.isSet(EIRDataType::BDADDR_TYPE) ) { - if( data.getAddressType() != this->addressType ) { + if( data.getAddressType() != this->addressAndType.type ) { WARN_PRINT("DBTDevice::update:: BDADDR_TYPE update not supported: %s for %s", data.toString().c_str(), this->toString(false).c_str()); } @@ -240,7 +236,7 @@ EIRDataType DBTDevice::update(GattGenericAccessSvc const &data, const uint64_t t std::shared_ptr<ConnectionInfo> DBTDevice::getConnectionInfo() noexcept { DBTManager & mgmt = adapter.getManager(); - std::shared_ptr<ConnectionInfo> connInfo = mgmt.getConnectionInfo(adapter.dev_id, address, addressType); + std::shared_ptr<ConnectionInfo> connInfo = mgmt.getConnectionInfo(adapter.dev_id, addressAndType); if( nullptr != connInfo ) { EIRDataType updateMask = EIRDataType::NONE; if( rssi != connInfo->getRSSI() ) { @@ -275,43 +271,44 @@ HCIStatusCode DBTDevice::connectLE(uint16_t le_scan_interval, uint16_t le_scan_w HCILEOwnAddressType hci_own_mac_type; HCILEPeerAddressType hci_peer_mac_type; - switch( addressType ) { + switch( addressAndType.type ) { case BDAddressType::BDADDR_LE_PUBLIC: hci_peer_mac_type = HCILEPeerAddressType::PUBLIC; hci_own_mac_type = HCILEOwnAddressType::PUBLIC; break; case BDAddressType::BDADDR_LE_RANDOM: { - switch( leRandomAddressType ) { - case BLERandomAddressType::UNRESOLVABLE_PRIVAT: - hci_peer_mac_type = HCILEPeerAddressType::RANDOM; - hci_own_mac_type = HCILEOwnAddressType::RANDOM; - ERR_PRINT("LE Random address type '%s' not supported yet: %s", - getBLERandomAddressTypeString(leRandomAddressType).c_str(), toString(false).c_str()); - return HCIStatusCode::UNACCEPTABLE_CONNECTION_PARAM; - case BLERandomAddressType::RESOLVABLE_PRIVAT: - hci_peer_mac_type = HCILEPeerAddressType::PUBLIC_IDENTITY; - hci_own_mac_type = HCILEOwnAddressType::RESOLVABLE_OR_PUBLIC; - ERR_PRINT("LE Random address type '%s' not supported yet: %s", - getBLERandomAddressTypeString(leRandomAddressType).c_str(), toString(false).c_str()); - return HCIStatusCode::UNACCEPTABLE_CONNECTION_PARAM; - case BLERandomAddressType::STATIC_PUBLIC: - // FIXME: This only works for a static random address not changing at all, - // i.e. between power-cycles - hence a temporary hack. - // We need to use 'resolving list' and/or LE Set Privacy Mode (HCI) for all devices. - hci_peer_mac_type = HCILEPeerAddressType::RANDOM; - hci_own_mac_type = HCILEOwnAddressType::PUBLIC; - break; - default: { - ERR_PRINT("Can't connectLE to LE Random address type '%s': %s", - getBLERandomAddressTypeString(leRandomAddressType).c_str(), toString(false).c_str()); - return HCIStatusCode::UNACCEPTABLE_CONNECTION_PARAM; - } + const BLERandomAddressType leRandomAddressType = addressAndType.getBLERandomAddressType(); + switch( leRandomAddressType ) { + case BLERandomAddressType::UNRESOLVABLE_PRIVAT: + hci_peer_mac_type = HCILEPeerAddressType::RANDOM; + hci_own_mac_type = HCILEOwnAddressType::RANDOM; + ERR_PRINT("LE Random address type '%s' not supported yet: %s", + getBLERandomAddressTypeString(leRandomAddressType).c_str(), toString(false).c_str()); + return HCIStatusCode::UNACCEPTABLE_CONNECTION_PARAM; + case BLERandomAddressType::RESOLVABLE_PRIVAT: + hci_peer_mac_type = HCILEPeerAddressType::PUBLIC_IDENTITY; + hci_own_mac_type = HCILEOwnAddressType::RESOLVABLE_OR_PUBLIC; + ERR_PRINT("LE Random address type '%s' not supported yet: %s", + getBLERandomAddressTypeString(leRandomAddressType).c_str(), toString(false).c_str()); + return HCIStatusCode::UNACCEPTABLE_CONNECTION_PARAM; + case BLERandomAddressType::STATIC_PUBLIC: + // FIXME: This only works for a static random address not changing at all, + // i.e. between power-cycles - hence a temporary hack. + // We need to use 'resolving list' and/or LE Set Privacy Mode (HCI) for all devices. + hci_peer_mac_type = HCILEPeerAddressType::RANDOM; + hci_own_mac_type = HCILEOwnAddressType::PUBLIC; + break; + default: { + ERR_PRINT("Can't connectLE to LE Random address type '%s': %s", + getBLERandomAddressTypeString(leRandomAddressType).c_str(), toString(false).c_str()); + return HCIStatusCode::UNACCEPTABLE_CONNECTION_PARAM; } - } break; - default: { - ERR_PRINT("Can't connectLE to address type '%s': %s", getBDAddressTypeString(addressType).c_str(), toString(false).c_str()); - return HCIStatusCode::UNACCEPTABLE_CONNECTION_PARAM; } + } break; + default: { + ERR_PRINT("Can't connectLE to address type '%s': %s", getBDAddressTypeString(addressAndType.type).c_str(), toString(false).c_str()); + return HCIStatusCode::UNACCEPTABLE_CONNECTION_PARAM; + } } if( isConnected ) { @@ -332,7 +329,7 @@ HCIStatusCode DBTDevice::connectLE(uint16_t le_scan_interval, uint16_t le_scan_w return HCIStatusCode::INTERNAL_FAILURE; } } - HCIStatusCode status = hci.le_create_conn(address, + HCIStatusCode status = hci.le_create_conn(addressAndType.address, hci_peer_mac_type, hci_own_mac_type, le_scan_interval, le_scan_window, conn_interval_min, conn_interval_max, conn_latency, supervision_timeout); @@ -367,7 +364,7 @@ HCIStatusCode DBTDevice::connectBREDR(const uint16_t pkt_type, const uint16_t cl ERR_PRINT("DBTDevice::connectBREDR: Already connected: %s", toString(false).c_str()); return HCIStatusCode::CONNECTION_ALREADY_EXISTS; } - if( !isBREDRAddressType() ) { + if( !addressAndType.isBREDRAddress() ) { ERR_PRINT("DBTDevice::connectBREDR: Not a BDADDR_BREDR address: %s", toString(false).c_str()); return HCIStatusCode::UNACCEPTABLE_CONNECTION_PARAM; } @@ -385,7 +382,7 @@ HCIStatusCode DBTDevice::connectBREDR(const uint16_t pkt_type, const uint16_t cl return HCIStatusCode::INTERNAL_FAILURE; } } - HCIStatusCode status = hci.create_conn(address, pkt_type, clock_offset, role_switch); + HCIStatusCode status = hci.create_conn(addressAndType.address, pkt_type, clock_offset, role_switch); allowDisconnect = true; if ( HCIStatusCode::SUCCESS != status ) { ERR_PRINT("DBTDevice::connectBREDR: Could not create connection: status 0x%2.2X (%s), errno %d %s on %s", @@ -397,7 +394,7 @@ HCIStatusCode DBTDevice::connectBREDR(const uint16_t pkt_type, const uint16_t cl HCIStatusCode DBTDevice::connectDefault() { - switch( addressType ) { + switch( addressAndType.type ) { case BDAddressType::BDADDR_LE_PUBLIC: [[fallthrough]]; case BDAddressType::BDADDR_LE_RANDOM: @@ -432,7 +429,7 @@ void DBTDevice::notifyLEFeatures(std::shared_ptr<DBTDevice> sthis, const LEFeatu isLEFeaturesBitSet(features, LEFeatures::LE_Encryption), toString(false).c_str()); le_features = features; - if( isLEAddressType() && !l2cap_att.isOpen() ) { + if( addressAndType.isLEAddress() && !l2cap_att.isOpen() ) { std::thread bg(&DBTDevice::processL2CAPSetup, this, sthis); // @suppress("Invalid arguments") bg.detach(); } @@ -443,7 +440,7 @@ void DBTDevice::processL2CAPSetup(std::shared_ptr<DBTDevice> sthis) { jau::sc_atomic_critical sync(sync_pairing); DBG_PRINT("DBTDevice::processL2CAPSetup: Start %s", toString(false).c_str()); - if( isLEAddressType() && !l2cap_att.isOpen() ) { + if( addressAndType.isLEAddress() && !l2cap_att.isOpen() ) { const BTSecurityLevel sec_level_user = pairing_data.sec_level_user; const SMPIOCapability io_cap_conn = pairing_data.ioCap_conn; BTSecurityLevel sec_level { BTSecurityLevel::UNSET }; @@ -545,9 +542,9 @@ bool DBTDevice::checkPairingKeyDistributionComplete(const std::string& timestamp } if( jau::environment::get().debug ) { - jau::PLAIN_PRINT(false, "[%s] Debug: DBTDevice:SMP:KEY_DISTRIBUTION: done %d, address[%s, %s]", + jau::PLAIN_PRINT(false, "[%s] Debug: DBTDevice:SMP:KEY_DISTRIBUTION: done %d, address%s", timestamp.c_str(), res, - address.toString().c_str(), getBDAddressTypeString(addressType).c_str()); + addressAndType.toString().c_str()); jau::PLAIN_PRINT(false, "[%s] - keys[init %s / %s, resp %s / %s]", timestamp.c_str(), getSMPKeyTypeMaskString(pairing_data.keys_init_has).c_str(), @@ -698,9 +695,9 @@ void DBTDevice::hciSMPMsgCallback(std::shared_ptr<DBTDevice> sthis, std::shared_ bool is_device_ready = false; if( jau::environment::get().debug ) { - jau::PLAIN_PRINT(false, "[%s] Debug: DBTDevice:hci:SMP.0: address[%s, %s]", + jau::PLAIN_PRINT(false, "[%s] Debug: DBTDevice:hci:SMP.0: address%s", timestamp.c_str(), - address.toString().c_str(), getBDAddressTypeString(addressType).c_str()); + addressAndType.toString().c_str()); jau::PLAIN_PRINT(false, "[%s] - %s", timestamp.c_str(), msg->toString().c_str()); jau::PLAIN_PRINT(false, "[%s] - %s", timestamp.c_str(), source.toString().c_str()); jau::PLAIN_PRINT(false, "[%s] - %s", timestamp.c_str(), toString(false).c_str()); @@ -752,8 +749,8 @@ void DBTDevice::hciSMPMsgCallback(std::shared_ptr<DBTDevice> sthis, std::shared_ if( jau::environment::get().debug ) { jau::PLAIN_PRINT(false, "[%s] ", timestamp.c_str()); - jau::PLAIN_PRINT(false, "[%s] Debug: DBTDevice:hci:SMP.2: address[%s, %s]: State %s, Mode %s, using SC %d:", timestamp.c_str() , - address.toString().c_str(), getBDAddressTypeString(addressType).c_str(), + jau::PLAIN_PRINT(false, "[%s] Debug: DBTDevice:hci:SMP.2: address%s: State %s, Mode %s, using SC %d:", timestamp.c_str() , + addressAndType.toString().c_str(), getSMPPairingStateString(pstate).c_str(), getPairingModeString(pmode).c_str(), use_sc); jau::PLAIN_PRINT(false, "[%s] - oob: init %s", timestamp.c_str(), getSMPOOBDataFlagString(pairing_data.oobFlag_init).c_str()); jau::PLAIN_PRINT(false, "[%s] - oob: resp %s", timestamp.c_str(), getSMPOOBDataFlagString(pairing_data.oobFlag_resp).c_str()); @@ -912,13 +909,13 @@ void DBTDevice::hciSMPMsgCallback(std::shared_ptr<DBTDevice> sthis, std::shared_ if( jau::environment::get().debug ) { if( old_pstate == pstate /* && old_pmode == pmode */ ) { - jau::PLAIN_PRINT(false, "[%s] Debug: DBTDevice:hci:SMP.4: Unchanged: address[%s, %s]", + jau::PLAIN_PRINT(false, "[%s] Debug: DBTDevice:hci:SMP.4: Unchanged: address%s", timestamp.c_str(), - address.toString().c_str(), getBDAddressTypeString(addressType).c_str()); + addressAndType.toString().c_str()); } else { - jau::PLAIN_PRINT(false, "[%s] Debug: DBTDevice:hci:SMP.5: Updated: address[%s, %s]", + jau::PLAIN_PRINT(false, "[%s] Debug: DBTDevice:hci:SMP.5: Updated: address%s", timestamp.c_str(), - address.toString().c_str(), getBDAddressTypeString(addressType).c_str()); + addressAndType.toString().c_str()); } jau::PLAIN_PRINT(false, "[%s] - state %s -> %s, mode %s -> %s, ready %d", timestamp.c_str(), @@ -980,7 +977,7 @@ HCIStatusCode DBTDevice::setLongTermKeyInfo(const SMPLongTermKeyInfo& ltk) noexc pairing_data.ltk_init = ltk; } DBTManager & mngr = adapter.getManager(); - HCIStatusCode res = mngr.uploadLongTermKeyInfo(adapter.dev_id, address, addressType, ltk); + HCIStatusCode res = mngr.uploadLongTermKeyInfo(adapter.dev_id, addressAndType, ltk); return res; } @@ -1004,11 +1001,11 @@ HCIStatusCode DBTDevice::pair(const SMPIOCapability io_cap) noexcept { DBTManager& mngr = adapter.getManager(); DBG_PRINT("DBTDevice::pairDevice: Start: io %s, %s", getSMPIOCapabilityString(io_cap).c_str(), toString(false).c_str()); - mngr.uploadConnParam(adapter.dev_id, address, addressType); + mngr.uploadConnParam(adapter.dev_id, addressAndType); jau::sc_atomic_critical sync(sync_pairing); pairing_data.ioCap_conn = io_cap; - const bool res = mngr.pairDevice(adapter.dev_id, address, addressType, io_cap); + const bool res = mngr.pairDevice(adapter.dev_id, addressAndType, io_cap); if( !res ) { pairing_data.ioCap_conn = SMPIOCapability::UNSET; } @@ -1120,7 +1117,7 @@ HCIStatusCode DBTDevice::setPairingPasskey(const uint32_t passkey) noexcept { if( SMPPairingState::PASSKEY_EXPECTED == pairing_data.state ) { DBTManager& mngr = adapter.getManager(); - MgmtStatus res = mngr.userPasskeyReply(adapter.dev_id, address, addressType, passkey); + MgmtStatus res = mngr.userPasskeyReply(adapter.dev_id, addressAndType, passkey); DBG_PRINT("DBTDevice:mgmt:SMP: PASSKEY '%d', state %s, result %s", passkey, getSMPPairingStateString(pairing_data.state).c_str(), getMgmtStatusString(res).c_str()); return HCIStatusCode::SUCCESS; @@ -1137,7 +1134,7 @@ HCIStatusCode DBTDevice::setPairingPasskeyNegative() noexcept { if( SMPPairingState::PASSKEY_EXPECTED == pairing_data.state ) { DBTManager& mngr = adapter.getManager(); - MgmtStatus res = mngr.userPasskeyNegativeReply(adapter.dev_id, address, addressType); + MgmtStatus res = mngr.userPasskeyNegativeReply(adapter.dev_id, addressAndType); DBG_PRINT("DBTDevice:mgmt:SMP: PASSKEY NEGATIVE, state %s, result %s", getSMPPairingStateString(pairing_data.state).c_str(), getMgmtStatusString(res).c_str()); return HCIStatusCode::SUCCESS; @@ -1154,7 +1151,7 @@ HCIStatusCode DBTDevice::setPairingNumericComparison(const bool positive) noexce if( SMPPairingState::NUMERIC_COMPARE_EXPECTED == pairing_data.state ) { DBTManager& mngr = adapter.getManager(); - MgmtStatus res = mngr.userConfirmReply(adapter.dev_id, address, addressType, positive); + MgmtStatus res = mngr.userConfirmReply(adapter.dev_id, addressAndType, positive); DBG_PRINT("DBTDevice:mgmt:SMP: CONFIRM '%d', state %s, result %s", positive, getSMPPairingStateString(pairing_data.state).c_str(), getMgmtStatusString(res).c_str()); return HCIStatusCode::SUCCESS; @@ -1483,7 +1480,7 @@ HCIStatusCode DBTDevice::disconnect(const HCIStatusCode reason) noexcept { goto exit; } - res = hci.disconnect(hciConnHandle.load(), address, addressType, reason); + res = hci.disconnect(hciConnHandle.load(), addressAndType, reason); if( HCIStatusCode::SUCCESS != res ) { ERR_PRINT("DBTDevice::disconnect: status %s, handle 0x%X, isConnected %d/%d: errno %d %s on %s", getHCIStatusCodeString(res).c_str(), hciConnHandle.load(), @@ -1499,7 +1496,7 @@ exit: // send the DISCONN_COMPLETE event directly. // SEND_EVENT: Perform off-thread to avoid potential deadlock w/ application callbacks (similar when sent from HCIHandler's reader-thread) std::thread bg(&DBTAdapter::mgmtEvDeviceDisconnectedHCI, &adapter, std::shared_ptr<MgmtEvent>( // @suppress("Invalid arguments") - new MgmtEvtDeviceDisconnected(adapter.dev_id, address, addressType, reason, hciConnHandle.load()) ) ); + new MgmtEvtDeviceDisconnected(adapter.dev_id, addressAndType, reason, hciConnHandle.load()) ) ); bg.detach(); // adapter.mgmtEvDeviceDisconnectedHCI( std::shared_ptr<MgmtEvent>( new MgmtEvtDeviceDisconnected(adapter.dev_id, address, addressType, reason, hciConnHandle.load()) ) ); } @@ -1513,7 +1510,7 @@ exit: HCIStatusCode DBTDevice::unpair() noexcept { #if USE_LINUX_BT_SECURITY - const MgmtStatus res = adapter.getManager().unpairDevice(adapter.dev_id, address, addressType, false /* disconnect */); + const MgmtStatus res = adapter.getManager().unpairDevice(adapter.dev_id, addressAndType, false /* disconnect */); clearSMPStates(false /* connected */); return getHCIStatusCode(res); #elif SMP_SUPPORTED_BY_OS diff --git a/src/direct_bt/DBTManager.cpp b/src/direct_bt/DBTManager.cpp index 1fcd3a7d..e442c660 100644 --- a/src/direct_bt/DBTManager.cpp +++ b/src/direct_bt/DBTManager.cpp @@ -322,7 +322,7 @@ std::shared_ptr<AdapterInfo> DBTManager::initAdapter(const uint16_t dev_id, cons setMode(dev_id, MgmtCommand::Opcode::SET_CONNECTABLE, 0, current_settings); setMode(dev_id, MgmtCommand::Opcode::SET_FAST_CONNECTABLE, 0, current_settings); - removeDeviceFromWhitelist(dev_id, EUI48_ANY_DEVICE, BDAddressType::BDADDR_BREDR); // flush whitelist! + removeDeviceFromWhitelist(dev_id, BDAddressAndType::ANY_BREDR_DEVICE); // flush whitelist! setMode(dev_id, MgmtCommand::Opcode::SET_POWERED, 1, current_settings); @@ -834,10 +834,10 @@ bool DBTManager::stopDiscovery(const uint16_t dev_id, const ScanType type) noexc return false; } -bool DBTManager::uploadConnParam(const uint16_t dev_id, const EUI48 &address, const BDAddressType address_type, +bool DBTManager::uploadConnParam(const uint16_t dev_id, const BDAddressAndType & addressAndType, const uint16_t conn_min_interval, const uint16_t conn_max_interval, const uint16_t conn_latency, const uint16_t supervision_timeout) noexcept { - MgmtConnParam connParam{ address, address_type, conn_min_interval, conn_max_interval, conn_latency, supervision_timeout }; + MgmtConnParam connParam{ addressAndType.address, addressAndType.type, conn_min_interval, conn_max_interval, conn_latency, supervision_timeout }; MgmtLoadConnParamCmd req(dev_id, connParam); std::shared_ptr<MgmtEvent> res = sendWithReply(req); if( nullptr != res && res->getOpcode() == MgmtEvent::Opcode::CMD_COMPLETE ) { @@ -877,11 +877,11 @@ HCIStatusCode DBTManager::uploadLongTermKey(const uint16_t dev_id, const MgmtLon return res; } -HCIStatusCode DBTManager::uploadLongTermKeyInfo(const uint16_t dev_id, const EUI48& address, BDAddressType address_type, +HCIStatusCode DBTManager::uploadLongTermKeyInfo(const uint16_t dev_id, const BDAddressAndType & addressAndType, const SMPLongTermKeyInfo& ltk) noexcept { const MgmtLTKType key_type = getMgmtLTKType(ltk.properties); const bool responder = ( SMPLongTermKeyInfo::Property::RESPONDER & ltk.properties ) != SMPLongTermKeyInfo::Property::NONE; - const MgmtLongTermKeyInfo mgmt_ltk_info { address, address_type, key_type, responder, ltk.enc_size, ltk.ediv, ltk.rand, ltk.ltk }; + const MgmtLongTermKeyInfo mgmt_ltk_info { addressAndType.address, addressAndType.type, key_type, responder, ltk.enc_size, ltk.ediv, ltk.rand, ltk.ltk }; MgmtLoadLongTermKeyCmd req(dev_id, mgmt_ltk_info); HCIStatusCode res; std::shared_ptr<MgmtEvent> reply = sendWithReply(req); @@ -901,8 +901,8 @@ HCIStatusCode DBTManager::uploadLongTermKeyInfo(const uint16_t dev_id, const EUI return res; } -MgmtStatus DBTManager::userPasskeyReply(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType, const uint32_t passkey) noexcept { - MgmtUserPasskeyReplyCmd cmd(dev_id, address, addressType, passkey); +MgmtStatus DBTManager::userPasskeyReply(const uint16_t dev_id, const BDAddressAndType & addressAndType, const uint32_t passkey) noexcept { + MgmtUserPasskeyReplyCmd cmd(dev_id, addressAndType, passkey); std::shared_ptr<MgmtEvent> res = sendWithReply(cmd); if( nullptr != res && res->getOpcode() == MgmtEvent::Opcode::CMD_COMPLETE ) { const MgmtEvtCmdComplete &res1 = *static_cast<const MgmtEvtCmdComplete *>(res.get()); @@ -912,8 +912,8 @@ MgmtStatus DBTManager::userPasskeyReply(const uint16_t dev_id, const EUI48 &addr return MgmtStatus::TIMEOUT; } -MgmtStatus DBTManager::userPasskeyNegativeReply(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType) noexcept { - MgmtUserPasskeyNegativeReplyCmd cmd(dev_id, address, addressType); +MgmtStatus DBTManager::userPasskeyNegativeReply(const uint16_t dev_id, const BDAddressAndType & addressAndType) noexcept { + MgmtUserPasskeyNegativeReplyCmd cmd(dev_id, addressAndType); std::shared_ptr<MgmtEvent> res = sendWithReply(cmd); if( nullptr != res && res->getOpcode() == MgmtEvent::Opcode::CMD_COMPLETE ) { const MgmtEvtCmdComplete &res1 = *static_cast<const MgmtEvtCmdComplete *>(res.get()); @@ -923,13 +923,13 @@ MgmtStatus DBTManager::userPasskeyNegativeReply(const uint16_t dev_id, const EUI return MgmtStatus::TIMEOUT; } -MgmtStatus DBTManager::userConfirmReply(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType, const bool positive) noexcept { +MgmtStatus DBTManager::userConfirmReply(const uint16_t dev_id, const BDAddressAndType & addressAndType, const bool positive) noexcept { std::shared_ptr<MgmtEvent> res; if( positive ) { - MgmtUserConfirmReplyCmd cmd(dev_id, address, addressType); + MgmtUserConfirmReplyCmd cmd(dev_id, addressAndType); res = sendWithReply(cmd); } else { - MgmtUserConfirmNegativeReplyCmd cmd(dev_id, address, addressType); + MgmtUserConfirmNegativeReplyCmd cmd(dev_id, addressAndType); res = sendWithReply(cmd); } if( nullptr != res && res->getOpcode() == MgmtEvent::Opcode::CMD_COMPLETE ) { @@ -940,13 +940,13 @@ MgmtStatus DBTManager::userConfirmReply(const uint16_t dev_id, const EUI48 &addr return MgmtStatus::TIMEOUT; } -bool DBTManager::pairDevice(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType, const SMPIOCapability iocap) noexcept { - MgmtPairDeviceCmd cmd(dev_id, address, addressType, iocap); +bool DBTManager::pairDevice(const uint16_t dev_id, const BDAddressAndType & addressAndType, const SMPIOCapability iocap) noexcept { + MgmtPairDeviceCmd cmd(dev_id, addressAndType, iocap); return send(cmd); } -MgmtStatus DBTManager::unpairDevice(const uint16_t dev_id, const EUI48 &address, const BDAddressType addressType, const bool disconnect) noexcept { - MgmtUnpairDeviceCmd cmd(dev_id, address, addressType, disconnect); +MgmtStatus DBTManager::unpairDevice(const uint16_t dev_id, const BDAddressAndType & addressAndType, const bool disconnect) noexcept { + MgmtUnpairDeviceCmd cmd(dev_id, addressAndType, disconnect); std::shared_ptr<MgmtEvent> res = sendWithReply(cmd); if( nullptr != res && res->getOpcode() == MgmtEvent::Opcode::CMD_COMPLETE ) { @@ -957,10 +957,10 @@ MgmtStatus DBTManager::unpairDevice(const uint16_t dev_id, const EUI48 &address, return MgmtStatus::TIMEOUT; } -bool DBTManager::isDeviceWhitelisted(const uint16_t dev_id, const EUI48 &address) noexcept { +bool DBTManager::isDeviceWhitelisted(const uint16_t dev_id, const BDAddressAndType & addressAndType) noexcept { for(auto it = whitelist.begin(); it != whitelist.end(); ) { std::shared_ptr<WhitelistElem> wle = *it; - if( wle->dev_id == dev_id && wle->address == address ) { + if( wle->dev_id == dev_id && wle->address_and_type == addressAndType ) { return true; } else { ++it; @@ -969,11 +969,11 @@ bool DBTManager::isDeviceWhitelisted(const uint16_t dev_id, const EUI48 &address return false; } -bool DBTManager::addDeviceToWhitelist(const uint16_t dev_id, const EUI48 &address, const BDAddressType address_type, const HCIWhitelistConnectType ctype) noexcept { - MgmtAddDeviceToWhitelistCmd req(dev_id, address, address_type, ctype); +bool DBTManager::addDeviceToWhitelist(const uint16_t dev_id, const BDAddressAndType & addressAndType, const HCIWhitelistConnectType ctype) noexcept { + MgmtAddDeviceToWhitelistCmd req(dev_id, addressAndType, ctype); // Check if already exist in our local whitelist first, reject if so .. - if( isDeviceWhitelisted(dev_id, address) ) { + if( isDeviceWhitelisted(dev_id, addressAndType) ) { ERR_PRINT("DBTManager::addDeviceToWhitelist: Already in local whitelist, remove first: %s", req.toString().c_str()); return false; } @@ -981,7 +981,7 @@ bool DBTManager::addDeviceToWhitelist(const uint16_t dev_id, const EUI48 &addres if( nullptr != res && res->getOpcode() == MgmtEvent::Opcode::CMD_COMPLETE ) { const MgmtEvtCmdComplete &res1 = *static_cast<const MgmtEvtCmdComplete *>(res.get()); if( MgmtStatus::SUCCESS == res1.getStatus() ) { - std::shared_ptr<WhitelistElem> wle( new WhitelistElem{dev_id, address, address_type, ctype} ); + std::shared_ptr<WhitelistElem> wle( new WhitelistElem{dev_id, addressAndType, ctype} ); whitelist.push_back(wle); return true; } @@ -1005,7 +1005,7 @@ int DBTManager::removeAllDevicesFromWhitelist() noexcept { DBG_PRINT("DBTManager::removeAllDevicesFromWhitelist.B: Start %d elements", count); whitelist.clear(); jau::for_each_cow(adapterInfos, [&](std::shared_ptr<AdapterInfo> & a) { - removeDeviceFromWhitelist(a->dev_id, EUI48_ANY_DEVICE, BDAddressType::BDADDR_BREDR); // flush whitelist! + removeDeviceFromWhitelist(a->dev_id, BDAddressAndType::ANY_BREDR_DEVICE); // flush whitelist! }); #endif @@ -1014,12 +1014,12 @@ int DBTManager::removeAllDevicesFromWhitelist() noexcept { return count; } -bool DBTManager::removeDeviceFromWhitelist(const uint16_t dev_id, const EUI48 &address, const BDAddressType address_type) noexcept { +bool DBTManager::removeDeviceFromWhitelist(const uint16_t dev_id, const BDAddressAndType & addressAndType) noexcept { // Remove from our local whitelist first { for(auto it = whitelist.begin(); it != whitelist.end(); ) { std::shared_ptr<WhitelistElem> wle = *it; - if( wle->dev_id == dev_id && wle->address == address ) { + if( wle->dev_id == dev_id && wle->address_and_type == addressAndType ) { it = whitelist.erase(it); } else { ++it; @@ -1028,7 +1028,7 @@ bool DBTManager::removeDeviceFromWhitelist(const uint16_t dev_id, const EUI48 &a } // Actual removal - MgmtRemoveDeviceFromWhitelistCmd req(dev_id, address, address_type); + MgmtRemoveDeviceFromWhitelistCmd req(dev_id, addressAndType); std::shared_ptr<MgmtEvent> res = sendWithReply(req); if( nullptr != res && res->getOpcode() == MgmtEvent::Opcode::CMD_COMPLETE ) { const MgmtEvtCmdComplete &res1 = *static_cast<const MgmtEvtCmdComplete *>(res.get()); @@ -1040,7 +1040,7 @@ bool DBTManager::removeDeviceFromWhitelist(const uint16_t dev_id, const EUI48 &a } bool DBTManager::disconnect(const bool ioErrorCause, - const uint16_t dev_id, const EUI48 &peer_bdaddr, const BDAddressType peer_mac_type, + const uint16_t dev_id, const BDAddressAndType & addressAndType, const HCIStatusCode reason) noexcept { bool bres = false; @@ -1048,7 +1048,7 @@ bool DBTManager::disconnect(const bool ioErrorCause, // see Issue #124 fast re-connect on CSR adapter. // This will always notify the adapter of a disconnected device. { - MgmtDisconnectCmd req(dev_id, peer_bdaddr, peer_mac_type); + MgmtDisconnectCmd req(dev_id, addressAndType); std::shared_ptr<MgmtEvent> res = sendWithReply(req); if( nullptr != res && res->getOpcode() == MgmtEvent::Opcode::CMD_COMPLETE ) { const MgmtEvtCmdComplete &res1 = *static_cast<const MgmtEvtCmdComplete *>(res.get()); @@ -1060,14 +1060,14 @@ bool DBTManager::disconnect(const bool ioErrorCause, if( !ioErrorCause ) { // In case of an ioError (lost-connection), don't wait for the lagging // DISCONN_COMPLETE event but send it directly. - MgmtEvtDeviceDisconnected *e = new MgmtEvtDeviceDisconnected(dev_id, peer_bdaddr, peer_mac_type, reason, 0xffff); + MgmtEvtDeviceDisconnected *e = new MgmtEvtDeviceDisconnected(dev_id, addressAndType, reason, 0xffff); sendMgmtEvent(std::shared_ptr<MgmtEvent>(e)); } return bres; } -std::shared_ptr<ConnectionInfo> DBTManager::getConnectionInfo(const uint16_t dev_id, const EUI48 &address, const BDAddressType address_type) noexcept { - MgmtGetConnectionInfoCmd req(dev_id, address, address_type); +std::shared_ptr<ConnectionInfo> DBTManager::getConnectionInfo(const uint16_t dev_id, const BDAddressAndType& addressAndType) noexcept { + MgmtGetConnectionInfoCmd req(dev_id, addressAndType); std::shared_ptr<MgmtEvent> res = sendWithReply(req); if( nullptr != res && res->getOpcode() == MgmtEvent::Opcode::CMD_COMPLETE ) { const MgmtEvtCmdComplete &res1 = *static_cast<const MgmtEvtCmdComplete *>(res.get()); diff --git a/src/direct_bt/GATTHandler.cpp b/src/direct_bt/GATTHandler.cpp index 51098f2f..9b7ba3b8 100644 --- a/src/direct_bt/GATTHandler.cpp +++ b/src/direct_bt/GATTHandler.cpp @@ -285,7 +285,7 @@ GATTHandler::GATTHandler(const std::shared_ptr<DBTDevice> &device, L2CAPComm& l2 : env(GATTEnv::get()), wbr_device(device), l2cap(l2cap_att), - deviceString(device->getAddressString()), + deviceString(device->getAddressAndType().toString()), rbuffer(number(Defaults::MAX_ATT_MTU)), is_connected(l2cap.isOpen()), has_ioerror(false), attPDURing(env.ATTPDU_RING_CAPACITY), l2capReaderShallStop(false), diff --git a/src/direct_bt/HCIHandler.cpp b/src/direct_bt/HCIHandler.cpp index 22077640..f4cca0dd 100644 --- a/src/direct_bt/HCIHandler.cpp +++ b/src/direct_bt/HCIHandler.cpp @@ -77,21 +77,21 @@ __pack( struct hci_rp_status { } ); HCIHandler::HCIConnectionRef HCIHandler::addOrUpdateHCIConnection(std::vector<HCIConnectionRef> &list, - const EUI48 & address, BDAddressType addrType, const uint16_t handle) noexcept { + const BDAddressAndType& addressAndType, const uint16_t handle) noexcept { const std::lock_guard<std::recursive_mutex> lock(mtx_connectionList); // RAII-style acquire and relinquish via destructor // remove all old entry with given address first for (auto it = list.begin(); it != list.end(); ) { HCIConnectionRef conn = *it; - if ( conn->equals(address, addrType) ) { + if ( conn->equals(addressAndType) ) { // reuse same entry - WORDY_PRINT("HCIHandler::addTrackerConnection: address[%s, %s], handle %s: reuse entry %s - %s", - address.toString().c_str(), getBDAddressTypeString(addrType).c_str(), jau::uint16HexString(handle).c_str(), + WORDY_PRINT("HCIHandler::addTrackerConnection: address%s, handle %s: reuse entry %s - %s", + addressAndType.toString().c_str(), jau::uint16HexString(handle).c_str(), conn->toString().c_str(), toString().c_str()); // Overwrite tracked connection handle with given _valid_ handle only, i.e. non zero! if( 0 != handle ) { if( 0 != conn->getHandle() && handle != conn->getHandle() ) { - WARN_PRINT("HCIHandler::addTrackerConnection: address[%s, %s], handle %s: reusing entry %s, overwriting non-zero handle - %s", - address.toString().c_str(), getBDAddressTypeString(addrType).c_str(), jau::uint16HexString(handle).c_str(), + WARN_PRINT("HCIHandler::addTrackerConnection: address%s, handle %s: reusing entry %s, overwriting non-zero handle - %s", + addressAndType.toString().c_str(), jau::uint16HexString(handle).c_str(), conn->toString().c_str(), toString().c_str()); } conn->setHandle( handle ); @@ -101,17 +101,17 @@ HCIHandler::HCIConnectionRef HCIHandler::addOrUpdateHCIConnection(std::vector<HC ++it; } } - HCIConnectionRef res( new HCIConnection(address, addrType, handle) ); + HCIConnectionRef res( new HCIConnection(addressAndType, handle) ); list.push_back( res ); return res; } -HCIHandler::HCIConnectionRef HCIHandler::findHCIConnection(std::vector<HCIConnectionRef> &list, const EUI48 & address, BDAddressType addrType) noexcept { +HCIHandler::HCIConnectionRef HCIHandler::findHCIConnection(std::vector<HCIConnectionRef> &list, const BDAddressAndType& addressAndType) noexcept { const std::lock_guard<std::recursive_mutex> lock(mtx_connectionList); // RAII-style acquire and relinquish via destructor const size_t size = list.size(); for (size_t i = 0; i < size; i++) { HCIConnectionRef & e = list[i]; - if( e->equals(address, addrType) ) { + if( e->equals(addressAndType) ) { return e; } } @@ -206,13 +206,13 @@ std::shared_ptr<MgmtEvent> HCIHandler::translate(std::shared_ptr<HCIEvent> ev) n return nullptr; } const HCILEPeerAddressType hciAddrType = static_cast<HCILEPeerAddressType>(ev_cc->bdaddr_type); - const BDAddressType addrType = getBDAddressType(hciAddrType); + const BDAddressAndType addressAndType(ev_cc->bdaddr, getBDAddressType(hciAddrType)); const uint16_t handle = jau::le_to_cpu(ev_cc->handle); - const HCIConnectionRef conn = addOrUpdateTrackerConnection(ev_cc->bdaddr, addrType, handle); + const HCIConnectionRef conn = addOrUpdateTrackerConnection(addressAndType, handle); if( HCIStatusCode::SUCCESS == status ) { - return std::shared_ptr<MgmtEvent>( new MgmtEvtDeviceConnected(dev_id, ev_cc->bdaddr, addrType, handle) ); + return std::shared_ptr<MgmtEvent>( new MgmtEvtDeviceConnected(dev_id, addressAndType, handle) ); } else { - std::shared_ptr<MgmtEvent> res( new MgmtEvtDeviceConnectFailed(dev_id, ev_cc->bdaddr, addrType, status) ); + std::shared_ptr<MgmtEvent> res( new MgmtEvtDeviceConnectFailed(dev_id, addressAndType, status) ); removeTrackerConnection(conn); return res; } @@ -238,7 +238,7 @@ std::shared_ptr<MgmtEvent> HCIHandler::translate(std::shared_ptr<HCIEvent> ev) n getHCIStatusCodeString(status).c_str(), jau::uint16HexString(handle), conn->toString().c_str()); return nullptr; } - return std::shared_ptr<MgmtEvent>( new MgmtEvtHCILERemoteUserFeatures(dev_id, conn->getAddress(), conn->getAddressType(), features) ); + return std::shared_ptr<MgmtEvent>( new MgmtEvtHCILERemoteUserFeatures(dev_id, conn->getAddressAndType(), features) ); } default: return nullptr; @@ -253,11 +253,12 @@ std::shared_ptr<MgmtEvent> HCIHandler::translate(std::shared_ptr<HCIEvent> ev) n ev->toString().c_str(), toString().c_str()); return nullptr; } - HCIConnectionRef conn = addOrUpdateTrackerConnection(ev_cc->bdaddr, BDAddressType::BDADDR_BREDR, ev_cc->handle); + const BDAddressAndType addressAndType(ev_cc->bdaddr, BDAddressType::BDADDR_BREDR); + HCIConnectionRef conn = addOrUpdateTrackerConnection(addressAndType, ev_cc->handle); if( HCIStatusCode::SUCCESS == status ) { - return std::shared_ptr<MgmtEvent>( new MgmtEvtDeviceConnected(dev_id, conn->getAddress(), conn->getAddressType(), conn->getHandle()) ); + return std::shared_ptr<MgmtEvent>( new MgmtEvtDeviceConnected(dev_id, conn->getAddressAndType(), conn->getHandle()) ); } else { - std::shared_ptr<MgmtEvent> res( new MgmtEvtDeviceConnectFailed(dev_id, conn->getAddress(), conn->getAddressType(), status) ); + std::shared_ptr<MgmtEvent> res( new MgmtEvtDeviceConnectFailed(dev_id, conn->getAddressAndType(),status) ); removeTrackerConnection(conn); return res; } @@ -284,7 +285,7 @@ std::shared_ptr<MgmtEvent> HCIHandler::translate(std::shared_ptr<HCIEvent> ev) n conn->toString().c_str(), ev->toString().c_str(), toString().c_str()); } const HCIStatusCode hciRootReason = static_cast<HCIStatusCode>(ev_cc->reason); - return std::shared_ptr<MgmtEvent>( new MgmtEvtDeviceDisconnected(dev_id, conn->getAddress(), conn->getAddressType(), hciRootReason, conn->getHandle()) ); + return std::shared_ptr<MgmtEvent>( new MgmtEvtDeviceDisconnected(dev_id, conn->getAddressAndType(), hciRootReason, conn->getHandle()) ); } } case HCIEventType::ENCRYPT_CHANGE: { @@ -302,7 +303,7 @@ std::shared_ptr<MgmtEvent> HCIHandler::translate(std::shared_ptr<HCIEvent> ev) n jau::uint16HexString(handle), conn->toString().c_str()); return nullptr; } - return std::shared_ptr<MgmtEvent>( new MgmtEvtHCIEncryptionChanged(dev_id, conn->getAddress(), conn->getAddressType(), status, ev_cc->encrypt) ); + return std::shared_ptr<MgmtEvent>( new MgmtEvtHCIEncryptionChanged(dev_id, conn->getAddressAndType(), status, ev_cc->encrypt) ); } case HCIEventType::ENCRYPT_KEY_REFRESH_COMPLETE: { HCIStatusCode status; @@ -319,7 +320,7 @@ std::shared_ptr<MgmtEvent> HCIHandler::translate(std::shared_ptr<HCIEvent> ev) n jau::uint16HexString(handle), conn->toString().c_str()); return nullptr; } - return std::shared_ptr<MgmtEvent>( new MgmtEvtHCIEncryptionKeyRefreshComplete(dev_id, conn->getAddress(), conn->getAddressType(), status) ); + return std::shared_ptr<MgmtEvent>( new MgmtEvtHCIEncryptionKeyRefreshComplete(dev_id, conn->getAddressAndType(), status) ); } // TODO: AUTH_COMPLETE // 7.7.6 AUTH_COMPLETE 0x06 @@ -373,7 +374,7 @@ void HCIHandler::hciReaderThreadImpl() noexcept { COND_PRINT(env.DEBUG_EVENT, "HCIHandler-IO RECV (ACL.SMP) %s for %s", smpPDU->toString().c_str(), conn->toString().c_str()); jau::for_each_cow(hciSMPMsgCallbackList, [&](HCISMPMsgCallback &cb) { - cb.invoke(conn->getAddress(), conn->getAddressType(), smpPDU, l2cap); + cb.invoke(conn->getAddressAndType(), smpPDU, l2cap); }); } else { WARN_PRINT("HCIHandler-IO RECV Drop (ACL.SMP): Not tracked conn_handle %s: %s", @@ -968,7 +969,7 @@ HCIStatusCode HCIHandler::le_create_conn(const EUI48 &peer_bdaddr, cp->supervision_timeout = jau::cpu_to_le(supervision_timeout); cp->min_ce_len = jau::cpu_to_le(min_ce_length); cp->max_ce_len = jau::cpu_to_le(max_ce_length); - BDAddressType bdAddrType = getBDAddressType(peer_mac_type); + const BDAddressAndType addressAndType(peer_bdaddr, getBDAddressType(peer_mac_type)); int pendingConnections = countPendingTrackerConnections(); if( 0 < pendingConnections ) { @@ -985,7 +986,7 @@ HCIStatusCode HCIHandler::le_create_conn(const EUI48 &peer_bdaddr, DBG_PRINT("HCIHandler::le_create_conn: pending connections resolved after %d ms - %s", td, toString().c_str()); } } - HCIConnectionRef disconn = findDisconnectCmd(peer_bdaddr, bdAddrType); + HCIConnectionRef disconn = findDisconnectCmd(addressAndType); if( nullptr != disconn ) { DBG_PRINT("HCIHandler::le_create_conn: disconnect pending %s - %s", disconn->toString().c_str(), toString().c_str()); @@ -993,7 +994,7 @@ HCIStatusCode HCIHandler::le_create_conn(const EUI48 &peer_bdaddr, while( env.HCI_COMMAND_COMPLETE_REPLY_TIMEOUT > td && nullptr != disconn ) { std::this_thread::sleep_for(std::chrono::milliseconds(env.HCI_COMMAND_POLL_PERIOD)); td += env.HCI_COMMAND_POLL_PERIOD; - disconn = findDisconnectCmd(peer_bdaddr, bdAddrType); + disconn = findDisconnectCmd(addressAndType); } if( nullptr != disconn ) { WARN_PRINT("HCIHandler::le_create_conn: disconnect persisting after %d ms: %s - %s", @@ -1002,7 +1003,7 @@ HCIStatusCode HCIHandler::le_create_conn(const EUI48 &peer_bdaddr, DBG_PRINT("HCIHandler::le_create_conn: disconnect resolved after %d ms - %s", td, toString().c_str()); } } - HCIConnectionRef conn = addOrUpdateTrackerConnection(peer_bdaddr, bdAddrType, 0); + HCIConnectionRef conn = addOrUpdateTrackerConnection(addressAndType, 0); HCIStatusCode status; std::shared_ptr<HCIEvent> ev = processCommandStatus(req0, &status); if( HCIStatusCode::SUCCESS != status ) { @@ -1056,7 +1057,8 @@ HCIStatusCode HCIHandler::create_conn(const EUI48 &bdaddr, DBG_PRINT("HCIHandler::create_conn: pending connections resolved after %d ms - %s", td, toString().c_str()); } } - HCIConnectionRef disconn = findDisconnectCmd(bdaddr, BDAddressType::BDADDR_BREDR); + const BDAddressAndType addressAndType(bdaddr, BDAddressType::BDADDR_BREDR); + HCIConnectionRef disconn = findDisconnectCmd(addressAndType); if( nullptr != disconn ) { DBG_PRINT("HCIHandler::create_conn: disconnect pending %s - %s", disconn->toString().c_str(), toString().c_str()); @@ -1064,7 +1066,7 @@ HCIStatusCode HCIHandler::create_conn(const EUI48 &bdaddr, while( env.HCI_COMMAND_COMPLETE_REPLY_TIMEOUT > td && nullptr != disconn ) { std::this_thread::sleep_for(std::chrono::milliseconds(env.HCI_COMMAND_POLL_PERIOD)); td += env.HCI_COMMAND_POLL_PERIOD; - disconn = findDisconnectCmd(bdaddr, BDAddressType::BDADDR_BREDR); + disconn = findDisconnectCmd(addressAndType); } if( nullptr != disconn ) { WARN_PRINT("HCIHandler::create_conn: disconnect persisting after %d ms: %s - %s", @@ -1073,7 +1075,7 @@ HCIStatusCode HCIHandler::create_conn(const EUI48 &bdaddr, DBG_PRINT("HCIHandler::create_conn: disconnect resolved after %d ms - %s", td, toString().c_str()); } } - HCIConnectionRef conn = addOrUpdateTrackerConnection(bdaddr, BDAddressType::BDADDR_BREDR, 0); + HCIConnectionRef conn = addOrUpdateTrackerConnection(addressAndType, 0); HCIStatusCode status; std::shared_ptr<HCIEvent> ev = processCommandStatus(req0, &status); if( HCIStatusCode::SUCCESS != status ) { @@ -1088,7 +1090,7 @@ HCIStatusCode HCIHandler::create_conn(const EUI48 &bdaddr, return status; } -HCIStatusCode HCIHandler::disconnect(const uint16_t conn_handle, const EUI48 &peer_bdaddr, const BDAddressType peer_mac_type, +HCIStatusCode HCIHandler::disconnect(const uint16_t conn_handle, const BDAddressAndType& peerAddressAndType, const HCIStatusCode reason) noexcept { if( !isOpen() ) { @@ -1096,8 +1098,8 @@ HCIStatusCode HCIHandler::disconnect(const uint16_t conn_handle, const EUI48 &pe return HCIStatusCode::INTERNAL_FAILURE; } if( 0 == conn_handle ) { - ERR_PRINT("HCIHandler::disconnect: Null conn_handle given address[%s, %s] (drop) - %s", - peer_bdaddr.toString().c_str(), getBDAddressTypeString(peer_mac_type).c_str(), toString().c_str()); + ERR_PRINT("HCIHandler::disconnect: Null conn_handle given address%s (drop) - %s", + peerAddressAndType.toString().c_str(), toString().c_str()); return HCIStatusCode::INVALID_HCI_COMMAND_PARAMETERS; } { @@ -1105,18 +1107,18 @@ HCIStatusCode HCIHandler::disconnect(const uint16_t conn_handle, const EUI48 &pe HCIConnectionRef conn = findTrackerConnection(conn_handle); if( nullptr == conn ) { // disconnect called w/o being connected through this HCIHandler - conn = addOrUpdateTrackerConnection(peer_bdaddr, peer_mac_type, conn_handle); - WORDY_PRINT("HCIHandler::disconnect: Not tracked address[%s, %s], added %s - %s", - peer_bdaddr.toString().c_str(), getBDAddressTypeString(peer_mac_type).c_str(), + conn = addOrUpdateTrackerConnection(peerAddressAndType, conn_handle); + WORDY_PRINT("HCIHandler::disconnect: Not tracked address%s, added %s - %s", + peerAddressAndType.toString().c_str(), conn->toString().c_str(), toString().c_str()); - } else if( !conn->equals(peer_bdaddr, peer_mac_type) ) { - ERR_PRINT("HCIHandler::disconnect: Mismatch given address[%s, %s] and tracked %s (drop) - %s", - peer_bdaddr.toString().c_str(), getBDAddressTypeString(peer_mac_type).c_str(), + } else if( !conn->equals(peerAddressAndType) ) { + ERR_PRINT("HCIHandler::disconnect: Mismatch given address%s and tracked %s (drop) - %s", + peerAddressAndType.toString().c_str(), conn->toString().c_str(), toString().c_str()); return HCIStatusCode::INVALID_HCI_COMMAND_PARAMETERS; } - DBG_PRINT("HCIHandler::disconnect: address[%s, %s], handle %s, %s - %s", - peer_bdaddr.toString().c_str(), getBDAddressTypeString(peer_mac_type).c_str(), + DBG_PRINT("HCIHandler::disconnect: address%s, handle %s, %s - %s", + peerAddressAndType.toString().c_str(), jau::uint16HexString(conn_handle).c_str(), conn->toString().c_str(), toString().c_str()); } @@ -1135,7 +1137,7 @@ HCIStatusCode HCIHandler::disconnect(const uint16_t conn_handle, const EUI48 &pe std::shared_ptr<HCIEvent> ev = processCommandStatus(req0, &status); } if( HCIStatusCode::SUCCESS == status ) { - addOrUpdateDisconnectCmd(peer_bdaddr, peer_mac_type, conn_handle); + addOrUpdateDisconnectCmd(peerAddressAndType, conn_handle); } return status; } diff --git a/src/direct_bt/L2CAPComm.cpp b/src/direct_bt/L2CAPComm.cpp index 4248b15f..08e08fe6 100644 --- a/src/direct_bt/L2CAPComm.cpp +++ b/src/direct_bt/L2CAPComm.cpp @@ -109,9 +109,7 @@ L2CAPComm::L2CAPComm(const EUI48& adapterAddress_, const uint16_t psm_, const ui : env(L2CAPEnv::get()), adapterAddress(adapterAddress_), psm(psm_), cid(cid_), - deviceString("undefined"), - deviceAddress(EUI48_ANY_DEVICE), - deviceAddressType(BDAddressType::BDADDR_UNDEFINED), + deviceAddressAndType(BDAddressAndType::ANY_BREDR_DEVICE), socket_descriptor(-1), is_open(false), has_ioerror(false), interrupt_flag(false), tid_connect(0), tid_read(0) { } @@ -133,7 +131,7 @@ bool L2CAPComm::open(const DBTDevice& device, const BTSecurityLevel sec_level) { bool expOpen = false; // C++11, exp as value since C++20 if( !is_open.compare_exchange_strong(expOpen, true) ) { DBG_PRINT("L2CAPComm::open: Already open: %s, dd %d, %s, psm %u, cid %u", - getStateString().c_str(), socket_descriptor.load(), deviceString.c_str(), psm, cid); + getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(), psm, cid); return false; } const std::lock_guard<std::recursive_mutex> lock(mtx_write); // RAII-style acquire and relinquish via destructor @@ -153,9 +151,7 @@ bool L2CAPComm::open(const DBTDevice& device, const BTSecurityLevel sec_level) { * - l2cap_connect with destination address * -- connect(fd, ..) */ - deviceString = device.getAddressString(); - deviceAddress = device.getAddress(); - deviceAddressType = device.getAddressType(); + deviceAddressAndType = device.getAddressAndType(); /** BT Core Spec v5.2: Vol 3, Part A: L2CAP_CONNECTION_REQ */ sockaddr_l2 req; @@ -163,7 +159,7 @@ bool L2CAPComm::open(const DBTDevice& device, const BTSecurityLevel sec_level) { int to_retry_count=0; // ETIMEDOUT retry count DBG_PRINT("L2CAPComm::open: Start Connect: %s, dd %d, %s, psm %u, cid %u", - getStateString().c_str(), socket_descriptor.load(), deviceString.c_str(), psm, cid); + getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(), psm, cid); socket_descriptor = l2cap_open_dev(adapterAddress, psm, cid, BDAddressType::BDADDR_LE_PUBLIC); @@ -187,15 +183,15 @@ bool L2CAPComm::open(const DBTDevice& device, const BTSecurityLevel sec_level) { bzero((void *)&req, sizeof(req)); req.l2_family = AF_BLUETOOTH; req.l2_psm = jau::cpu_to_le(psm); - req.l2_bdaddr = deviceAddress; + req.l2_bdaddr = deviceAddressAndType.address; req.l2_cid = jau::cpu_to_le(cid); - req.l2_bdaddr_type = ::number(deviceAddressType); + req.l2_bdaddr_type = ::number(deviceAddressAndType.type); while( !interrupt_flag ) { // blocking res = ::connect(socket_descriptor, (struct sockaddr*)&req, sizeof(req)); - DBG_PRINT("L2CAPComm::open: Connect Result %d, errno 0%X %s, %s", res, errno, strerror(errno), deviceString.c_str()); + DBG_PRINT("L2CAPComm::open: Connect Result %d, errno 0%X %s, %s", res, errno, strerror(errno), deviceAddressAndType.toString().c_str()); if( !res ) { @@ -243,14 +239,14 @@ bool L2CAPComm::close() noexcept { bool expOpen = true; // C++11, exp as value since C++20 if( !is_open.compare_exchange_strong(expOpen, false) ) { DBG_PRINT("L2CAPComm::close: Not connected: %s, dd %d, %s, psm %u, cid %u", - getStateString().c_str(), socket_descriptor.load(), deviceString.c_str(), psm, cid); + getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(), psm, cid); return true; } const std::lock_guard<std::recursive_mutex> lock(mtx_write); // RAII-style acquire and relinquish via destructor has_ioerror = false; DBG_PRINT("L2CAPComm::close: Start: %s, dd %d, %s, psm %u, cid %u", - getStateString().c_str(), socket_descriptor.load(), deviceString.c_str(), psm, cid); + getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(), psm, cid); PERF_TS_T0(); interrupt_flag = true; @@ -289,7 +285,7 @@ bool L2CAPComm::close() noexcept { bool L2CAPComm::setBTSecurityLevel(const BTSecurityLevel sec_level) { if( !is_open ) { DBG_PRINT("L2CAPComm::setBTSecurityLevel: Not connected: %s, dd %d, %s, psm %u, cid %u", - getStateString().c_str(), socket_descriptor.load(), deviceString.c_str(), psm, cid); + getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(), psm, cid); return false; } const std::lock_guard<std::recursive_mutex> lock(mtx_write); // RAII-style acquire and relinquish via destructor @@ -335,7 +331,7 @@ bool L2CAPComm::setBTSecurityLevelImpl(const BTSecurityLevel sec_level) { BTSecurityLevel L2CAPComm::getBTSecurityLevel() { if( !is_open ) { DBG_PRINT("L2CAPComm::getBTSecurityLevel: Not connected: %s, dd %d, %s, psm %u, cid %u", - getStateString().c_str(), socket_descriptor.load(), deviceString.c_str(), psm, cid); + getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(), psm, cid); return BTSecurityLevel::UNSET; } const std::lock_guard<std::recursive_mutex> lock(mtx_write); // RAII-style acquire and relinquish via destructor @@ -424,10 +420,10 @@ errout: if( is_open ) { if( env.L2CAP_RESTART_COUNT_ON_ERROR < 0 ) { ABORT("L2CAPComm::read: Error res %d; %s, dd %d, %s, psm %u, cid %u", - err_res, getStateString().c_str(), socket_descriptor.load(), deviceString.c_str(), psm, cid); + err_res, getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(), psm, cid); } else { IRQ_PRINT("L2CAPComm::read: Error res %d; %s, dd %d, %s, psm %u, cid %u", - err_res, getStateString().c_str(), socket_descriptor.load(), deviceString.c_str(), psm, cid); + err_res, getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(), psm, cid); } } } @@ -463,10 +459,10 @@ errout: if( is_open ) { if( env.L2CAP_RESTART_COUNT_ON_ERROR < 0 ) { ABORT("L2CAPComm::write: Error res %d; %s, dd %d, %s, psm %u, cid %u", - err_res, getStateString().c_str(), socket_descriptor.load(), deviceString.c_str(), psm, cid); + err_res, getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(), psm, cid); } else { IRQ_PRINT("L2CAPComm::write: Error res %d; %s, dd %d, %s, psm %u, cid %u", - err_res, getStateString().c_str(), socket_descriptor.load(), deviceString.c_str(), psm, cid); + err_res, getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(), psm, cid); } } return err_res; diff --git a/src/direct_bt/SMPHandler.cpp b/src/direct_bt/SMPHandler.cpp index 352f53b0..51effa7c 100644 --- a/src/direct_bt/SMPHandler.cpp +++ b/src/direct_bt/SMPHandler.cpp @@ -157,7 +157,7 @@ void SMPHandler::l2capReaderThreadImpl() { SMPHandler::SMPHandler(const std::shared_ptr<DBTDevice> &device) noexcept : env(SMPEnv::get()), - wbr_device(device), deviceString(device->getAddressString()), rbuffer(number(Defaults::SMP_MTU_BUFFER_SZ)), + wbr_device(device), deviceString(device->getAddressAndType().toString()), rbuffer(number(Defaults::SMP_MTU_BUFFER_SZ)), l2cap(device->getAdapter().getAddress(), L2CAP_PSM_UNDEF, L2CAP_CID_SMP), is_connected(l2cap.open(*device)), has_ioerror(false), smpPDURing(env.SMPPDU_RING_CAPACITY), l2capReaderShallStop(false), |