diff --git a/src/connectivity/bluetooth/core/bt-host/fidl/helpers.cc b/src/connectivity/bluetooth/core/bt-host/fidl/helpers.cc index 910dc444929e0fee5e4ce928a1c3cacf9fb559a8..a74630b544d1ad686a51d0590b6cb01a7dcfbeb0 100644 --- a/src/connectivity/bluetooth/core/bt-host/fidl/helpers.cc +++ b/src/connectivity/bluetooth/core/bt-host/fidl/helpers.cc @@ -4,10 +4,10 @@ #include "helpers.h" -#include <unordered_set> - #include <endian.h> +#include <unordered_set> + #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/connectivity/bluetooth/core/bt-host/common/uuid.h" #include "src/connectivity/bluetooth/core/bt-host/gap/advertising_data.h" @@ -99,9 +99,8 @@ fhost::AddressType BondingAddrTypeToFidl(bt::common::DeviceAddress::Type type) { } bt::sm::LTK LtkFromFidl(const fhost::LTK& ltk) { - return bt::sm::LTK( - SecurityPropsFromFidl(ltk.key.security_properties), - bt::hci::LinkKey(ltk.key.value, ltk.rand, ltk.ediv)); + return bt::sm::LTK(SecurityPropsFromFidl(ltk.key.security_properties), + bt::hci::LinkKey(ltk.key.value, ltk.rand, ltk.ediv)); } fhost::LTK LtkToFidl(const bt::sm::LTK& ltk) { @@ -118,8 +117,7 @@ fhost::LTK LtkToFidl(const bt::sm::LTK& ltk) { } bt::sm::Key KeyFromFidl(const fhost::RemoteKey& key) { - return bt::sm::Key(SecurityPropsFromFidl(key.security_properties), - key.value); + return bt::sm::Key(SecurityPropsFromFidl(key.security_properties), key.value); } fhost::RemoteKey KeyToFidl(const bt::sm::Key& key) { @@ -239,13 +237,13 @@ fctrl::AdapterInfo NewAdapterInfo(const bt::gap::Adapter& adapter) { return adapter_info; } -fctrl::RemoteDevice NewRemoteDevice(const bt::gap::RemoteDevice& device) { +fctrl::RemoteDevice NewRemoteDevice(const bt::gap::Peer& peer) { fctrl::RemoteDevice fidl_device; - fidl_device.identifier = device.identifier().ToString(); - fidl_device.address = device.address().value().ToString(); - fidl_device.technology = TechnologyTypeToFidl(device.technology()); - fidl_device.connected = device.connected(); - fidl_device.bonded = device.bonded(); + fidl_device.identifier = peer.identifier().ToString(); + fidl_device.address = peer.address().value().ToString(); + fidl_device.technology = TechnologyTypeToFidl(peer.technology()); + fidl_device.connected = peer.connected(); + fidl_device.bonded = peer.bonded(); // Set default value for device appearance. fidl_device.appearance = fctrl::Appearance::UNKNOWN; @@ -254,19 +252,19 @@ fctrl::RemoteDevice NewRemoteDevice(const bt::gap::RemoteDevice& device) { // to it. fidl_device.service_uuids.resize(0); - if (device.rssi() != bt::hci::kRSSIInvalid) { + if (peer.rssi() != bt::hci::kRSSIInvalid) { fidl_device.rssi = Int8::New(); - fidl_device.rssi->value = device.rssi(); + fidl_device.rssi->value = peer.rssi(); } - if (device.name()) { - fidl_device.name = *device.name(); + if (peer.name()) { + fidl_device.name = *peer.name(); } - if (device.le()) { + if (peer.le()) { bt::gap::AdvertisingData adv_data; - if (!bt::gap::AdvertisingData::FromBytes(device.le()->advertising_data(), + if (!bt::gap::AdvertisingData::FromBytes(peer.le()->advertising_data(), &adv_data)) { return fidl_device; } @@ -288,29 +286,29 @@ fctrl::RemoteDevice NewRemoteDevice(const bt::gap::RemoteDevice& device) { return fidl_device; } -fctrl::RemoteDevicePtr NewRemoteDevicePtr(const bt::gap::RemoteDevice& device) { +fctrl::RemoteDevicePtr NewRemoteDevicePtr(const bt::gap::Peer& peer) { auto fidl_device = fctrl::RemoteDevice::New(); - *fidl_device = NewRemoteDevice(device); + *fidl_device = NewRemoteDevice(peer); return fidl_device; } fhost::BondingData NewBondingData(const bt::gap::Adapter& adapter, - const bt::gap::RemoteDevice& device) { + const bt::gap::Peer& peer) { fhost::BondingData out_data; - out_data.identifier = device.identifier().ToString(); + out_data.identifier = peer.identifier().ToString(); out_data.local_address = adapter.state().controller_address().ToString(); - if (device.name()) { - out_data.name = *device.name(); + if (peer.name()) { + out_data.name = *peer.name(); } // Store LE data. - if (device.le() && device.le()->bond_data()) { + if (peer.le() && peer.le()->bond_data()) { out_data.le = fhost::LEData::New(); - const auto& le_data = *device.le()->bond_data(); + const auto& le_data = *peer.le()->bond_data(); const auto& identity = - le_data.identity_address ? *le_data.identity_address : device.address(); + le_data.identity_address ? *le_data.identity_address : peer.address(); out_data.le->address = identity.value().ToString(); out_data.le->address_type = BondingAddrTypeToFidl(identity.type()); @@ -335,10 +333,10 @@ fhost::BondingData NewBondingData(const bt::gap::Adapter& adapter, } // Store BR/EDR data. - if (device.bredr() && device.bredr()->link_key()) { + if (peer.bredr() && peer.bredr()->link_key()) { out_data.bredr = fhost::BREDRData::New(); - out_data.bredr->address = device.bredr()->address().value().ToString(); + out_data.bredr->address = peer.bredr()->address().value().ToString(); // TODO(BT-669): Populate with history of role switches. out_data.bredr->piconet_leader = false; @@ -346,25 +344,25 @@ fhost::BondingData NewBondingData(const bt::gap::Adapter& adapter, // TODO(BT-670): Populate with discovered SDP services. out_data.bredr->services.resize(0); - if (device.bredr()->link_key()) { + if (peer.bredr()->link_key()) { out_data.bredr->link_key = fhost::LTK::New(); - *out_data.bredr->link_key = LtkToFidl(*device.bredr()->link_key()); + *out_data.bredr->link_key = LtkToFidl(*peer.bredr()->link_key()); } } return out_data; } -fble::RemoteDevicePtr NewLERemoteDevice(const bt::gap::RemoteDevice& device) { +fble::RemoteDevicePtr NewLERemoteDevice(const bt::gap::Peer& peer) { bt::gap::AdvertisingData ad; - if (!device.le()) { + if (!peer.le()) { return nullptr; } - const auto& le = *device.le(); + const auto& le = *peer.le(); auto fidl_device = fble::RemoteDevice::New(); - fidl_device->identifier = device.identifier().ToString(); - fidl_device->connectable = device.connectable(); + fidl_device->identifier = peer.identifier().ToString(); + fidl_device->connectable = peer.connectable(); // Initialize advertising data only if its non-empty. if (le.advertising_data().size() != 0u) { @@ -375,9 +373,9 @@ fble::RemoteDevicePtr NewLERemoteDevice(const bt::gap::RemoteDevice& device) { fidl_device->advertising_data = ad.AsLEAdvertisingData(); } - if (device.rssi() != bt::hci::kRSSIInvalid) { + if (peer.rssi() != bt::hci::kRSSIInvalid) { fidl_device->rssi = Int8::New(); - fidl_device->rssi->value = device.rssi(); + fidl_device->rssi->value = peer.rssi(); } return fidl_device; diff --git a/src/connectivity/bluetooth/core/bt-host/fidl/helpers.h b/src/connectivity/bluetooth/core/bt-host/fidl/helpers.h index 25e1b808348349da13e244ae1c6a44d3e545c250..27a1f327ea3ddc5911d6210970d60c7f1252e290 100644 --- a/src/connectivity/bluetooth/core/bt-host/fidl/helpers.h +++ b/src/connectivity/bluetooth/core/bt-host/fidl/helpers.h @@ -5,22 +5,21 @@ #ifndef SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_FIDL_HELPERS_H_ #define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_FIDL_HELPERS_H_ -#include <optional> - #include <fuchsia/bluetooth/control/cpp/fidl.h> #include <fuchsia/bluetooth/cpp/fidl.h> #include <fuchsia/bluetooth/gatt/cpp/fidl.h> #include <fuchsia/bluetooth/host/cpp/fidl.h> #include <fuchsia/bluetooth/le/cpp/fidl.h> +#include <optional> + #include "lib/fidl/cpp/type_converter.h" #include "lib/fidl/cpp/vector.h" - #include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" #include "src/connectivity/bluetooth/core/bt-host/common/identifier.h" #include "src/connectivity/bluetooth/core/bt-host/common/status.h" #include "src/connectivity/bluetooth/core/bt-host/gap/adapter.h" -#include "src/connectivity/bluetooth/core/bt-host/gap/remote_device.h" +#include "src/connectivity/bluetooth/core/bt-host/gap/peer.h" // Helpers for implementing the Bluetooth FIDL interfaces. @@ -75,9 +74,9 @@ bt::sm::IOCapability IoCapabilityFromFidl( fuchsia::bluetooth::control::AdapterInfo NewAdapterInfo( const bt::gap::Adapter& adapter); fuchsia::bluetooth::control::RemoteDevice NewRemoteDevice( - const bt::gap::RemoteDevice& device); + const bt::gap::Peer& peer); fuchsia::bluetooth::control::RemoteDevicePtr NewRemoteDevicePtr( - const bt::gap::RemoteDevice& device); + const bt::gap::Peer& peer); // Functions to convert Host FIDL library objects. bt::sm::PairingData PairingDataFromFidl( @@ -87,13 +86,13 @@ bt::common::UInt128 LocalKeyFromFidl( std::optional<bt::sm::LTK> BrEdrKeyFromFidl( const fuchsia::bluetooth::host::BREDRData& data); fuchsia::bluetooth::host::BondingData NewBondingData( - const bt::gap::Adapter& adapter, const bt::gap::RemoteDevice& device); + const bt::gap::Adapter& adapter, const bt::gap::Peer& peer); // Functions to construct FIDL LE library objects from library objects. fuchsia::bluetooth::le::AdvertisingDataPtr NewAdvertisingData( const bt::common::ByteBuffer& advertising_data); fuchsia::bluetooth::le::RemoteDevicePtr NewLERemoteDevice( - const bt::gap::RemoteDevice& device); + const bt::gap::Peer& peer); // Validates the contents of a ScanFilter. bool IsScanFilterValid(const fuchsia::bluetooth::le::ScanFilter& fidl_filter); diff --git a/src/connectivity/bluetooth/core/bt-host/fidl/host_server.cc b/src/connectivity/bluetooth/core/bt-host/fidl/host_server.cc index 37b4c845ce6c2346753fb15c6a4b7ac0a0ccfd9a..4cdd5b028ed80ce9377397fbd7091bceaedf4c3e 100644 --- a/src/connectivity/bluetooth/core/bt-host/fidl/host_server.cc +++ b/src/connectivity/bluetooth/core/bt-host/fidl/host_server.cc @@ -51,24 +51,22 @@ HostServer::HostServer(zx::channel channel, ZX_DEBUG_ASSERT(gatt_host_); auto self = weak_ptr_factory_.GetWeakPtr(); - adapter->remote_device_cache()->set_device_updated_callback( - [self](const auto& device) { - if (self) { - self->OnRemoteDeviceUpdated(device); - } - }); - adapter->remote_device_cache()->set_device_removed_callback( + adapter->peer_cache()->set_peer_updated_callback([self](const auto& peer) { + if (self) { + self->OnPeerUpdated(peer); + } + }); + adapter->peer_cache()->set_peer_removed_callback( [self](const auto& identifier) { if (self) { - self->OnRemoteDeviceRemoved(identifier); - } - }); - adapter->remote_device_cache()->set_device_bonded_callback( - [self](const auto& device) { - if (self) { - self->OnRemoteDeviceBonded(device); + self->OnPeerRemoved(identifier); } }); + adapter->peer_cache()->set_peer_bonded_callback([self](const auto& peer) { + if (self) { + self->OnPeerBonded(peer); + } + }); adapter->set_auto_connect_callback([self](auto conn_ref) { if (self) { self->RegisterLowEnergyConnection(std::move(conn_ref), true); @@ -94,12 +92,11 @@ void HostServer::SetLocalData(::fuchsia::bluetooth::host::HostData host_data) { void HostServer::ListDevices(ListDevicesCallback callback) { std::vector<RemoteDevice> fidl_devices; - adapter()->remote_device_cache()->ForEach( - [&fidl_devices](const bt::gap::RemoteDevice& dev) { - if (dev.connectable()) { - fidl_devices.push_back(fidl_helpers::NewRemoteDevice(dev)); - } - }); + adapter()->peer_cache()->ForEach([&fidl_devices](const bt::gap::Peer& p) { + if (p.connectable()) { + fidl_devices.push_back(fidl_helpers::NewRemoteDevice(p)); + } + }); callback(std::vector<RemoteDevice>(std::move(fidl_devices))); } @@ -171,7 +168,7 @@ void HostServer::StartLEDiscovery(StartDiscoveryCallback callback) { // Set up a general-discovery filter for connectable devices. // NOTE(armansito): This currently has no effect since OnDeviceUpdated - // events are generated based on RemoteDeviceCache events. |session|'s + // events are generated based on PeerCache events. |session|'s // "result callback" is unused. session->filter()->set_connectable(true); session->filter()->SetGeneralDiscoveryFlags(); @@ -281,8 +278,8 @@ void HostServer::AddBondedDevices(::std::vector<BondingData> bonds, std::vector<std::string> failed_ids; for (auto& bond : bonds) { - auto device_id = DeviceIdFromString(bond.identifier); - if (!device_id) { + auto peer_id = DeviceIdFromString(bond.identifier); + if (!peer_id) { failed_ids.push_back(bond.identifier); continue; } @@ -307,7 +304,7 @@ void HostServer::AddBondedDevices(::std::vector<BondingData> bonds, std::optional<bt::sm::LTK> bredr_link_key; if (bond.bredr) { - // Dual-mode devices will have a BR/EDR-typed address. + // Dual-mode peers will have a BR/EDR-typed address. address = bt::common::DeviceAddress( bt::common::DeviceAddress::Type::kBREDR, bond.bredr->address); bredr_link_key = fidl_helpers::BrEdrKeyFromFidl(*bond.bredr); @@ -323,8 +320,8 @@ void HostServer::AddBondedDevices(::std::vector<BondingData> bonds, // TODO(armansito): BondingData should contain the identity address for both // transports instead of storing them separately. For now use the one we // obtained from |bond.le|. - if (!adapter()->AddBondedDevice(*device_id, address, le_bond_data, - bredr_link_key)) { + if (!adapter()->AddBondedPeer(*peer_id, address, le_bond_data, + bredr_link_key)) { failed_ids.push_back(bond.identifier); continue; } @@ -333,32 +330,31 @@ void HostServer::AddBondedDevices(::std::vector<BondingData> bonds, if (!failed_ids.empty()) { callback(fidl_helpers::NewFidlError( ErrorCode::FAILED, - fxl::StringPrintf("Some devices failed to load (ids: %s)", + fxl::StringPrintf("Some peers failed to load (ids: %s)", fxl::JoinStrings(failed_ids, ", ").c_str()))); } else { callback(Status()); } } -void HostServer::OnRemoteDeviceBonded( - const bt::gap::RemoteDevice& remote_device) { - bt_log(TRACE, "bt-host", "OnRemoteDeviceBonded()"); +void HostServer::OnPeerBonded(const bt::gap::Peer& peer) { + bt_log(TRACE, "bt-host", "OnPeerBonded()"); binding()->events().OnNewBondingData( - fidl_helpers::NewBondingData(*adapter(), remote_device)); + fidl_helpers::NewBondingData(*adapter(), peer)); } void HostServer::RegisterLowEnergyConnection( bt::gap::LowEnergyConnectionRefPtr conn_ref, bool auto_connect) { ZX_DEBUG_ASSERT(conn_ref); - bt::gap::DeviceId id = conn_ref->device_identifier(); + bt::gap::DeviceId id = conn_ref->peer_identifier(); auto iter = le_connections_.find(id); if (iter != le_connections_.end()) { - bt_log(WARN, "bt-host", "device already connected; reference dropped"); + bt_log(WARN, "bt-host", "peer already connected; reference dropped"); return; } - bt_log(TRACE, "bt-host", "LE device connected (%s): %s ", + bt_log(TRACE, "bt-host", "LE peer connected (%s): %s ", (auto_connect ? "auto" : "direct"), bt_str(id)); conn_ref->set_closed_callback([self = weak_ptr_factory_.GetWeakPtr(), id] { if (self) @@ -471,27 +467,27 @@ void HostServer::SetPairingDelegate( }); } -// Attempt to connect to device identified by |device_id|. The device must be -// in our device cache. We will attempt to connect technologies (LowEnergy, -// Classic or Dual-Mode) as the device claims to support when discovered -void HostServer::Connect(::std::string device_id, ConnectCallback callback) { - auto id = DeviceIdFromString(device_id); +// Attempt to connect to peer identified by |peer_id|. The peer must be +// in our peer cache. We will attempt to connect technologies (LowEnergy, +// Classic or Dual-Mode) as the peer claims to support when discovered +void HostServer::Connect(::std::string peer_id, ConnectCallback callback) { + auto id = DeviceIdFromString(peer_id); if (!id.has_value()) { - callback(NewFidlError(ErrorCode::INVALID_ARGUMENTS, "invalid device ID")); + callback(NewFidlError(ErrorCode::INVALID_ARGUMENTS, "invalid peer ID")); return; } - auto device = adapter()->remote_device_cache()->FindDeviceById(*id); - if (!device) { - // We don't support connecting to devices that are not in our cache + auto peer = adapter()->peer_cache()->FindById(*id); + if (!peer) { + // We don't support connecting to peers that are not in our cache callback(NewFidlError(ErrorCode::NOT_FOUND, - "Cannot find device with the given ID")); + "Cannot find peer with the given ID")); return; } - // TODO(BT-649): Dual-mode currently not supported; if the device supports - // LowEnergy we assume LE. If a dual-mode device, we should attempt to connect + // TODO(BT-649): Dual-mode currently not supported; if the peer supports + // LowEnergy we assume LE. If a dual-mode peer, we should attempt to connect // both protocols. - if (!device->le()) { + if (!peer->le()) { ConnectBrEdr(*id, std::move(callback)); return; } @@ -505,15 +501,15 @@ void HostServer::ConnectLowEnergy(DeviceId peer_id, ConnectCallback callback) { auto status, auto connection) { if (!status) { ZX_ASSERT(!connection); - bt_log(TRACE, "bt-host", "failed to connect to connect to device (id %s)", + bt_log(TRACE, "bt-host", "failed to connect to connect to peer (id %s)", bt_str(peer_id)); callback(StatusToFidl(status, "failed to connect")); return; } - // We must be connected and to the right device + // We must be connected and to the right peer ZX_ASSERT(connection); - ZX_ASSERT(peer_id == connection->device_identifier()); + ZX_ASSERT(peer_id == connection->peer_identifier()); callback(Status()); @@ -533,13 +529,13 @@ void HostServer::ConnectBrEdr(DeviceId peer_id, ConnectCallback callback) { auto status, auto connection) { if (!status) { ZX_ASSERT(!connection); - bt_log(TRACE, "bt-host", "failed to connect to connect to device (id %s)", + bt_log(TRACE, "bt-host", "failed to connect to connect to peer (id %s)", bt_str(peer_id)); callback(StatusToFidl(status, "failed to connect")); return; } - // We must be connected and to the right device + // We must be connected and to the right peer ZX_ASSERT(connection); ZX_ASSERT(peer_id == connection->peer_id()); @@ -552,13 +548,13 @@ void HostServer::ConnectBrEdr(DeviceId peer_id, ConnectCallback callback) { } } -void HostServer::Forget(::std::string device_id, ForgetCallback callback) { - auto id = DeviceIdFromString(device_id); +void HostServer::Forget(::std::string peer_id, ForgetCallback callback) { + auto id = DeviceIdFromString(peer_id); if (!id.has_value()) { callback(NewFidlError(ErrorCode::INVALID_ARGUMENTS, "Invalid peer ID")); return; } - auto peer = adapter()->remote_device_cache()->FindDeviceById(*id); + auto peer = adapter()->peer_cache()->FindById(*id); if (!peer) { callback(NewFidlError(ErrorCode::NOT_FOUND, "Cannot find peer with the given ID")); @@ -572,8 +568,8 @@ void HostServer::Forget(::std::string device_id, ForgetCallback callback) { adapter()->bredr_connection_manager()->Disconnect(*id); } - const bool forgot = adapter()->remote_device_cache()->ForgetPeer(*id); - bt_log(TRACE, "bt-host", "forget peer (id %s) %s", device_id.c_str(), + const bool forgot = adapter()->peer_cache()->ForgetPeer(*id); + bt_log(TRACE, "bt-host", "forget peer (id %s) %s", peer_id.c_str(), forgot ? "succeeded" : "failed"); if (!forgot) { callback(NewFidlError(ErrorCode::FAILED, "Failed to forget peer")); @@ -673,17 +669,17 @@ bt::sm::IOCapability HostServer::io_capability() const { } void HostServer::CompletePairing(DeviceId id, bt::sm::Status status) { - bt_log(INFO, "bt-host", "pairing complete for device: %s, status: %s", + bt_log(INFO, "bt-host", "pairing complete for peer: %s, status: %s", bt_str(id), status.ToString().c_str()); ZX_DEBUG_ASSERT(pairing_delegate_); pairing_delegate_->OnPairingComplete(id.ToString(), StatusToFidl(status)); } void HostServer::ConfirmPairing(DeviceId id, ConfirmCallback confirm) { - bt_log(INFO, "bt-host", "pairing request for device: %s", bt_str(id)); - auto found_device = adapter()->remote_device_cache()->FindDeviceById(id); - ZX_DEBUG_ASSERT(found_device); - auto device = fidl_helpers::NewRemoteDevicePtr(*found_device); + bt_log(INFO, "bt-host", "pairing request for peer: %s", bt_str(id)); + auto found_peer = adapter()->peer_cache()->FindById(id); + ZX_DEBUG_ASSERT(found_peer); + auto device = fidl_helpers::NewRemoteDevicePtr(*found_peer); ZX_DEBUG_ASSERT(device); ZX_DEBUG_ASSERT(pairing_delegate_); @@ -696,11 +692,12 @@ void HostServer::ConfirmPairing(DeviceId id, ConfirmCallback confirm) { void HostServer::DisplayPasskey(DeviceId id, uint32_t passkey, ConfirmCallback confirm) { - bt_log(INFO, "bt-host", "pairing request for device: %s", bt_str(id)); + bt_log(INFO, "bt-host", "pairing request for peer: %s", bt_str(id)); bt_log(INFO, "bt-host", "enter passkey: %06u", passkey); - auto device = fidl_helpers::NewRemoteDevicePtr( - *adapter()->remote_device_cache()->FindDeviceById(id)); + auto* peer = adapter()->peer_cache()->FindById(id); + ZX_DEBUG_ASSERT(peer); + auto device = fidl_helpers::NewRemoteDevicePtr(*peer); ZX_DEBUG_ASSERT(device); ZX_DEBUG_ASSERT(pairing_delegate_); @@ -713,8 +710,9 @@ void HostServer::DisplayPasskey(DeviceId id, uint32_t passkey, } void HostServer::RequestPasskey(DeviceId id, PasskeyResponseCallback respond) { - auto device = fidl_helpers::NewRemoteDevicePtr( - *adapter()->remote_device_cache()->FindDeviceById(id)); + auto* peer = adapter()->peer_cache()->FindById(id); + ZX_DEBUG_ASSERT(peer); + auto device = fidl_helpers::NewRemoteDevicePtr(*peer); ZX_DEBUG_ASSERT(device); ZX_DEBUG_ASSERT(pairing_delegate_); @@ -743,24 +741,23 @@ void HostServer::OnConnectionError(Server* server) { servers_.erase(server); } -void HostServer::OnRemoteDeviceUpdated( - const bt::gap::RemoteDevice& remote_device) { - if (!remote_device.connectable()) { +void HostServer::OnPeerUpdated(const bt::gap::Peer& peer) { + if (!peer.connectable()) { return; } - auto fidl_device = fidl_helpers::NewRemoteDevicePtr(remote_device); + auto fidl_device = fidl_helpers::NewRemoteDevicePtr(peer); if (!fidl_device) { - bt_log(TRACE, "bt-host", "ignoring malformed device update"); + bt_log(TRACE, "bt-host", "ignoring malformed peer update"); return; } this->binding()->events().OnDeviceUpdated(std::move(*fidl_device)); } -void HostServer::OnRemoteDeviceRemoved(bt::gap::DeviceId identifier) { - // TODO(armansito): Notify only if the device is connectable for symmetry with - // OnDeviceUpdated? +void HostServer::OnPeerRemoved(bt::gap::DeviceId identifier) { + // TODO(armansito): Notify only if the peer is connectable for symmetry with + // OnPeerUpdated? this->binding()->events().OnDeviceRemoved(identifier.ToString()); } diff --git a/src/connectivity/bluetooth/core/bt-host/fidl/host_server.h b/src/connectivity/bluetooth/core/bt-host/fidl/host_server.h index f0759ffb84ea1af2c67fa37fbae509afb8ff927b..8f84e87904d6d8508125d5a87511bd7d930c9855 100644 --- a/src/connectivity/bluetooth/core/bt-host/fidl/host_server.h +++ b/src/connectivity/bluetooth/core/bt-host/fidl/host_server.h @@ -88,24 +88,20 @@ class HostServer : public AdapterServerBase<fuchsia::bluetooth::host::Host>, void RequestPasskey(bt::gap::DeviceId id, PasskeyResponseCallback respond) override; - // Called by |adapter()->remote_device_cache()| when a remote device is - // updated. - void OnRemoteDeviceUpdated(const bt::gap::RemoteDevice& remote_device); + // Called by |adapter()->peer_cache()| when a peer is updated. + void OnPeerUpdated(const bt::gap::Peer& peer); - // Called by |adapter()->remote_device_cache()| when a remote device is - // removed. - void OnRemoteDeviceRemoved(bt::gap::DeviceId identifier); + // Called by |adapter()->peer_cache()| when a peer is removed. + void OnPeerRemoved(bt::gap::DeviceId identifier); - // Called by |adapter()->remote_device_cache()| when a remote device is - // bonded. - void OnRemoteDeviceBonded(const bt::gap::RemoteDevice& remote_device); + // Called by |adapter()->peer_cache()| when a peer is bonded. + void OnPeerBonded(const bt::gap::Peer& peer); void ConnectLowEnergy(bt::gap::DeviceId id, ConnectCallback callback); void ConnectBrEdr(bt::gap::DeviceId peer_id, ConnectCallback callback); - // Called when a connection is established to a remote device, either when - // initiated by a user via a client of Host.fidl, or automatically by the GAP - // adapter + // Called when a connection is established to a peer, either when initiated + // by a user via a client of Host.fidl, or automatically by the GAP adapter void RegisterLowEnergyConnection(bt::gap::LowEnergyConnectionRefPtr conn_ref, bool auto_connect); diff --git a/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_central_server.cc b/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_central_server.cc index 372292fe2cedd26722ad65f53c3fdc49cfcf9313..4a7aa803f2afc4fba39a32dc5939f7501bddb35b 100644 --- a/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_central_server.cc +++ b/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_central_server.cc @@ -6,9 +6,8 @@ #include <zircon/assert.h> -#include "src/connectivity/bluetooth/core/bt-host/common/log.h" - #include "helpers.h" +#include "src/connectivity/bluetooth/core/bt-host/common/log.h" using fuchsia::bluetooth::ErrorCode; using fuchsia::bluetooth::Int8; @@ -92,9 +91,9 @@ void LowEnergyCentralServer::StartScan(ScanFilterPtr filter, if (filter) fidl_helpers::PopulateDiscoveryFilter(*filter, session->filter()); - session->SetResultCallback([self](const auto& device) { + session->SetResultCallback([self](const auto& peer) { if (self) - self->OnScanResult(device); + self->OnScanResult(peer); }); session->set_error_callback([self] { @@ -130,7 +129,7 @@ void LowEnergyCentralServer::ConnectPeripheral( auto peer_id = fidl_helpers::DeviceIdFromString(identifier); if (!peer_id.has_value()) { callback(fidl_helpers::NewFidlError(ErrorCode::INVALID_ARGUMENTS, - "invalid device ID")); + "invalid peer ID")); return; } @@ -164,14 +163,14 @@ void LowEnergyCentralServer::ConnectPeripheral( if (!status) { ZX_DEBUG_ASSERT(!conn_ref); - bt_log(TRACE, "bt-host", "failed to connect to connect to device (id %s)", + bt_log(TRACE, "bt-host", "failed to connect to connect to peer (id %s)", bt_str(peer_id)); callback(fidl_helpers::StatusToFidl(status, "failed to connect")); return; } ZX_DEBUG_ASSERT(conn_ref); - ZX_DEBUG_ASSERT(peer_id == conn_ref->device_identifier()); + ZX_DEBUG_ASSERT(peer_id == conn_ref->peer_identifier()); if (iter->second) { // This can happen if a connect is requested after a previous request was @@ -200,10 +199,10 @@ void LowEnergyCentralServer::ConnectPeripheral( if (!adapter()->le_connection_manager()->Connect(*peer_id, std::move(conn_cb))) { - bt_log(TRACE, "bt-host", "cannot connect to unknown device (id: %s)", + bt_log(TRACE, "bt-host", "cannot connect to unknown peer (id: %s)", identifier.c_str()); callback( - fidl_helpers::NewFidlError(ErrorCode::NOT_FOUND, "unknown device ID")); + fidl_helpers::NewFidlError(ErrorCode::NOT_FOUND, "unknown peer ID")); return; } @@ -215,20 +214,20 @@ void LowEnergyCentralServer::DisconnectPeripheral( auto peer_id = fidl_helpers::DeviceIdFromString(identifier); if (!peer_id.has_value()) { callback(fidl_helpers::NewFidlError(ErrorCode::INVALID_ARGUMENTS, - "invalid device ID")); + "invalid peer ID")); return; } auto iter = connections_.find(*peer_id); if (iter == connections_.end()) { - bt_log(TRACE, "bt-host", "client not connected to device (id: %s)", + bt_log(TRACE, "bt-host", "client not connected to peer (id: %s)", identifier.c_str()); - callback(fidl_helpers::NewFidlError(ErrorCode::NOT_FOUND, - "device not connected")); + callback( + fidl_helpers::NewFidlError(ErrorCode::NOT_FOUND, "peer not connected")); return; } - // If a request to this device is pending then the request will be canceled. + // If a request to this peer is pending then the request will be canceled. bool was_pending = !iter->second; connections_.erase(iter); @@ -242,17 +241,16 @@ void LowEnergyCentralServer::DisconnectPeripheral( callback(Status()); } -void LowEnergyCentralServer::OnScanResult( - const bt::gap::RemoteDevice& remote_device) { - auto fidl_device = fidl_helpers::NewLERemoteDevice(remote_device); +void LowEnergyCentralServer::OnScanResult(const bt::gap::Peer& peer) { + auto fidl_device = fidl_helpers::NewLERemoteDevice(peer); if (!fidl_device) { bt_log(TRACE, "bt-host", "ignoring malformed scan result"); return; } - if (remote_device.rssi() != bt::hci::kRSSIInvalid) { + if (peer.rssi() != bt::hci::kRSSIInvalid) { fidl_device->rssi = Int8::New(); - fidl_device->rssi->value = remote_device.rssi(); + fidl_device->rssi->value = peer.rssi(); } binding()->events().OnDeviceDiscovered(std::move(*fidl_device)); diff --git a/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_central_server.h b/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_central_server.h index c9349f700c810f2a4da8293aebd8ffef5dd4b627..a394e6d3e90c5968c99a8cf52c562c5c3c8de959 100644 --- a/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_central_server.h +++ b/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_central_server.h @@ -46,7 +46,7 @@ class LowEnergyCentralServer DisconnectPeripheralCallback callback) override; // Called by |scan_session_| when a device is discovered. - void OnScanResult(const bt::gap::RemoteDevice& remote_device); + void OnScanResult(const bt::gap::Peer& peer); // Notifies the delegate that the scan state for this Central has changed. void NotifyScanStateChanged(bool scanning); @@ -64,7 +64,7 @@ class LowEnergyCentralServer std::unique_ptr<bt::gap::LowEnergyDiscoverySession> scan_session_; // This client's connection references. A client can hold a connection to - // multiple peers. Each key is a remote device identifier. Each value is + // multiple peers. Each key is a peer identifier. Each value is // a. nullptr, if a connect request to this device is currently pending. // b. a valid reference if this Central is holding a connection reference to // this device. diff --git a/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_peripheral_server.cc b/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_peripheral_server.cc index bbb5a70e00c1936999f64ac11808807a76703a5f..987573b02a97ec0c8fa40577e8ff90f649cd4f53 100644 --- a/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_peripheral_server.cc +++ b/src/connectivity/bluetooth/core/bt-host/fidl/low_energy_peripheral_server.cc @@ -6,15 +6,14 @@ #include <zircon/assert.h> +#include "helpers.h" #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/connectivity/bluetooth/core/bt-host/gap/advertising_data.h" -#include "src/connectivity/bluetooth/core/bt-host/gap/remote_device.h" +#include "src/connectivity/bluetooth/core/bt-host/gap/peer.h" #include "src/connectivity/bluetooth/core/bt-host/hci/hci_constants.h" #include "src/connectivity/bluetooth/core/bt-host/hci/util.h" #include "src/lib/fxl/strings/string_number_conversions.h" -#include "helpers.h" - using fuchsia::bluetooth::ErrorCode; using fuchsia::bluetooth::Status; @@ -76,7 +75,7 @@ void LowEnergyPeripheralServer::InstanceData::ReleaseConnection() { ZX_DEBUG_ASSERT(conn_ref_); owner_->binding()->events().OnCentralDisconnected( - conn_ref_->device_identifier().ToString()); + conn_ref_->peer_identifier().ToString()); conn_ref_ = nullptr; } @@ -159,7 +158,7 @@ void LowEnergyPeripheralServer::StopAdvertising( auto peer_id = AdvertisementIdFromString(id); if (!peer_id.has_value()) { callback(fidl_helpers::NewFidlError(ErrorCode::INVALID_ARGUMENTS, - "invalid device ID")); + "invalid peer ID")); return; } @@ -219,14 +218,13 @@ void LowEnergyPeripheralServer::OnConnected( it->second.ReleaseConnection(); }); - // A RemoteDevice will have been created for the new connection. - auto* device = - adapter()->device_cache().FindDeviceById(conn->device_identifier()); - ZX_DEBUG_ASSERT(device); + // A peer will have been created for the new connection. + auto* peer = adapter()->peer_cache()->FindById(conn->peer_identifier()); + ZX_DEBUG_ASSERT(peer); bt_log(TRACE, "bt-host", "central connected"); RemoteDevicePtr remote_device = - fidl_helpers::NewLERemoteDevice(std::move(*device)); + fidl_helpers::NewLERemoteDevice(std::move(*peer)); ZX_DEBUG_ASSERT(remote_device); it->second.RetainConnection(std::move(conn), std::move(*remote_device)); } diff --git a/src/connectivity/bluetooth/core/bt-host/gap/BUILD.gn b/src/connectivity/bluetooth/core/bt-host/gap/BUILD.gn index 71de540e151b23902fef9794782577c0a3039527..04f6a0d5e49fbc88670706d7b6d8d5a75bbcdb97 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/BUILD.gn +++ b/src/connectivity/bluetooth/core/bt-host/gap/BUILD.gn @@ -33,10 +33,10 @@ static_library("gap") { "low_energy_state.cc", "low_energy_state.h", "pairing_delegate.h", - "remote_device.cc", - "remote_device.h", - "remote_device_cache.cc", - "remote_device_cache.h", + "peer.cc", + "peer.h", + "peer_cache.cc", + "peer_cache.h", ] public_deps = [ @@ -70,7 +70,7 @@ source_set("tests") { "low_energy_advertising_manager_unittest.cc", "low_energy_connection_manager_unittest.cc", "low_energy_discovery_manager_unittest.cc", - "remote_device_cache_unittest.cc", + "peer_cache_unittest.cc", ] deps = [ diff --git a/src/connectivity/bluetooth/core/bt-host/gap/adapter.cc b/src/connectivity/bluetooth/core/bt-host/gap/adapter.cc index a2844a1e92649c2a90d2fc7130c49e00691024eb..1211b92d54ffc7f5065de576e79c950a271664b5 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/adapter.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/adapter.cc @@ -13,7 +13,7 @@ #include "low_energy_advertising_manager.h" #include "low_energy_connection_manager.h" #include "low_energy_discovery_manager.h" -#include "remote_device.h" +#include "peer.h" #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/connectivity/bluetooth/core/bt-host/common/random.h" #include "src/connectivity/bluetooth/core/bt-host/hci/connection.h" @@ -192,12 +192,12 @@ void Adapter::ShutDown() { CleanUp(); } -bool Adapter::AddBondedDevice(DeviceId identifier, - const common::DeviceAddress& address, - const sm::PairingData& le_bond_data, - const std::optional<sm::LTK>& link_key) { - return remote_device_cache()->AddBondedDevice(identifier, address, - le_bond_data, link_key); +bool Adapter::AddBondedPeer(DeviceId identifier, + const common::DeviceAddress& address, + const sm::PairingData& le_bond_data, + const std::optional<sm::LTK>& link_key) { + return peer_cache()->AddBondedPeer(identifier, address, le_bond_data, + link_key); } void Adapter::SetPairingDelegate(fxl::WeakPtr<PairingDelegate> delegate) { @@ -548,11 +548,11 @@ void Adapter::InitializeStep4(InitializeCallback callback) { // Initialize the LE manager objects le_discovery_manager_ = std::make_unique<LowEnergyDiscoveryManager>( - hci_, hci_le_scanner_.get(), &device_cache_); + hci_, hci_le_scanner_.get(), &peer_cache_); le_discovery_manager_->set_directed_connectable_callback( fit::bind_member(this, &Adapter::OnLeAutoConnectRequest)); le_connection_manager_ = std::make_unique<LowEnergyConnectionManager>( - hci_, le_address_manager_.get(), hci_le_connector_.get(), &device_cache_, + hci_, le_address_manager_.get(), hci_le_connector_.get(), &peer_cache_, data_domain_, gatt_); le_advertising_manager_ = std::make_unique<LowEnergyAdvertisingManager>( hci_le_advertiser_.get(), le_address_manager_.get()); @@ -563,7 +563,7 @@ void Adapter::InitializeStep4(InitializeCallback callback) { common::DeviceAddress::Type::kBREDR, state_.controller_address()); bredr_connection_manager_ = std::make_unique<BrEdrConnectionManager>( - hci_, &device_cache_, local_bredr_address, data_domain_, + hci_, &peer_cache_, local_bredr_address, data_domain_, state_.features().HasBit(0, hci::LMPFeature::kInterlacedPageScan)); hci::InquiryMode mode = hci::InquiryMode::kStandard; @@ -576,7 +576,7 @@ void Adapter::InitializeStep4(InitializeCallback callback) { } bredr_discovery_manager_ = - std::make_unique<BrEdrDiscoveryManager>(hci_, mode, &device_cache_); + std::make_unique<BrEdrDiscoveryManager>(hci_, mode, &peer_cache_); sdp_server_ = std::make_unique<sdp::Server>(data_domain_); } @@ -688,11 +688,11 @@ void Adapter::OnTransportClosed() { transport_closed_cb_(); } -void Adapter::OnLeAutoConnectRequest(DeviceId device_id) { +void Adapter::OnLeAutoConnectRequest(DeviceId peer_id) { ZX_DEBUG_ASSERT(le_connection_manager_); auto self = weak_ptr_factory_.GetWeakPtr(); - le_connection_manager_->Connect(device_id, [self](auto status, auto conn) { - DeviceId id = conn->device_identifier(); + le_connection_manager_->Connect(peer_id, [self](auto status, auto conn) { + DeviceId id = conn->peer_identifier(); if (!self) { bt_log(INFO, "gap", "ignoring auto-connection (adapter destroyed)"); return; @@ -702,7 +702,7 @@ void Adapter::OnLeAutoConnectRequest(DeviceId device_id) { return; } - bt_log(INFO, "gap", "device auto-connected (id: %s)", bt_str(id)); + bt_log(INFO, "gap", "peer auto-connected (id: %s)", bt_str(id)); if (self->auto_conn_cb_) { self->auto_conn_cb_(std::move(conn)); } diff --git a/src/connectivity/bluetooth/core/bt-host/gap/adapter.h b/src/connectivity/bluetooth/core/bt-host/gap/adapter.h index 941d10c2f9aedb5adcbd1cbae948a89c49564ce7..06d5581389911cad4aa2adcb5896c753859ebf9a 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/adapter.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/adapter.h @@ -17,7 +17,7 @@ #include "src/connectivity/bluetooth/core/bt-host/data/domain.h" #include "src/connectivity/bluetooth/core/bt-host/gap/adapter_state.h" #include "src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager.h" -#include "src/connectivity/bluetooth/core/bt-host/gap/remote_device_cache.h" +#include "src/connectivity/bluetooth/core/bt-host/gap/peer_cache.h" #include "src/connectivity/bluetooth/core/bt-host/gatt/gatt.h" #include "src/connectivity/bluetooth/core/bt-host/sdp/server.h" #include "src/lib/fxl/memory/weak_ptr.h" @@ -107,8 +107,8 @@ class Adapter final { // Returns a weak pointer to this adapter. fxl::WeakPtr<Adapter> AsWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } - // Returns this Adapter's remote device cache. - const RemoteDeviceCache& device_cache() const { return device_cache_; } + // Returns this Adapter's peer cache. + const PeerCache& peer_cache() const { return peer_cache_; } // Returns this Adapter's BR/EDR connection manager. BrEdrConnectionManager* bredr_connection_manager() const { @@ -147,15 +147,14 @@ class Adapter final { return le_advertising_manager_.get(); } - // Returns this Adapter's remote device cache. - RemoteDeviceCache* remote_device_cache() { return &device_cache_; } + // Returns this Adapter's peer cache. + PeerCache* peer_cache() { return &peer_cache_; } - // Add a previously bonded device to the device cache and set it up for + // Add a previously bonded device to the peer cache and set it up for // auto-connect procedures. - bool AddBondedDevice(DeviceId identifier, - const common::DeviceAddress& address, - const sm::PairingData& le_bond_data, - const std::optional<sm::LTK>& link_key); + bool AddBondedPeer(DeviceId identifier, const common::DeviceAddress& address, + const sm::PairingData& le_bond_data, + const std::optional<sm::LTK>& link_key); // Assigns a pairing delegate to this adapter. This PairingDelegate and its // I/O capabilities will be used for all future pairing procedures. Setting a @@ -175,7 +174,7 @@ class Adapter final { hci::StatusCallback callback); // Assign a callback to be notified when a connection is automatically - // established to a bonded LE device in the directed connectable mode (Vol 3, + // established to a bonded LE peer in the directed connectable mode (Vol 3, // Part C, 9.3.3). using AutoConnectCallback = fit::function<void(LowEnergyConnectionRefPtr)>; void set_auto_connect_callback(AutoConnectCallback callback) { @@ -217,7 +216,7 @@ class Adapter final { // which is handled by routing the request to |le_connection_manager_| to // initiate a Direct Connection Establishment procedure (Vol 3, Part C, // 9.3.8). - void OnLeAutoConnectRequest(DeviceId device_id); + void OnLeAutoConnectRequest(DeviceId peer_id); // Called by |le_address_manager_| to query whether it is currently allowed to // reconfigure the LE random address. @@ -252,7 +251,7 @@ class Adapter final { // Provides access to discovered, connected, and/or bonded remote Bluetooth // devices. - RemoteDeviceCache device_cache_; + PeerCache peer_cache_; // The data domain used by GAP to interact with L2CAP and RFCOMM layers. fbl::RefPtr<data::Domain> data_domain_; diff --git a/src/connectivity/bluetooth/core/bt-host/gap/adapter_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gap/adapter_unittest.cc index 269e173716c272930650a6f02a87b227b1a0cb2d..858c0b854deee26aea45371e41d45f39bb062b72 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/adapter_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/adapter_unittest.cc @@ -277,8 +277,8 @@ TEST_F(GAP_AdapterTest, SetNameSuccess) { } } -TEST_F(GAP_AdapterTest, RemoteDeviceCacheReturnsNonNull) { - EXPECT_TRUE(adapter()->remote_device_cache()); +TEST_F(GAP_AdapterTest, PeerCacheReturnsNonNull) { + EXPECT_TRUE(adapter()->peer_cache()); } TEST_F(GAP_AdapterTest, LeAutoConnect) { @@ -305,19 +305,18 @@ TEST_F(GAP_AdapterTest, LeAutoConnect) { adapter()->le_discovery_manager()->EnableBackgroundScan(true); RunLoopUntilIdle(); EXPECT_FALSE(conn); - EXPECT_EQ(0u, adapter()->remote_device_cache()->count()); + EXPECT_EQ(0u, adapter()->peer_cache()->count()); - // Mark the device as bonded and advance the scan period. + // Mark the peer as bonded and advance the scan period. sm::PairingData pdata; pdata.ltk = sm::LTK(); - adapter()->remote_device_cache()->AddBondedDevice(kDeviceId, kTestAddr, pdata, - {}); - EXPECT_EQ(1u, adapter()->remote_device_cache()->count()); + adapter()->peer_cache()->AddBondedPeer(kDeviceId, kTestAddr, pdata, {}); + EXPECT_EQ(1u, adapter()->peer_cache()->count()); RunLoopFor(kTestScanPeriod); - // The device should have been auto-connected. + // The peer should have been auto-connected. ASSERT_TRUE(conn); - EXPECT_EQ(kDeviceId, conn->device_identifier()); + EXPECT_EQ(kDeviceId, conn->peer_identifier()); } // Tests the interactions between the advertising manager and the local address @@ -471,7 +470,7 @@ TEST_F(GAP_AdapterTest, LocalAddressForConnections) { InitializeAdapter([](bool) {}); // Set-up a device for testing. - auto* peer = adapter()->remote_device_cache()->NewDevice(kTestAddr, true); + auto* peer = adapter()->peer_cache()->NewPeer(kTestAddr, true); auto fake_peer = std::make_unique<FakePeer>(kTestAddr); test_device()->AddPeer(std::move(fake_peer)); @@ -523,7 +522,7 @@ TEST_F(GAP_AdapterTest, LocalAddressDuringHangingConnect) { // Add a device to the cache but not the fake controller. This will cause the // connection request to hang. - auto* peer = adapter()->remote_device_cache()->NewDevice(kTestAddr, true); + auto* peer = adapter()->peer_cache()->NewPeer(kTestAddr, true); constexpr auto kTestDelay = zx::sec(5); constexpr auto kTestTimeout = kPrivateAddressTimeout + kTestDelay; @@ -562,8 +561,7 @@ TEST_F(GAP_AdapterTest, LocalAddressDuringHangingConnect) { EXPECT_EQ(HostError::kTimedOut, status.error()); // The peer should not have expired. - ASSERT_EQ(peer, - adapter()->remote_device_cache()->FindDeviceByAddress(kTestAddr)); + ASSERT_EQ(peer, adapter()->peer_cache()->FindByAddress(kTestAddr)); adapter()->le_connection_manager()->Connect(peer->identifier(), connect_cb); RunLoopUntilIdle(); ASSERT_TRUE(test_device()->le_random_address()); @@ -576,8 +574,7 @@ TEST_F(GAP_AdapterTest, LocalAddressDuringHangingConnect) { RunLoopFor(kPrivateAddressTimeout); EXPECT_EQ(last_random_addr, *test_device()->le_random_address()); - ASSERT_EQ(peer, - adapter()->remote_device_cache()->FindDeviceByAddress(kTestAddr)); + ASSERT_EQ(peer, adapter()->peer_cache()->FindByAddress(kTestAddr)); // The address should refresh after the next connection attempt. RunLoopFor(kTestDelay); @@ -604,7 +601,7 @@ TEST_F(GAP_AdapterTest, ExistingConnectionDoesNotPreventLocalAddressChange) { conn_ref = std::move(c); }; - auto* peer = adapter()->remote_device_cache()->NewDevice(kTestAddr, true); + auto* peer = adapter()->peer_cache()->NewPeer(kTestAddr, true); auto fake_peer = std::make_unique<FakePeer>(kTestAddr); test_device()->AddPeer(std::move(fake_peer)); adapter()->le_connection_manager()->Connect(peer->identifier(), connect_cb); diff --git a/src/connectivity/bluetooth/core/bt-host/gap/advertising_data.cc b/src/connectivity/bluetooth/core/bt-host/gap/advertising_data.cc index aaa644c4f98586f168d2242a81e6d4e557bf1f3a..62805ae78efe75ea2052091fc467d54919e09083 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/advertising_data.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/advertising_data.cc @@ -4,17 +4,17 @@ #include "advertising_data.h" -#include <type_traits> - #include <endian.h> #include <zircon/assert.h> +#include <type_traits> + #include "lib/fidl/cpp/type_converter.h" #include "lib/fidl/cpp/vector.h" -#include "src/lib/fxl/strings/string_printf.h" -#include "src/lib/fxl/strings/utf_codecs.h" #include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" #include "src/connectivity/bluetooth/core/bt-host/common/log.h" +#include "src/lib/fxl/strings/string_printf.h" +#include "src/lib/fxl/strings/utf_codecs.h" // A partial fidl::TypeConverter template specialization for copying the // contents of a type that derives from ByteBuffer into a @@ -229,7 +229,7 @@ bool AdvertisingData::FromBytes(const ByteBuffer& data, break; } case DataType::kAppearance: { - // TODO(armansito): RemoteDevice should have a function to return the + // TODO(armansito): Peer should have a function to return the // device appearance, as it can be obtained either from advertising data // or via GATT. if (field.size() != kAppearanceSize) { diff --git a/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager.cc b/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager.cc index 548a36de48d42596550e152b75316c869fcd5468..c66e80c10f851daf96bf218d99cef316d9c9ca20 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager.cc @@ -7,7 +7,7 @@ #include <zircon/assert.h> #include "src/connectivity/bluetooth/core/bt-host/common/log.h" -#include "src/connectivity/bluetooth/core/bt-host/gap/remote_device_cache.h" +#include "src/connectivity/bluetooth/core/bt-host/gap/peer_cache.h" #include "src/connectivity/bluetooth/core/bt-host/hci/connection.h" #include "src/connectivity/bluetooth/core/bt-host/hci/hci_constants.h" #include "src/connectivity/bluetooth/core/bt-host/hci/sequential_command_runner.h" @@ -19,7 +19,7 @@ namespace gap { using common::DeviceAddress; using common::HostError; using std::unique_ptr; -using ConnectionState = RemoteDevice::ConnectionState; +using ConnectionState = Peer::ConnectionState; namespace { @@ -74,11 +74,11 @@ hci::CommandChannel::EventHandlerId BrEdrConnectionManager::AddEventHandler( } BrEdrConnectionManager::BrEdrConnectionManager( - fxl::RefPtr<hci::Transport> hci, RemoteDeviceCache* device_cache, + fxl::RefPtr<hci::Transport> hci, PeerCache* peer_cache, DeviceAddress local_address, fbl::RefPtr<data::Domain> data_domain, bool use_interlaced_scan) : hci_(hci), - cache_(device_cache), + cache_(peer_cache), local_address_(local_address), data_domain_(data_domain), interrogator_(cache_, hci_, async_get_default_dispatcher()), @@ -183,9 +183,9 @@ DeviceId BrEdrConnectionManager::GetPeerId(hci::ConnectionHandle handle) const { return common::kInvalidDeviceId; } - auto* device = cache_->FindDeviceByAddress(it->second.link().peer_address()); - ZX_DEBUG_ASSERT_MSG(device, "Couldn't find device for handle %#.4x", handle); - return device->identifier(); + auto* peer = cache_->FindByAddress(it->second.link().peer_address()); + ZX_DEBUG_ASSERT_MSG(peer, "Couldn't find peer for handle %#.4x", handle); + return peer->identifier(); } bool BrEdrConnectionManager::OpenL2capChannel(DeviceId peer_id, l2cap::PSM psm, @@ -290,8 +290,8 @@ void BrEdrConnectionManager::WritePageScanSettings(uint16_t interval, std::optional<std::pair<hci::ConnectionHandle, BrEdrConnection*>> BrEdrConnectionManager::FindConnectionById(DeviceId peer_id) { - auto* const device = cache_->FindDeviceById(peer_id); - if (!device || !device->bredr() || !device->bredr()->connected()) { + auto* const peer = cache_->FindById(peer_id); + if (!peer || !peer->bredr() || !peer->bredr()->connected()) { return std::nullopt; } @@ -357,13 +357,13 @@ void BrEdrConnectionManager::OnConnectionRequest( hci::kCommandStatusEventCode); } -RemoteDevice* BrEdrConnectionManager::FindOrInitDevice(DeviceAddress addr) { - RemoteDevice* device = cache_->FindDeviceByAddress(addr); - if (!device) { +Peer* BrEdrConnectionManager::FindOrInitPeer(DeviceAddress addr) { + Peer* peer = cache_->FindByAddress(addr); + if (!peer) { bool connectable = true; - device = cache_->NewDevice(addr, connectable); + peer = cache_->NewPeer(addr, connectable); } - return device; + return peer; } void BrEdrConnectionManager::OnConnectionComplete( @@ -407,16 +407,16 @@ void BrEdrConnectionManager::InitializeConnection(DeviceAddress addr, hci::Connection::Role::kMaster, local_address_, addr, hci_); - RemoteDevice* device = FindOrInitDevice(addr); - // In Br/Edr, we should never establish more than one link to a given device - ZX_DEBUG_ASSERT(!FindConnectionById(device->identifier())); - device->MutBrEdr().SetConnectionState(ConnectionState::kInitializing); + Peer* peer = FindOrInitPeer(addr); + // In Br/Edr, we should never establish more than one link to a given peer + ZX_DEBUG_ASSERT(!FindConnectionById(peer->identifier())); + peer->MutBrEdr().SetConnectionState(ConnectionState::kInitializing); - // Interrogate this device to find out its version/capabilities. + // Interrogate this peer to find out its version/capabilities. auto self = weak_ptr_factory_.GetWeakPtr(); interrogator_.Start( - device->identifier(), std::move(link), - [device, self](auto status, auto conn_ptr) { + peer->identifier(), std::move(link), + [peer, self](auto status, auto conn_ptr) { if (bt_is_error(status, WARN, "gap-bredr", "interrogate failed, dropping connection")) return; @@ -424,14 +424,13 @@ void BrEdrConnectionManager::InitializeConnection(DeviceAddress addr, conn_ptr->handle()); if (!self) return; - self->EstablishConnection(device, status, std::move(conn_ptr)); + self->EstablishConnection(peer, status, std::move(conn_ptr)); }); } // Establish a full BrEdrConnection for a link that has been interrogated void BrEdrConnectionManager::EstablishConnection( - RemoteDevice* device, hci::Status status, - unique_ptr<hci::Connection> connection) { + Peer* peer, hci::Status status, unique_ptr<hci::Connection> connection) { auto self = weak_ptr_factory_.GetWeakPtr(); auto error_handler = [self, connection = connection->WeakPtr()] { @@ -462,14 +461,14 @@ void BrEdrConnectionManager::EstablishConnection( auto conn = connections_ - .try_emplace(handle, device->identifier(), std::move(connection)) + .try_emplace(handle, peer->identifier(), std::move(connection)) .first; - device->MutBrEdr().SetConnectionState(ConnectionState::kConnected); + peer->MutBrEdr().SetConnectionState(ConnectionState::kConnected); if (discoverer_.search_count()) { data_domain_->OpenL2capChannel( handle, l2cap::kSDP, - [self, peer_id = device->identifier()](auto channel) { + [self, peer_id = peer->identifier()](auto channel) { if (!self) return; auto client = sdp::Client::Create(std::move(channel)); @@ -479,13 +478,13 @@ void BrEdrConnectionManager::EstablishConnection( dispatcher_); } - auto request = connection_requests_.extract(device->identifier()); + auto request = connection_requests_.extract(peer->identifier()); if (request) { auto conn_ptr = &(conn->second); request.mapped().NotifyCallbacks(hci::Status(), [conn_ptr] { return conn_ptr; }); // If this was our in-flight request, close it - if (device->address() == pending_request_->peer_address()) { + if (peer->address() == pending_request_->peer_address()) { pending_request_.reset(); } TryCreateNextConnection(); @@ -511,10 +510,10 @@ void BrEdrConnectionManager::OnDisconnectionComplete( return; } - auto* device = cache_->FindDeviceByAddress(it->second.link().peer_address()); + auto* peer = cache_->FindByAddress(it->second.link().peer_address()); bt_log(INFO, "gap-bredr", "%s disconnected - %s, handle: %#.4x, reason: %#.2x", - bt_str(device->identifier()), bt_str(event.ToStatus()), handle, + bt_str(peer->identifier()), bt_str(event.ToStatus()), handle, params.reason); CleanupConnection(handle, connections_.extract(handle).mapped(), true); @@ -523,10 +522,9 @@ void BrEdrConnectionManager::OnDisconnectionComplete( void BrEdrConnectionManager::CleanupConnection(hci::ConnectionHandle handle, BrEdrConnection& conn, bool link_already_closed) { - auto* device = cache_->FindDeviceByAddress(conn.link().peer_address()); - ZX_DEBUG_ASSERT_MSG(device, "Couldn't find RemoteDevice for handle: %#.4x", - handle); - device->MutBrEdr().SetConnectionState(ConnectionState::kNotConnected); + auto* peer = cache_->FindByAddress(conn.link().peer_address()); + ZX_DEBUG_ASSERT_MSG(peer, "Couldn't find peer for handle: %#.4x", handle); + peer->MutBrEdr().SetConnectionState(ConnectionState::kNotConnected); data_domain_->RemoveConnection(handle); @@ -543,8 +541,8 @@ void BrEdrConnectionManager::OnLinkKeyRequest(const hci::EventPacket& event) { common::DeviceAddress addr(common::DeviceAddress::Type::kBREDR, params.bd_addr); - auto* device = cache_->FindDeviceByAddress(addr); - if (!device || !device->bredr()->bonded()) { + auto* peer = cache_->FindByAddress(addr); + if (!peer || !peer->bredr()->bonded()) { bt_log(INFO, "gap-bredr", "no known peer with address %s found", addr.ToString().c_str()); @@ -563,7 +561,7 @@ void BrEdrConnectionManager::OnLinkKeyRequest(const hci::EventPacket& event) { } bt_log(INFO, "gap-bredr", "recalling link key for bonded peer %s", - bt_str(device->identifier())); + bt_str(peer->identifier())); auto reply = hci::CommandPacket::New( hci::kLinkKeyRequestReply, sizeof(hci::LinkKeyRequestReplyCommandParams)); @@ -572,7 +570,7 @@ void BrEdrConnectionManager::OnLinkKeyRequest(const hci::EventPacket& event) { ->mutable_payload<hci::LinkKeyRequestReplyCommandParams>(); reply_params->bd_addr = params.bd_addr; - const sm::LTK& link_key = *device->bredr()->link_key(); + const sm::LTK& link_key = *peer->bredr()->link_key(); ZX_DEBUG_ASSERT(link_key.security().enc_key_size() == 16); const auto& key_value = link_key.key().value(); std::copy(key_value.begin(), key_value.end(), reply_params->link_key); @@ -595,8 +593,8 @@ void BrEdrConnectionManager::OnLinkKeyNotification( bt_log(TRACE, "gap-bredr", "got link key (type %u) for address %s", params.key_type, addr.ToString().c_str()); - auto* device = cache_->FindDeviceByAddress(addr); - if (!device) { + auto* peer = cache_->FindByAddress(addr); + if (!peer) { bt_log(WARN, "gap-bredr", "no known peer with address %s found; link key not stored", addr.ToString().c_str()); @@ -606,15 +604,15 @@ void BrEdrConnectionManager::OnLinkKeyNotification( const auto key_type = static_cast<hci::LinkKeyType>(params.key_type); sm::SecurityProperties sec_props; if (key_type == hci::LinkKeyType::kChangedCombination) { - if (!device->bredr() || !device->bredr()->bonded()) { + if (!peer->bredr() || !peer->bredr()->bonded()) { bt_log(WARN, "gap-bredr", "can't update link key of unbonded peer %s", - bt_str(device->identifier())); + bt_str(peer->identifier())); return; } // Reuse current properties - ZX_DEBUG_ASSERT(device->bredr()->link_key()); - sec_props = device->bredr()->link_key()->security(); + ZX_DEBUG_ASSERT(peer->bredr()->link_key()); + sec_props = peer->bredr()->link_key()->security(); } else { sec_props = sm::SecurityProperties(key_type); } @@ -622,7 +620,7 @@ void BrEdrConnectionManager::OnLinkKeyNotification( if (sec_props.level() == sm::SecurityLevel::kNoSecurity) { bt_log(WARN, "gap-bredr", "link key for peer %s has insufficient security; not stored", - bt_str(device->identifier())); + bt_str(peer->identifier())); return; } @@ -632,7 +630,7 @@ void BrEdrConnectionManager::OnLinkKeyNotification( sm::LTK key(sec_props, hci::LinkKey(key_value, 0, 0)); if (!cache_->StoreBrEdrBond(addr, key)) { bt_log(ERROR, "gap-bredr", "failed to cache bonding data (id: %s)", - bt_str(device->identifier())); + bt_str(peer->identifier())); } } @@ -653,7 +651,7 @@ void BrEdrConnectionManager::OnIOCapabilitiesRequest( // TODO(jamuraa, BT-169): ask the PairingDelegate if it's set what the IO // capabilities it has. reply_params->io_capability = hci::IOCapability::kNoInputNoOutput; - // TODO(BT-8): Add OOB status from RemoteDeviceCache. + // TODO(BT-8): Add OOB status from PeerCache. reply_params->oob_data_present = 0x00; // None present. // TODO(BT-656): Determine this based on the service requirements. reply_params->auth_requirements = hci::AuthRequirements::kGeneralBonding; @@ -687,14 +685,14 @@ void BrEdrConnectionManager::OnUserConfirmationRequest( bool BrEdrConnectionManager::Connect( DeviceId peer_id, ConnectResultCallback on_connection_result) { - RemoteDevice* peer = cache_->FindDeviceById(peer_id); + Peer* peer = cache_->FindById(peer_id); if (!peer) { - bt_log(WARN, "gap-bredr", "device not found (id: %s)", bt_str(peer_id)); + bt_log(WARN, "gap-bredr", "peer not found (id: %s)", bt_str(peer_id)); return false; } if (peer->technology() == TechnologyType::kLowEnergy) { - bt_log(ERROR, "gap-bredr", "device does not support BrEdr: %s", + bt_log(ERROR, "gap-bredr", "peer does not support BrEdr: %s", peer->ToString().c_str()); return false; } @@ -741,10 +739,10 @@ void BrEdrConnectionManager::TryCreateNextConnection() { return; } - RemoteDevice* peer = nullptr; + Peer* peer = nullptr; for (auto& request : connection_requests_) { - const auto& next_device_addr = request.second.address(); - peer = cache_->FindDeviceByAddress(next_device_addr); + const auto& next_peer_addr = request.second.address(); + peer = cache_->FindByAddress(next_peer_addr); if (peer && peer->bredr()) break; } @@ -766,8 +764,8 @@ void BrEdrConnectionManager::TryCreateNextConnection() { peer->bredr()->page_scan_repetition_mode(), request_timeout_, on_failure); } else { - // If there are no pending requests for devices which are in the cache, try - // to connect to a device which has left the cache, in case it is still + // If there are no pending requests for peers which are in the cache, try + // to connect to a peer which has left the cache, in case it is still // possible auto request = connection_requests_.begin(); if (request != connection_requests_.end()) { @@ -785,13 +783,12 @@ void BrEdrConnectionManager::TryCreateNextConnection() { void BrEdrConnectionManager::OnConnectFailure(hci::Status status, DeviceId peer_id) { // The request failed or timed out. - bt_log(ERROR, "gap-bredr", "failed to connect to device (id: %s)", + bt_log(ERROR, "gap-bredr", "failed to connect to peer (id: %s)", bt_str(peer_id)); - RemoteDevice* dev = cache_->FindDeviceById(peer_id); - // The device may no longer be in the cache by the time this function is - // called - if (dev) { - dev->MutBrEdr().SetConnectionState(ConnectionState::kNotConnected); + Peer* peer = cache_->FindById(peer_id); + // The peer may no longer be in the cache by the time this function is called + if (peer) { + peer->MutBrEdr().SetConnectionState(ConnectionState::kNotConnected); } pending_request_.reset(); diff --git a/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager.h b/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager.h index 88afbfe50a640e10b8422ab3ac1d0e6cab977717..ede79679a7c81d4c08c8c1ef2f1a90250dbf496c 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager.h @@ -8,7 +8,7 @@ #include "src/connectivity/bluetooth/core/bt-host/data/domain.h" #include "src/connectivity/bluetooth/core/bt-host/gap/bredr_interrogator.h" #include "src/connectivity/bluetooth/core/bt-host/gap/connection_request.h" -#include "src/connectivity/bluetooth/core/bt-host/gap/remote_device.h" +#include "src/connectivity/bluetooth/core/bt-host/gap/peer.h" #include "src/connectivity/bluetooth/core/bt-host/hci/bredr_connection_request.h" #include "src/connectivity/bluetooth/core/bt-host/hci/command_channel.h" #include "src/connectivity/bluetooth/core/bt-host/hci/connection.h" @@ -26,7 +26,7 @@ class Transport; namespace gap { class PairingDelegate; -class RemoteDeviceCache; +class PeerCache; class BrEdrConnectionManager; // Represents an established Br/Edr connection, after we have performed @@ -49,12 +49,11 @@ class BrEdrConnection final { }; // Manages all activity related to connections in the BR/EDR section of the -// controller, including whether the device can be connected to, incoming +// controller, including whether the peer can be connected to, incoming // connections, and initiating connections. class BrEdrConnectionManager final { public: - BrEdrConnectionManager(fxl::RefPtr<hci::Transport> hci, - RemoteDeviceCache* device_cache, + BrEdrConnectionManager(fxl::RefPtr<hci::Transport> hci, PeerCache* peer_cache, common::DeviceAddress local_address, fbl::RefPtr<data::Domain> data_domain, bool use_interlaced_scan); @@ -69,18 +68,18 @@ class BrEdrConnectionManager final { // rejected. void SetPairingDelegate(fxl::WeakPtr<PairingDelegate> delegate); - // Retrieves the device id that is connected to the connection |handle|. - // Returns common::kInvalidDeviceId if no such device exists. + // Retrieves the peer id that is connected to the connection |handle|. + // Returns common::kInvalidDeviceId if no such peer exists. DeviceId GetPeerId(hci::ConnectionHandle handle) const; // Opens a new L2CAP channel to service |psm| on |peer_id|. Returns false if - // the device is not already connected. + // the peer is not already connected. using SocketCallback = fit::function<void(zx::socket)>; bool OpenL2capChannel(DeviceId peer_id, l2cap::PSM psm, SocketCallback cb, async_dispatcher_t* dispatcher); - // Add a service search to be performed on new connected remote devices. - // This search will happen on every device connection. + // Add a service search to be performed on new connected remote peers. + // This search will happen on every peer connection. // |callback| will be called with the |attributes| that exist in the service // entry on the remote SDP server. This callback is called in the same // dispatcher as BrEdrConnectionManager was created. @@ -103,7 +102,7 @@ class BrEdrConnectionManager final { fit::function<void(hci::Status, BrEdrConnection*)>; // Initiates an outgoing Create Connection Request to attempt to connect to - // the device identified by |peer_id|. Returns false if the connection + // the peer identified by |peer_id|. Returns false if the connection // request was invalid, otherwise returns true and |callback| will be called // with the result of the procedure, whether successful or not // TODO(BT-820) - implement a timeout @@ -120,7 +119,7 @@ class BrEdrConnectionManager final { void SendCreateConnectionCancelCommand(common::DeviceAddress addr); // Disconnects any existing BR/EDR connection to |peer_id|. Returns false if - // |peer_id| is not a recognized BR/EDR device or the corresponding peer is + // |peer_id| is not a recognized BR/EDR peer or the corresponding peer is // not connected. bool Disconnect(DeviceId peer_id); @@ -140,7 +139,8 @@ class BrEdrConnectionManager final { // Find the handle for a connection to |peer_id|. Returns nullopt if no BR/EDR // |peer_id| is connected. - std::optional<std::pair<hci::ConnectionHandle, BrEdrConnection*>> FindConnectionById(DeviceId peer_id); + std::optional<std::pair<hci::ConnectionHandle, BrEdrConnection*>> + FindConnectionById(DeviceId peer_id); // Callbacks for registered events void OnConnectionRequest(const hci::EventPacket& event); @@ -153,13 +153,13 @@ class BrEdrConnectionManager final { // Called once interrogation is complete to establish a BrEdrConnection and, // if in response to an outgoing connection request, completes the request - void EstablishConnection(RemoteDevice* device, hci::Status status, + void EstablishConnection(Peer* peer, hci::Status status, std::unique_ptr<hci::Connection> conn_ptr); - RemoteDevice* FindOrInitDevice(common::DeviceAddress addr); + Peer* FindOrInitPeer(common::DeviceAddress addr); // Called when we complete a pending request. Initiates a new connection - // attempt for the next device in the pending list, if any. + // attempt for the next peer in the pending list, if any. void TryCreateNextConnection(); // Called when a request times out waiting for a connection complete packet, @@ -169,8 +169,7 @@ class BrEdrConnectionManager final { // Cleanup a connection which has been deliberately disconnected, or had all // references to it dropped - void CleanupConnection(hci::ConnectionHandle handle, - BrEdrConnection& conn, + void CleanupConnection(hci::ConnectionHandle handle, BrEdrConnection& conn, bool link_already_closed); using ConnectionMap = @@ -179,10 +178,10 @@ class BrEdrConnectionManager final { fxl::RefPtr<hci::Transport> hci_; std::unique_ptr<hci::SequentialCommandRunner> hci_cmd_runner_; - // Device cache is used to look up parameters for connecting to devices and - // update the state of connected devices as well as introduce unknown devices. + // Peer cache is used to look up parameters for connecting to peers and + // update the state of connected peers as well as introduce unknown peers. // This object must outlive this instance. - RemoteDeviceCache* cache_; + PeerCache* cache_; const common::DeviceAddress local_address_; @@ -215,7 +214,7 @@ class BrEdrConnectionManager final { hci::PageScanType page_scan_type_; bool use_interlaced_scan_; - // Outstanding connection requests based on remote device ID. + // Outstanding connection requests based on remote peer ID. std::unordered_map<DeviceId, ConnectionRequest<BrEdrConnection*>> connection_requests_; diff --git a/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager_unittest.cc index 9778c14411e7b407a21fc4e85a56a51c2f506556..bee1b6714ea16175a14da2027eaef5763ee87b9a 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/bredr_connection_manager_unittest.cc @@ -6,7 +6,7 @@ #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" #include "src/connectivity/bluetooth/core/bt-host/data/fake_domain.h" -#include "src/connectivity/bluetooth/core/bt-host/gap/remote_device_cache.h" +#include "src/connectivity/bluetooth/core/bt-host/gap/peer_cache.h" #include "src/connectivity/bluetooth/core/bt-host/hci/hci.h" #include "src/connectivity/bluetooth/core/bt-host/hci/util.h" #include "src/connectivity/bluetooth/core/bt-host/l2cap/fake_channel.h" @@ -317,13 +317,13 @@ class BrEdrConnectionManagerTest : public TestingBase { TestingBase::SetUp(); InitializeACLDataChannel(); - device_cache_ = std::make_unique<RemoteDeviceCache>(); + peer_cache_ = std::make_unique<PeerCache>(); data_domain_ = data::testing::FakeDomain::Create(); data_domain_->Initialize(); auto hci = transport(); connection_manager_ = std::make_unique<BrEdrConnectionManager>( - hci, device_cache_.get(), kLocalDevAddr, data_domain_, true); + hci, peer_cache_.get(), kLocalDevAddr, data_domain_, true); StartTestDevice(); @@ -345,7 +345,7 @@ class BrEdrConnectionManagerTest : public TestingBase { RunLoopUntilIdle(); test_device()->Stop(); data_domain_ = nullptr; - device_cache_ = nullptr; + peer_cache_ = nullptr; TestingBase::TearDown(); } @@ -357,7 +357,7 @@ class BrEdrConnectionManagerTest : public TestingBase { connection_manager_ = std::move(mgr); } - RemoteDeviceCache* device_cache() const { return device_cache_.get(); } + PeerCache* peer_cache() const { return peer_cache_.get(); } data::testing::FakeDomain* data_domain() const { return data_domain_.get(); } @@ -373,7 +373,7 @@ class BrEdrConnectionManagerTest : public TestingBase { QueueSuccessfulInterrogation(kTestDevAddr, kConnectionHandle); } - void QueueSuccessfulCreateConnection(RemoteDevice* peer, + void QueueSuccessfulCreateConnection(Peer* peer, hci::ConnectionHandle conn) const { const DynamicByteBuffer complete_packet = testing::ConnectionCompletePacket(peer->address(), conn); @@ -421,7 +421,7 @@ class BrEdrConnectionManagerTest : public TestingBase { private: std::unique_ptr<BrEdrConnectionManager> connection_manager_; - std::unique_ptr<RemoteDeviceCache> device_cache_; + std::unique_ptr<PeerCache> peer_cache_; fbl::RefPtr<data::testing::FakeDomain> data_domain_; int transaction_count_ = 0; @@ -499,7 +499,7 @@ TEST_F(GAP_BrEdrConnectionManagerTest, EnableConnectivity) { } // Test: An incoming connection request should trigger an acceptance and -// interrogation should allow a device that only report the first Extended +// interrogation should allow a peer that only report the first Extended // Features page. TEST_F(GAP_BrEdrConnectionManagerTest, IncomingConnection_BrokenExtendedPageResponse) { @@ -556,7 +556,7 @@ TEST_F(GAP_BrEdrConnectionManagerTest, IncomingConnectionSuccess) { RunLoopUntilIdle(); - auto* dev = device_cache()->FindDeviceByAddress(kTestDevAddr); + auto* dev = peer_cache()->FindByAddress(kTestDevAddr); ASSERT_TRUE(dev); EXPECT_EQ(dev->identifier(), connmgr()->GetPeerId(kConnectionHandle)); EXPECT_EQ(kIncomingConnTransactions, transaction_count()); @@ -578,13 +578,13 @@ TEST_F(GAP_BrEdrConnectionManagerTest, IncomingConnectionSuccess) { EXPECT_EQ(kIncomingConnTransactions + 3, transaction_count()); } -// Test: An incoming connection request should upgrade a known LE device with a -// matching address to a dual mode device. +// Test: An incoming connection request should upgrade a known LE peer with a +// matching address to a dual mode peer. TEST_F(GAP_BrEdrConnectionManagerTest, - IncomingConnectionUpgradesKnownLowEnergyDeviceToDualMode) { + IncomingConnectionUpgradesKnownLowEnergyPeerToDualMode) { const DeviceAddress le_alias_addr(DeviceAddress::Type::kLEPublic, kTestDevAddr.value()); - RemoteDevice* const dev = device_cache()->NewDevice(le_alias_addr, true); + Peer* const dev = peer_cache()->NewPeer(le_alias_addr, true); ASSERT_TRUE(dev); ASSERT_EQ(TechnologyType::kLowEnergy, dev->technology()); @@ -594,7 +594,7 @@ TEST_F(GAP_BrEdrConnectionManagerTest, RunLoopUntilIdle(); - ASSERT_EQ(dev, device_cache()->FindDeviceByAddress(kTestDevAddr)); + ASSERT_EQ(dev, peer_cache()->FindByAddress(kTestDevAddr)); EXPECT_EQ(dev->identifier(), connmgr()->GetPeerId(kConnectionHandle)); EXPECT_EQ(TechnologyType::kDualMode, dev->technology()); @@ -610,9 +610,9 @@ TEST_F(GAP_BrEdrConnectionManagerTest, RemoteDisconnect) { test_device()->SendCommandChannelPacket(kConnectionRequest); RunLoopUntilIdle(); - auto* dev = device_cache()->FindDeviceByAddress(kTestDevAddr); - ASSERT_TRUE(dev); - EXPECT_EQ(dev->identifier(), connmgr()->GetPeerId(kConnectionHandle)); + auto* peer = peer_cache()->FindByAddress(kTestDevAddr); + ASSERT_TRUE(peer); + EXPECT_EQ(peer->identifier(), connmgr()->GetPeerId(kConnectionHandle)); EXPECT_EQ(kIncomingConnTransactions, transaction_count()); @@ -762,7 +762,7 @@ const auto kLinkKeyRequestNegativeReplyRsp = TEST_DEV_ADDR_BYTES_LE // peer address ); -// Test: replies negative to Link Key Requests for unknown and unbonded devices +// Test: replies negative to Link Key Requests for unknown and unbonded peers TEST_F(GAP_BrEdrConnectionManagerTest, LinkKeyRequestAndNegativeReply) { test_device()->QueueCommandTransaction(kLinkKeyRequestNegativeReply, {&kLinkKeyRequestNegativeReplyRsp}); @@ -781,10 +781,10 @@ TEST_F(GAP_BrEdrConnectionManagerTest, LinkKeyRequestAndNegativeReply) { EXPECT_EQ(kIncomingConnTransactions + 1, transaction_count()); - auto* dev = device_cache()->FindDeviceByAddress(kTestDevAddr); - ASSERT_TRUE(dev); - ASSERT_TRUE(dev->connected()); - ASSERT_FALSE(dev->bonded()); + auto* peer = peer_cache()->FindByAddress(kTestDevAddr); + ASSERT_TRUE(peer); + ASSERT_TRUE(peer->connected()); + ASSERT_FALSE(peer->bonded()); test_device()->QueueCommandTransaction(kLinkKeyRequestNegativeReply, {&kLinkKeyRequestNegativeReplyRsp}); @@ -829,14 +829,14 @@ const auto kLinkKeyRequestReplyRsp = common::CreateStaticByteBuffer( TEST_DEV_ADDR_BYTES_LE // peer address ); -// Test: replies to Link Key Requests for bonded device -TEST_F(GAP_BrEdrConnectionManagerTest, RecallLinkKeyForBondedDevice) { - ASSERT_TRUE(device_cache()->AddBondedDevice(DeviceId(999), kTestDevAddr, {}, - kLinkKey)); - auto* dev = device_cache()->FindDeviceByAddress(kTestDevAddr); - ASSERT_TRUE(dev); - ASSERT_FALSE(dev->connected()); - ASSERT_TRUE(dev->bonded()); +// Test: replies to Link Key Requests for bonded peer +TEST_F(GAP_BrEdrConnectionManagerTest, RecallLinkKeyForBondedPeer) { + ASSERT_TRUE( + peer_cache()->AddBondedPeer(DeviceId(999), kTestDevAddr, {}, kLinkKey)); + auto* peer = peer_cache()->FindByAddress(kTestDevAddr); + ASSERT_TRUE(peer); + ASSERT_FALSE(peer->connected()); + ASSERT_TRUE(peer->bonded()); QueueSuccessfulIncomingConn(); @@ -845,7 +845,7 @@ TEST_F(GAP_BrEdrConnectionManagerTest, RecallLinkKeyForBondedDevice) { RunLoopUntilIdle(); EXPECT_EQ(kIncomingConnTransactions, transaction_count()); - ASSERT_TRUE(dev->connected()); + ASSERT_TRUE(peer->connected()); test_device()->QueueCommandTransaction(kLinkKeyRequestReply, {&kLinkKeyRequestReplyRsp}); @@ -876,8 +876,8 @@ const auto kLinkKeyRequestReplyChanged = common::CreateStaticByteBuffer( 0x1d, 0x0d, 0x0a, 0xd5 // link key ); -// Test: stores and recalls link key for a remote device -TEST_F(GAP_BrEdrConnectionManagerTest, BondRemoteDevice) { +// Test: stores and recalls link key for a remote peer +TEST_F(GAP_BrEdrConnectionManagerTest, BondPeer) { QueueSuccessfulIncomingConn(); test_device()->SendCommandChannelPacket(kConnectionRequest); @@ -886,15 +886,15 @@ TEST_F(GAP_BrEdrConnectionManagerTest, BondRemoteDevice) { EXPECT_EQ(kIncomingConnTransactions, transaction_count()); - auto* dev = device_cache()->FindDeviceByAddress(kTestDevAddr); - ASSERT_TRUE(dev); - ASSERT_TRUE(dev->connected()); - ASSERT_FALSE(dev->bonded()); + auto* peer = peer_cache()->FindByAddress(kTestDevAddr); + ASSERT_TRUE(peer); + ASSERT_TRUE(peer->connected()); + ASSERT_FALSE(peer->bonded()); test_device()->SendCommandChannelPacket(kLinkKeyNotification); RunLoopUntilIdle(); - EXPECT_TRUE(dev->bonded()); + EXPECT_TRUE(peer->bonded()); test_device()->QueueCommandTransaction(kLinkKeyRequestReply, {&kLinkKeyRequestReplyRsp}); @@ -909,7 +909,7 @@ TEST_F(GAP_BrEdrConnectionManagerTest, BondRemoteDevice) { test_device()->SendCommandChannelPacket(kLinkKeyNotificationChanged); RunLoopUntilIdle(); - EXPECT_TRUE(dev->bonded()); + EXPECT_TRUE(peer->bonded()); test_device()->QueueCommandTransaction(kLinkKeyRequestReplyChanged, {&kLinkKeyRequestReplyRsp}); @@ -918,14 +918,14 @@ TEST_F(GAP_BrEdrConnectionManagerTest, BondRemoteDevice) { RunLoopUntilIdle(); - EXPECT_TRUE(dev->bonded()); + EXPECT_TRUE(peer->bonded()); EXPECT_EQ(kIncomingConnTransactions + 2, transaction_count()); QueueDisconnection(kConnectionHandle); } -// Test: can't change the link key of an unbonded device -TEST_F(GAP_BrEdrConnectionManagerTest, UnbondedDeviceChangeLinkKey) { +// Test: can't change the link key of an unbonded peer +TEST_F(GAP_BrEdrConnectionManagerTest, UnbondedPeerChangeLinkKey) { QueueSuccessfulIncomingConn(); test_device()->SendCommandChannelPacket(kConnectionRequest); @@ -934,16 +934,16 @@ TEST_F(GAP_BrEdrConnectionManagerTest, UnbondedDeviceChangeLinkKey) { EXPECT_EQ(kIncomingConnTransactions, transaction_count()); - auto* dev = device_cache()->FindDeviceByAddress(kTestDevAddr); - ASSERT_TRUE(dev); - ASSERT_TRUE(dev->connected()); - ASSERT_FALSE(dev->bonded()); + auto* peer = peer_cache()->FindByAddress(kTestDevAddr); + ASSERT_TRUE(peer); + ASSERT_TRUE(peer->connected()); + ASSERT_FALSE(peer->bonded()); // Change the link key. test_device()->SendCommandChannelPacket(kLinkKeyNotificationChanged); RunLoopUntilIdle(); - EXPECT_FALSE(dev->bonded()); + EXPECT_FALSE(peer->bonded()); test_device()->QueueCommandTransaction(kLinkKeyRequestNegativeReply, {&kLinkKeyRequestReplyRsp}); @@ -952,7 +952,7 @@ TEST_F(GAP_BrEdrConnectionManagerTest, UnbondedDeviceChangeLinkKey) { RunLoopUntilIdle(); - EXPECT_FALSE(dev->bonded()); + EXPECT_FALSE(peer->bonded()); EXPECT_EQ(kIncomingConnTransactions + 1, transaction_count()); QueueDisconnection(kConnectionHandle); @@ -977,15 +977,15 @@ TEST_F(GAP_BrEdrConnectionManagerTest, LegacyLinkKeyNotBonded) { EXPECT_EQ(kIncomingConnTransactions, transaction_count()); - auto* dev = device_cache()->FindDeviceByAddress(kTestDevAddr); - ASSERT_TRUE(dev); - ASSERT_TRUE(dev->connected()); - ASSERT_FALSE(dev->bonded()); + auto* peer = peer_cache()->FindByAddress(kTestDevAddr); + ASSERT_TRUE(peer); + ASSERT_TRUE(peer->connected()); + ASSERT_FALSE(peer->bonded()); test_device()->SendCommandChannelPacket(kLinkKeyNotificationLegacy); RunLoopUntilIdle(); - EXPECT_FALSE(dev->bonded()); + EXPECT_FALSE(peer->bonded()); test_device()->QueueCommandTransaction(kLinkKeyRequestNegativeReply, {&kLinkKeyRequestReplyRsp}); @@ -994,7 +994,7 @@ TEST_F(GAP_BrEdrConnectionManagerTest, LegacyLinkKeyNotBonded) { RunLoopUntilIdle(); - EXPECT_FALSE(dev->bonded()); + EXPECT_FALSE(peer->bonded()); EXPECT_EQ(kIncomingConnTransactions + 1, transaction_count()); QueueDisconnection(kConnectionHandle); @@ -1031,7 +1031,7 @@ TEST_F(GAP_BrEdrConnectionManagerTest, DisconnectOnLinkError) { EXPECT_EQ(kIncomingConnTransactions + 3, transaction_count()); } -TEST_F(GAP_BrEdrConnectionManagerTest, ConnectedDeviceTimeout) { +TEST_F(GAP_BrEdrConnectionManagerTest, ConnectedPeerTimeout) { QueueSuccessfulIncomingConn(); test_device()->SendCommandChannelPacket(kConnectionRequest); @@ -1040,9 +1040,9 @@ TEST_F(GAP_BrEdrConnectionManagerTest, ConnectedDeviceTimeout) { EXPECT_EQ(kIncomingConnTransactions, transaction_count()); - auto* dev = device_cache()->FindDeviceByAddress(kTestDevAddr); - ASSERT_TRUE(dev); - EXPECT_TRUE(dev->connected()); + auto* peer = peer_cache()->FindByAddress(kTestDevAddr); + ASSERT_TRUE(peer); + EXPECT_TRUE(peer->connected()); // We want to make sure the connection doesn't expire. RunLoopFor(zx::sec(600)); @@ -1052,19 +1052,19 @@ TEST_F(GAP_BrEdrConnectionManagerTest, ConnectedDeviceTimeout) { RunLoopUntilIdle(); - // Device should still be there, but not connected anymore - dev = device_cache()->FindDeviceByAddress(kTestDevAddr); - ASSERT_TRUE(dev); - EXPECT_FALSE(dev->connected()); + // Peer should still be there, but not connected anymore + peer = peer_cache()->FindByAddress(kTestDevAddr); + ASSERT_TRUE(peer); + EXPECT_FALSE(peer->connected()); EXPECT_EQ(kInvalidDeviceId, connmgr()->GetPeerId(kConnectionHandle)); } TEST_F(GAP_BrEdrConnectionManagerTest, ServiceSearch) { size_t search_cb_count = 0; auto search_cb = [&](auto id, const auto& attributes) { - auto* dev = device_cache()->FindDeviceByAddress(kTestDevAddr); - ASSERT_TRUE(dev); - ASSERT_EQ(id, dev->identifier()); + auto* peer = peer_cache()->FindByAddress(kTestDevAddr); + ASSERT_TRUE(peer); + ASSERT_EQ(id, peer->identifier()); ASSERT_EQ(1u, attributes.count(sdp::kServiceId)); search_cb_count++; }; @@ -1154,13 +1154,13 @@ TEST_F(GAP_BrEdrConnectionManagerTest, ServiceSearch) { QueueDisconnection(kConnectionHandle); } -TEST_F(GAP_BrEdrConnectionManagerTest, ConnectUnknownDevice) { +TEST_F(GAP_BrEdrConnectionManagerTest, ConnectUnknownPeer) { EXPECT_FALSE(connmgr()->Connect(DeviceId(456), {})); } -TEST_F(GAP_BrEdrConnectionManagerTest, ConnectLowEnergyDevice) { - auto* dev = device_cache()->NewDevice(kTestDevAddrLe, true); - EXPECT_FALSE(connmgr()->Connect(dev->identifier(), {})); +TEST_F(GAP_BrEdrConnectionManagerTest, ConnectLowEnergyPeer) { + auto* peer = peer_cache()->NewPeer(kTestDevAddrLe, true); + EXPECT_FALSE(connmgr()->Connect(peer->identifier(), {})); } // Test: user-initiated disconnection @@ -1171,35 +1171,35 @@ TEST_F(GAP_BrEdrConnectionManagerTest, DisconnectClosesHciConnection) { RunLoopUntilIdle(); - // Disconnecting an unknown device should do nothing. + // Disconnecting an unknown peer should do nothing. EXPECT_FALSE(connmgr()->Disconnect(DeviceId(999))); RunLoopUntilIdle(); EXPECT_EQ(kIncomingConnTransactions, transaction_count()); - auto* const dev = device_cache()->FindDeviceByAddress(kTestDevAddr); - ASSERT_TRUE(dev); - ASSERT_TRUE(dev->bredr()->connected()); + auto* const peer = peer_cache()->FindByAddress(kTestDevAddr); + ASSERT_TRUE(peer); + ASSERT_TRUE(peer->bredr()->connected()); QueueDisconnection(kConnectionHandle); - EXPECT_TRUE(connmgr()->Disconnect(dev->identifier())); + EXPECT_TRUE(connmgr()->Disconnect(peer->identifier())); RunLoopUntilIdle(); EXPECT_EQ(kIncomingConnTransactions + 1, transaction_count()); - EXPECT_FALSE(dev->bredr()->connected()); + EXPECT_FALSE(peer->bredr()->connected()); // Disconnecting a closed connection returns false. - EXPECT_FALSE(connmgr()->Disconnect(dev->identifier())); + EXPECT_FALSE(connmgr()->Disconnect(peer->identifier())); } TEST_F(GAP_BrEdrConnectionManagerTest, AddServiceSearchAll) { size_t search_cb_count = 0; auto search_cb = [&](auto id, const auto&) { - auto* dev = device_cache()->FindDeviceByAddress(kTestDevAddr); - ASSERT_TRUE(dev); - ASSERT_EQ(id, dev->identifier()); + auto* peer = peer_cache()->FindByAddress(kTestDevAddr); + ASSERT_TRUE(peer); + ASSERT_EQ(id, peer->identifier()); search_cb_count++; }; @@ -1258,59 +1258,57 @@ TEST_F(GAP_BrEdrConnectionManagerTest, AddServiceSearchAll) { QueueDisconnection(kConnectionHandle); } -std::string FormatConnectionState(RemoteDevice::ConnectionState s) { +std::string FormatConnectionState(Peer::ConnectionState s) { switch (s) { - case RemoteDevice::ConnectionState::kConnected: + case Peer::ConnectionState::kConnected: return "kConnected"; - case RemoteDevice::ConnectionState::kInitializing: + case Peer::ConnectionState::kInitializing: return "kInitializing"; - case RemoteDevice::ConnectionState::kNotConnected: + case Peer::ConnectionState::kNotConnected: return "kNotConnected"; } return "<Invalid state>"; } -::testing::AssertionResult IsInitializing(RemoteDevice* dev) { - if (RemoteDevice::ConnectionState::kInitializing != - dev->bredr()->connection_state()) { +::testing::AssertionResult IsInitializing(Peer* peer) { + if (Peer::ConnectionState::kInitializing != + peer->bredr()->connection_state()) { return ::testing::AssertionFailure() - << "Expected device connection_state: kInitializing, found " - << FormatConnectionState(dev->bredr()->connection_state()); + << "Expected peer connection_state: kInitializing, found " + << FormatConnectionState(peer->bredr()->connection_state()); } return ::testing::AssertionSuccess(); } -::testing::AssertionResult IsConnected(RemoteDevice* dev) { - if (RemoteDevice::ConnectionState::kConnected != - dev->bredr()->connection_state()) { +::testing::AssertionResult IsConnected(Peer* peer) { + if (Peer::ConnectionState::kConnected != peer->bredr()->connection_state()) { return ::testing::AssertionFailure() - << "Expected device connection_state: kConnected, found " - << FormatConnectionState(dev->bredr()->connection_state()); + << "Expected peer connection_state: kConnected, found " + << FormatConnectionState(peer->bredr()->connection_state()); } - if (dev->temporary()) { + if (peer->temporary()) { return ::testing::AssertionFailure() - << "Expected device to be non-temporary, but found temporary"; + << "Expected peer to be non-temporary, but found temporary"; } return ::testing::AssertionSuccess(); } -::testing::AssertionResult NotConnected(RemoteDevice* dev) { - if (RemoteDevice::ConnectionState::kNotConnected != - dev->bredr()->connection_state()) { +::testing::AssertionResult NotConnected(Peer* peer) { + if (Peer::ConnectionState::kNotConnected != + peer->bredr()->connection_state()) { return ::testing::AssertionFailure() - << "Expected device connection_state: kNotConnected, found " - << FormatConnectionState(dev->bredr()->connection_state()); + << "Expected peer connection_state: kNotConnected, found " + << FormatConnectionState(peer->bredr()->connection_state()); } return ::testing::AssertionSuccess(); } -::testing::AssertionResult HasConnectionTo(RemoteDevice* dev, - BrEdrConnection* conn) { +::testing::AssertionResult HasConnectionTo(Peer* peer, BrEdrConnection* conn) { if (!conn) { return ::testing::AssertionFailure() << "Expected BrEdrConnection, but found nullptr"; } - if (dev->identifier() != conn->peer_id()) { + if (peer->identifier() != conn->peer_id()) { return ::testing::AssertionFailure() - << "Expected connection peer_id " << bt_str(dev->identifier()) + << "Expected connection peer_id " << bt_str(peer->identifier()) << " but found " << bt_str(conn->peer_id()); } return ::testing::AssertionSuccess(); @@ -1323,25 +1321,25 @@ std::string FormatConnectionState(RemoteDevice::ConnectionState s) { }) // An error is received via the HCI Command cb_status event -TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSingleDeviceErrorStatus) { - auto* dev = device_cache()->NewDevice(kTestDevAddr, true); +TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSinglePeerErrorStatus) { + auto* peer = peer_cache()->NewPeer(kTestDevAddr, true); test_device()->QueueCommandTransaction( CommandTransaction(kCreateConnection, {&kCreateConnectionRspError})); - ASSERT_TRUE(dev->bredr()); - EXPECT_TRUE(NotConnected(dev)); + ASSERT_TRUE(peer->bredr()); + EXPECT_TRUE(NotConnected(peer)); hci::Status status; EXPECT_TRUE( - connmgr()->Connect(dev->identifier(), CALLBACK_EXPECT_FAILURE(status))); - EXPECT_TRUE(IsInitializing(dev)); + connmgr()->Connect(peer->identifier(), CALLBACK_EXPECT_FAILURE(status))); + EXPECT_TRUE(IsInitializing(peer)); RunLoopUntilIdle(); EXPECT_TRUE(status.is_protocol_error()); EXPECT_EQ(hci::StatusCode::kConnectionFailedToBeEstablished, status.protocol_error()); - EXPECT_TRUE(NotConnected(dev)); + EXPECT_TRUE(NotConnected(peer)); } ::testing::AssertionResult StatusEqual(hci::StatusCode expected, @@ -1355,8 +1353,8 @@ TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSingleDeviceErrorStatus) { } // Connection Complete event reports error -TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSingleDeviceFailure) { - auto* dev = device_cache()->NewDevice(kTestDevAddr, true); +TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSinglePeerFailure) { + auto* peer = peer_cache()->NewPeer(kTestDevAddr, true); test_device()->QueueCommandTransaction(CommandTransaction( kCreateConnection, {&kCreateConnectionRsp, &kConnectionCompleteError})); @@ -1369,9 +1367,9 @@ TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSingleDeviceFailure) { status = cb_status; callback_run = true; }; - EXPECT_TRUE(connmgr()->Connect(dev->identifier(), callback)); - ASSERT_TRUE(dev->bredr()); - EXPECT_TRUE(IsInitializing(dev)); + EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback)); + ASSERT_TRUE(peer->bredr()); + EXPECT_TRUE(IsInitializing(peer)); RunLoopUntilIdle(); @@ -1380,11 +1378,11 @@ TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSingleDeviceFailure) { EXPECT_TRUE(status.is_protocol_error()); EXPECT_TRUE(StatusEqual(hci::StatusCode::kConnectionFailedToBeEstablished, status.protocol_error())); - EXPECT_TRUE(NotConnected(dev)); + EXPECT_TRUE(NotConnected(peer)); } -TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSingleDeviceTimeout) { - auto* dev = device_cache()->NewDevice(kTestDevAddr, true); +TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSinglePeerTimeout) { + auto* peer = peer_cache()->NewPeer(kTestDevAddr, true); test_device()->QueueCommandTransaction( CommandTransaction(kCreateConnection, {&kCreateConnectionRsp})); @@ -1398,25 +1396,25 @@ TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSingleDeviceTimeout) { status = cb_status; }; - EXPECT_TRUE(connmgr()->Connect(dev->identifier(), callback)); - ASSERT_TRUE(dev->bredr()); - EXPECT_TRUE(IsInitializing(dev)); + EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback)); + ASSERT_TRUE(peer->bredr()); + EXPECT_TRUE(IsInitializing(peer)); RunLoopFor(kBrEdrCreateConnectionTimeout); RunLoopFor(kBrEdrCreateConnectionTimeout); EXPECT_FALSE(status); EXPECT_EQ(common::HostError::kTimedOut, status.error()) << status.ToString(); - EXPECT_TRUE(NotConnected(dev)); + EXPECT_TRUE(NotConnected(peer)); } -// Successful connection to single device -TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSingleDevice) { - auto* dev = device_cache()->NewDevice(kTestDevAddr, true); - EXPECT_TRUE(dev->temporary()); +// Successful connection to single peer +TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSinglePeer) { + auto* peer = peer_cache()->NewPeer(kTestDevAddr, true); + EXPECT_TRUE(peer->temporary()); // Queue up the connection test_device()->QueueCommandTransaction(CommandTransaction( kCreateConnection, {&kCreateConnectionRsp, &kConnectionComplete})); - QueueSuccessfulInterrogation(dev->address(), kConnectionHandle); + QueueSuccessfulInterrogation(peer->address(), kConnectionHandle); QueueDisconnection(kConnectionHandle); // Initialize as error to verify that |callback| assigns success. @@ -1428,25 +1426,25 @@ TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSingleDevice) { conn_ref = std::move(cb_conn_ref); }; - EXPECT_TRUE(connmgr()->Connect(dev->identifier(), callback)); - ASSERT_TRUE(dev->bredr()); - EXPECT_TRUE(IsInitializing(dev)); + EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback)); + ASSERT_TRUE(peer->bredr()); + EXPECT_TRUE(IsInitializing(peer)); RunLoopUntilIdle(); EXPECT_TRUE(status); EXPECT_EQ(status.ToString(), hci::Status().ToString()); - EXPECT_TRUE(HasConnectionTo(dev, conn_ref)); - EXPECT_TRUE(IsConnected(dev)); + EXPECT_TRUE(HasConnectionTo(peer, conn_ref)); + EXPECT_TRUE(IsConnected(peer)); } -// Connecting to an already connected device should complete instantly -TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSingleDeviceAlreadyConnected) { - auto* dev = device_cache()->NewDevice(kTestDevAddr, true); - EXPECT_TRUE(dev->temporary()); +// Connecting to an already connected peer should complete instantly +TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSinglePeerAlreadyConnected) { + auto* peer = peer_cache()->NewPeer(kTestDevAddr, true); + EXPECT_TRUE(peer->temporary()); // Queue up the connection test_device()->QueueCommandTransaction(CommandTransaction( kCreateConnection, {&kCreateConnectionRsp, &kConnectionComplete})); - QueueSuccessfulInterrogation(dev->address(), kConnectionHandle); + QueueSuccessfulInterrogation(peer->address(), kConnectionHandle); QueueDisconnection(kConnectionHandle); // Initialize as error to verify that |callback| assigns success. @@ -1461,37 +1459,37 @@ TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSingleDeviceAlreadyConnected) { ++num_callbacks; }; - // Connect to the device for the first time - EXPECT_TRUE(connmgr()->Connect(dev->identifier(), callback)); - ASSERT_TRUE(dev->bredr()); - EXPECT_TRUE(IsInitializing(dev)); + // Connect to the peer for the first time + EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback)); + ASSERT_TRUE(peer->bredr()); + EXPECT_TRUE(IsInitializing(peer)); RunLoopUntilIdle(); EXPECT_TRUE(status); EXPECT_EQ(status.ToString(), hci::Status().ToString()); - EXPECT_TRUE(HasConnectionTo(dev, conn_ref)); - EXPECT_TRUE(IsConnected(dev)); + EXPECT_TRUE(HasConnectionTo(peer, conn_ref)); + EXPECT_TRUE(IsConnected(peer)); EXPECT_EQ(num_callbacks, 1); - // Attempt to connect again to the already connected device - EXPECT_TRUE(connmgr()->Connect(dev->identifier(), callback)); + // Attempt to connect again to the already connected peer + EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback)); RunLoopUntilIdle(); EXPECT_EQ(num_callbacks, 2); EXPECT_TRUE(status); EXPECT_EQ(status.ToString(), hci::Status().ToString()); - EXPECT_TRUE(HasConnectionTo(dev, conn_ref)); - EXPECT_TRUE(IsConnected(dev)); + EXPECT_TRUE(HasConnectionTo(peer, conn_ref)); + EXPECT_TRUE(IsConnected(peer)); } -// Initiating Two Connections to the same (currently unconnected) device should +// Initiating Two Connections to the same (currently unconnected) peer should // successfully establish both -TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSingleDeviceTwoInFlight) { - auto* dev = device_cache()->NewDevice(kTestDevAddr, true); - EXPECT_TRUE(dev->temporary()); +TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSinglePeerTwoInFlight) { + auto* peer = peer_cache()->NewPeer(kTestDevAddr, true); + EXPECT_TRUE(peer->temporary()); // Queue up the connection test_device()->QueueCommandTransaction(CommandTransaction( kCreateConnection, {&kCreateConnectionRsp, &kConnectionComplete})); - QueueSuccessfulInterrogation(dev->address(), kConnectionHandle); + QueueSuccessfulInterrogation(peer->address(), kConnectionHandle); QueueDisconnection(kConnectionHandle); // Initialize as error to verify that |callback| assigns success. @@ -1507,26 +1505,26 @@ TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSingleDeviceTwoInFlight) { }; // Launch one request, but don't run the loop - EXPECT_TRUE(connmgr()->Connect(dev->identifier(), callback)); - ASSERT_TRUE(dev->bredr()); - EXPECT_TRUE(IsInitializing(dev)); + EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback)); + ASSERT_TRUE(peer->bredr()); + EXPECT_TRUE(IsInitializing(peer)); // Launch second inflight request - EXPECT_TRUE(connmgr()->Connect(dev->identifier(), callback)); + EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback)); // Run the loop which should complete both requests RunLoopUntilIdle(); EXPECT_TRUE(status); EXPECT_EQ(status.ToString(), hci::Status().ToString()); - EXPECT_TRUE(HasConnectionTo(dev, conn_ref)); - EXPECT_TRUE(IsConnected(dev)); + EXPECT_TRUE(HasConnectionTo(peer, conn_ref)); + EXPECT_TRUE(IsConnected(peer)); EXPECT_EQ(num_callbacks, 2); } -TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSecondDeviceFirstTimesOut) { - auto* peer_a = device_cache()->NewDevice(kTestDevAddr, true); - auto* peer_b = device_cache()->NewDevice(kTestDevAddr2, true); +TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSecondPeerFirstTimesOut) { + auto* peer_a = peer_cache()->NewPeer(kTestDevAddr, true); + auto* peer_b = peer_cache()->NewPeer(kTestDevAddr2, true); // Enqueue first connection request (which will timeout and be cancelled) test_device()->QueueCommandTransaction( @@ -1580,7 +1578,7 @@ TEST_F(GAP_BrEdrConnectionManagerTest, ConnectSecondDeviceFirstTimesOut) { EXPECT_TRUE(IsConnected(peer_b)); } -// TODO(BT-819) Connecting a device that's being interrogated +// TODO(BT-819) Connecting a peer that's being interrogated #undef COMMAND_COMPLETE_RSP #undef COMMAND_STATUS_RSP diff --git a/src/connectivity/bluetooth/core/bt-host/gap/bredr_discovery_manager.cc b/src/connectivity/bluetooth/core/bt-host/gap/bredr_discovery_manager.cc index 1453edfb0c74e7a43d83586e09b69c4637053c9a..d703dd36d46af1263ebe380c0f24602e9ed355e3 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/bredr_discovery_manager.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/bredr_discovery_manager.cc @@ -9,7 +9,7 @@ #include <zircon/assert.h> #include "src/connectivity/bluetooth/core/bt-host/common/log.h" -#include "src/connectivity/bluetooth/core/bt-host/gap/remote_device_cache.h" +#include "src/connectivity/bluetooth/core/bt-host/gap/peer_cache.h" #include "src/connectivity/bluetooth/core/bt-host/hci/transport.h" #include "src/connectivity/bluetooth/core/bt-host/hci/util.h" @@ -19,9 +19,9 @@ namespace gap { namespace { template <typename EventParamType, typename ResultType> -std::unordered_set<RemoteDevice*> ProcessInquiryResult( - RemoteDeviceCache* cache, const hci::EventPacket& event) { - std::unordered_set<RemoteDevice*> updated; +std::unordered_set<Peer*> ProcessInquiryResult(PeerCache* cache, + const hci::EventPacket& event) { + std::unordered_set<Peer*> updated; bt_log(SPEW, "gap-bredr", "inquiry result received"); size_t result_size = event.view().payload_size() - sizeof(EventParamType); @@ -35,14 +35,14 @@ std::unordered_set<RemoteDevice*> ProcessInquiryResult( for (int i = 0; i < result.num_responses; i++) { common::DeviceAddress addr(common::DeviceAddress::Type::kBREDR, result.responses[i].bd_addr); - RemoteDevice* device = cache->FindDeviceByAddress(addr); - if (!device) { - device = cache->NewDevice(addr, true); + Peer* peer = cache->FindByAddress(addr); + if (!peer) { + peer = cache->NewPeer(addr, true); } - ZX_DEBUG_ASSERT(device); + ZX_DEBUG_ASSERT(peer); - device->MutBrEdr().SetInquiryData(result.responses[i]); - updated.insert(device); + peer->MutBrEdr().SetInquiryData(result.responses[i]); + updated.insert(peer); } return updated; } @@ -58,10 +58,9 @@ BrEdrDiscoverySession::~BrEdrDiscoverySession() { manager_->RemoveDiscoverySession(this); } -void BrEdrDiscoverySession::NotifyDiscoveryResult( - const RemoteDevice& device) const { - if (device_found_callback_) { - device_found_callback_(device); +void BrEdrDiscoverySession::NotifyDiscoveryResult(const Peer& peer) const { + if (peer_found_callback_) { + peer_found_callback_(peer); } } @@ -82,10 +81,10 @@ BrEdrDiscoverableSession::~BrEdrDiscoverableSession() { BrEdrDiscoveryManager::BrEdrDiscoveryManager(fxl::RefPtr<hci::Transport> hci, hci::InquiryMode mode, - RemoteDeviceCache* device_cache) + PeerCache* peer_cache) : hci_(hci), dispatcher_(async_get_default_dispatcher()), - cache_(device_cache), + cache_(peer_cache), result_handler_id_(0u), desired_inquiry_mode_(mode), current_inquiry_mode_(hci::InquiryMode::kStandard), @@ -241,25 +240,25 @@ void BrEdrDiscoveryManager::StopInquiry() { } void BrEdrDiscoveryManager::InquiryResult(const hci::EventPacket& event) { - std::unordered_set<RemoteDevice*> devices; + std::unordered_set<Peer*> peers; if (event.event_code() == hci::kInquiryResultEventCode) { - devices = + peers = ProcessInquiryResult<hci::InquiryResultEventParams, hci::InquiryResult>( cache_, event); } else if (event.event_code() == hci::kInquiryResultWithRSSIEventCode) { - devices = ProcessInquiryResult<hci::InquiryResultWithRSSIEventParams, - hci::InquiryResultRSSI>(cache_, event); + peers = ProcessInquiryResult<hci::InquiryResultWithRSSIEventParams, + hci::InquiryResultRSSI>(cache_, event); } else { bt_log(ERROR, "gap-bredr", "unsupported inquiry result type"); return; } - for (RemoteDevice* device : devices) { - if (!device->name()) { - RequestRemoteDeviceName(device->identifier()); + for (Peer* peer : peers) { + if (!peer->name()) { + RequestPeerName(peer->identifier()); } for (const auto& session : discovering_) { - session->NotifyDiscoveryResult(*device); + session->NotifyDiscoveryResult(*peer); } } } @@ -280,29 +279,29 @@ void BrEdrDiscoveryManager::ExtendedInquiryResult( common::DeviceAddress addr(common::DeviceAddress::Type::kBREDR, result.bd_addr); - RemoteDevice* device = cache_->FindDeviceByAddress(addr); - if (!device) { - device = cache_->NewDevice(addr, true); + Peer* peer = cache_->FindByAddress(addr); + if (!peer) { + peer = cache_->NewPeer(addr, true); } - ZX_DEBUG_ASSERT(device); + ZX_DEBUG_ASSERT(peer); - device->MutBrEdr().SetInquiryData(result); + peer->MutBrEdr().SetInquiryData(result); - if (!device->name()) { - RequestRemoteDeviceName(device->identifier()); + if (!peer->name()) { + RequestPeerName(peer->identifier()); } for (const auto& session : discovering_) { - session->NotifyDiscoveryResult(*device); + session->NotifyDiscoveryResult(*peer); } } -void BrEdrDiscoveryManager::RequestRemoteDeviceName(DeviceId id) { +void BrEdrDiscoveryManager::RequestPeerName(DeviceId id) { if (requesting_names_.count(id)) { bt_log(SPEW, "gap-bredr", "already requesting name for %s", bt_str(id)); return; } - RemoteDevice* device = cache_->FindDeviceById(id); - if (!device) { + Peer* peer = cache_->FindById(id); + if (!peer) { bt_log(WARN, "gap-bredr", "cannot request name, unknown id: %s", bt_str(id)); return; @@ -312,13 +311,13 @@ void BrEdrDiscoveryManager::RequestRemoteDeviceName(DeviceId id) { packet->mutable_view()->mutable_payload_data().SetToZeros(); auto params = packet->mutable_view() ->mutable_payload<hci::RemoteNameRequestCommandParams>(); - ZX_DEBUG_ASSERT(device->bredr()); - ZX_DEBUG_ASSERT(device->bredr()->page_scan_repetition_mode()); - params->bd_addr = device->address().value(); + ZX_DEBUG_ASSERT(peer->bredr()); + ZX_DEBUG_ASSERT(peer->bredr()->page_scan_repetition_mode()); + params->bd_addr = peer->address().value(); params->page_scan_repetition_mode = - *(device->bredr()->page_scan_repetition_mode()); - if (device->bredr()->clock_offset()) { - params->clock_offset = htole16(*(device->bredr()->clock_offset())); + *(peer->bredr()->page_scan_repetition_mode()); + if (peer->bredr()->clock_offset()) { + params->clock_offset = htole16(*(peer->bredr()->clock_offset())); } auto cb = [id, self = weak_ptr_factory_.GetWeakPtr()](auto, @@ -344,9 +343,9 @@ void BrEdrDiscoveryManager::RequestRemoteDeviceName(DeviceId id) { .template payload<hci::RemoteNameRequestCompleteEventParams>(); for (size_t len = 0; len <= hci::kMaxNameLength; len++) { if (params.remote_name[len] == 0 || len == hci::kMaxNameLength) { - RemoteDevice* device = self->cache_->FindDeviceById(id); - if (device) { - device->SetName( + Peer* peer = self->cache_->FindById(id); + if (peer) { + peer->SetName( std::string(params.remote_name, params.remote_name + len)); } return; diff --git a/src/connectivity/bluetooth/core/bt-host/gap/bredr_discovery_manager.h b/src/connectivity/bluetooth/core/bt-host/gap/bredr_discovery_manager.h index c596d3319390ea933a47c570c7fc7ec540cb26cb..b3ea75cb5c16503519e01225cbdbe9a0204f2f2c 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/bredr_discovery_manager.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/bredr_discovery_manager.h @@ -12,7 +12,7 @@ #include <queue> #include <unordered_set> -#include "src/connectivity/bluetooth/core/bt-host/gap/remote_device.h" +#include "src/connectivity/bluetooth/core/bt-host/gap/peer.h" #include "src/connectivity/bluetooth/core/bt-host/hci/command_channel.h" #include "src/connectivity/bluetooth/core/bt-host/hci/control_packets.h" #include "src/lib/fxl/memory/weak_ptr.h" @@ -26,11 +26,11 @@ class Transport; namespace gap { class BrEdrDiscoveryManager; -class RemoteDeviceCache; +class PeerCache; -// BrEdrDiscoveryManager implements discovery for BR/EDR devices. We provide a -// mechanism for multiple clients to simultaneously request discovery. Devices -// discovered will be added to the RemoteDeviceCache. +// BrEdrDiscoveryManager implements discovery for BR/EDR peers. We provide a +// mechanism for multiple clients to simultaneously request discovery. Peers +// discovered will be added to the PeerCache. // // Only one instance of BrEdrDiscoveryManager should be created for a bt-host. // @@ -52,10 +52,10 @@ class BrEdrDiscoverySession final { // Set a result callback that will be notified whenever a result is returned // from the controller. You will get duplicate results when using this // method. - // Prefer RemoteDeviceCache.set_device_updated_callback() instead. - using DeviceFoundCallback = fit::function<void(const RemoteDevice& device)>; - void set_result_callback(DeviceFoundCallback callback) { - device_found_callback_ = std::move(callback); + // Prefer PeerCache.set_peer_updated_callback() instead. + using PeerFoundCallback = fit::function<void(const Peer& peer)>; + void set_result_callback(PeerFoundCallback callback) { + peer_found_callback_ = std::move(callback); } // Set a callback to be notified if the session becomes inactive because @@ -70,15 +70,15 @@ class BrEdrDiscoverySession final { // Used by the BrEdrDiscoveryManager to create a session. explicit BrEdrDiscoverySession(fxl::WeakPtr<BrEdrDiscoveryManager> manager); - // Called by the BrEdrDiscoveryManager when a device report is found. - void NotifyDiscoveryResult(const RemoteDevice& device) const; + // Called by the BrEdrDiscoveryManager when a peer report is found. + void NotifyDiscoveryResult(const Peer& peer) const; // Marks this session as ended because of an error. void NotifyError() const; fxl::WeakPtr<BrEdrDiscoveryManager> manager_; fit::closure error_callback_; - DeviceFoundCallback device_found_callback_; + PeerFoundCallback peer_found_callback_; fxl::ThreadChecker thread_checker_; DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(BrEdrDiscoverySession); @@ -87,7 +87,7 @@ class BrEdrDiscoverySession final { class BrEdrDiscoverableSession final { public: // Destroying a session instance relinquishes the request. - // The device may still be discoverable if others are requesting so. + // The peer may still be discoverable if others are requesting so. ~BrEdrDiscoverableSession(); private: @@ -105,15 +105,15 @@ class BrEdrDiscoverableSession final { class BrEdrDiscoveryManager final { public: - // |device_cache| MUST out-live this BrEdrDiscoveryManager. + // |peer_cache| MUST out-live this BrEdrDiscoveryManager. BrEdrDiscoveryManager(fxl::RefPtr<hci::Transport> hci, hci::InquiryMode mode, - RemoteDeviceCache* device_cache); + PeerCache* peer_cache); ~BrEdrDiscoveryManager(); // Starts discovery and reports the status via |callback|. If discovery has // been successfully started, the callback will receive a session object that - // it owns. If no sessions are owned, device discovery is stopped. + // it owns. If no sessions are owned, peer discovery is stopped. using DiscoveryCallback = fit::function<void(const hci::Status& status, std::unique_ptr<BrEdrDiscoverySession> session)>; @@ -122,7 +122,7 @@ class BrEdrDiscoveryManager final { // Returns whether a discovery session is active. bool discovering() const { return !discovering_.empty(); } - // Requests this device be discoverable. Devices are discoverable as long as + // Requests this device be discoverable. We are discoverable as long as // anyone holds a discoverable session. using DiscoverableCallback = fit::function<void(const hci::Status& status, @@ -172,8 +172,8 @@ class BrEdrDiscoveryManager final { // Removes |session_| from the active sessions. void RemoveDiscoverableSession(BrEdrDiscoverableSession* session); - // Sends a RemoteNameRequest to the device with |id|. - void RequestRemoteDeviceName(DeviceId id); + // Sends a RemoteNameRequest to the peer with |id|. + void RequestPeerName(DeviceId id); // The HCI Transport fxl::RefPtr<hci::Transport> hci_; @@ -181,9 +181,9 @@ class BrEdrDiscoveryManager final { // The dispatcher that we use for invoking callbacks asynchronously. async_dispatcher_t* dispatcher_; - // Device cache to use. + // Peer cache to use. // We hold a raw pointer is because it must out-live us. - RemoteDeviceCache* cache_; + PeerCache* cache_; // The list of discovering sessions. We store raw pointers here as we // don't own the sessions. Sessions notify us when they are destroyed to @@ -196,7 +196,7 @@ class BrEdrDiscoveryManager final { // TODO(NET-619): we should not need these once we can Inquiry Cancel. std::unordered_set<BrEdrDiscoverySession*> zombie_discovering_; - // The set of devices that we have pending name requests for. + // The set of peers that we have pending name requests for. std::unordered_set<DeviceId> requesting_names_; // The set of callbacks that are waiting on inquiry to start. diff --git a/src/connectivity/bluetooth/core/bt-host/gap/bredr_discovery_manager_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gap/bredr_discovery_manager_unittest.cc index 80e296a2a089aade90d36b049c3542c0165ea962..32e131603c2fcf37ece1752687b73a34b0461d8f 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/bredr_discovery_manager_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/bredr_discovery_manager_unittest.cc @@ -5,7 +5,7 @@ #include "src/connectivity/bluetooth/core/bt-host/gap/bredr_discovery_manager.h" #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" -#include "src/connectivity/bluetooth/core/bt-host/gap/remote_device_cache.h" +#include "src/connectivity/bluetooth/core/bt-host/gap/peer_cache.h" #include "src/connectivity/bluetooth/core/bt-host/hci/hci.h" #include "src/connectivity/bluetooth/core/bt-host/testing/fake_controller_test.h" #include "src/connectivity/bluetooth/core/bt-host/testing/test_controller.h" @@ -82,12 +82,12 @@ class BrEdrDiscoveryManagerTest : public TestingBase { CommandTransaction(kWriteInquiryType, {&kWriteInquiryTypeRsp})); discovery_manager_ = std::make_unique<BrEdrDiscoveryManager>( - transport(), mode, &device_cache_); + transport(), mode, &peer_cache_); RunLoopUntilIdle(); } - RemoteDeviceCache* device_cache() { return &device_cache_; } + PeerCache* peer_cache() { return &peer_cache_; } protected: BrEdrDiscoveryManager* discovery_manager() const { @@ -95,7 +95,7 @@ class BrEdrDiscoveryManagerTest : public TestingBase { } private: - RemoteDeviceCache device_cache_; + PeerCache peer_cache_; std::unique_ptr<BrEdrDiscoveryManager> discovery_manager_; DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(BrEdrDiscoveryManagerTest); @@ -291,7 +291,7 @@ const auto kWriteScanEnableRsp = COMMAND_COMPLETE_RSP(hci::kWriteScanEnable); // Test: requesting discovery should start inquiry // Test: Inquiry Results that come in when there is discovery get reported up // correctly to the sessions -// Test: Devices discovered are reported to the cache +// Test: Peers discovered are reported to the cache // Test: Inquiry Results that come in when there's no discovery happening get // discarded. TEST_F(GAP_BrEdrDiscoveryManagerTest, RequestDiscoveryAndDrop) { @@ -302,13 +302,13 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, RequestDiscoveryAndDrop) { {&kRemoteNameRequestRsp, &kRemoteNameRequestComplete1})); std::unique_ptr<BrEdrDiscoverySession> session; - size_t devices_found = 0u; + size_t peers_found = 0u; discovery_manager()->RequestDiscovery( - [&session, &devices_found](auto status, auto cb_session) { + [&session, &peers_found](auto status, auto cb_session) { EXPECT_TRUE(status); cb_session->set_result_callback( - [&devices_found](const auto& device) { devices_found++; }); + [&peers_found](const auto&) { peers_found++; }); session = std::move(cb_session); }); @@ -316,7 +316,7 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, RequestDiscoveryAndDrop) { RunLoopUntilIdle(); - EXPECT_EQ(1u, devices_found); + EXPECT_EQ(1u, peers_found); EXPECT_TRUE(discovery_manager()->discovering()); test_device()->QueueCommandTransaction( @@ -326,7 +326,7 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, RequestDiscoveryAndDrop) { RunLoopUntilIdle(); - EXPECT_EQ(2u, devices_found); + EXPECT_EQ(2u, peers_found); // TODO(jamuraa, NET-619): test InquiryCancel when it is implemented @@ -335,7 +335,7 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, RequestDiscoveryAndDrop) { RunLoopUntilIdle(); - EXPECT_EQ(2u, devices_found); + EXPECT_EQ(2u, peers_found); EXPECT_FALSE(discovery_manager()->discovering()); test_device()->SendCommandChannelPacket(kInquiryComplete); @@ -353,13 +353,13 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, MultipleRequests) { {&kRemoteNameRequestRsp, &kRemoteNameRequestComplete1})); std::unique_ptr<BrEdrDiscoverySession> session1; - size_t devices_found1 = 0u; + size_t peers_found1 = 0u; discovery_manager()->RequestDiscovery( - [&session1, &devices_found1](auto status, auto cb_session) { + [&session1, &peers_found1](auto status, auto cb_session) { EXPECT_TRUE(status); cb_session->set_result_callback( - [&devices_found1](const auto& device) { devices_found1++; }); + [&peers_found1](const auto&) { peers_found1++; }); session1 = std::move(cb_session); }); @@ -368,33 +368,33 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, MultipleRequests) { RunLoopUntilIdle(); EXPECT_TRUE(session1); - EXPECT_EQ(1u, devices_found1); + EXPECT_EQ(1u, peers_found1); EXPECT_TRUE(discovery_manager()->discovering()); std::unique_ptr<BrEdrDiscoverySession> session2; - size_t devices_found2 = 0u; + size_t peers_found2 = 0u; discovery_manager()->RequestDiscovery( - [&session2, &devices_found2](auto status, auto cb_session) { + [&session2, &peers_found2](auto status, auto cb_session) { EXPECT_TRUE(status); cb_session->set_result_callback( - [&devices_found2](const auto& device) { devices_found2++; }); + [&peers_found2](const auto&) { peers_found2++; }); session2 = std::move(cb_session); }); RunLoopUntilIdle(); EXPECT_TRUE(session2); - EXPECT_EQ(1u, devices_found1); - EXPECT_EQ(0u, devices_found2); + EXPECT_EQ(1u, peers_found1); + EXPECT_EQ(0u, peers_found2); EXPECT_TRUE(discovery_manager()->discovering()); test_device()->SendCommandChannelPacket(kInquiryResult); RunLoopUntilIdle(); - EXPECT_EQ(2u, devices_found1); - EXPECT_EQ(1u, devices_found2); + EXPECT_EQ(2u, peers_found1); + EXPECT_EQ(1u, peers_found2); session1 = nullptr; @@ -404,8 +404,8 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, MultipleRequests) { RunLoopUntilIdle(); - EXPECT_EQ(2u, devices_found1); - EXPECT_EQ(2u, devices_found2); + EXPECT_EQ(2u, peers_found1); + EXPECT_EQ(2u, peers_found2); // TODO(jamuraa, NET-619): test InquiryCancel when it is implemented @@ -415,8 +415,8 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, MultipleRequests) { RunLoopUntilIdle(); - EXPECT_EQ(2u, devices_found1); - EXPECT_EQ(2u, devices_found2); + EXPECT_EQ(2u, peers_found1); + EXPECT_EQ(2u, peers_found2); EXPECT_FALSE(discovery_manager()->discovering()); @@ -429,7 +429,7 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, MultipleRequests) { // still restart the Inquiry. // Test: starting a session "while" the other one is stopping should return // without needing an InquiryComplete first. -// Test: we should only request a device's name if it's the first time we +// Test: we should only request a peer's name if it's the first time we // encounter it. TEST_F(GAP_BrEdrDiscoveryManagerTest, RequestDiscoveryWhileStop) { test_device()->QueueCommandTransaction( @@ -439,13 +439,13 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, RequestDiscoveryWhileStop) { {&kRemoteNameRequestRsp, &kRemoteNameRequestComplete1})); std::unique_ptr<BrEdrDiscoverySession> session1; - size_t devices_found1 = 0u; + size_t peers_found1 = 0u; discovery_manager()->RequestDiscovery( - [&session1, &devices_found1](auto status, auto cb_session) { + [&session1, &peers_found1](auto status, auto cb_session) { EXPECT_TRUE(status); cb_session->set_result_callback( - [&devices_found1](const auto& device) { devices_found1++; }); + [&peers_found1](const auto&) { peers_found1++; }); session1 = std::move(cb_session); }); @@ -454,7 +454,7 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, RequestDiscoveryWhileStop) { RunLoopUntilIdle(); EXPECT_TRUE(session1); - EXPECT_EQ(1u, devices_found1); + EXPECT_EQ(1u, peers_found1); EXPECT_TRUE(discovery_manager()->discovering()); // Drop the active session. @@ -462,12 +462,12 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, RequestDiscoveryWhileStop) { RunLoopUntilIdle(); std::unique_ptr<BrEdrDiscoverySession> session2; - size_t devices_found2 = 0u; + size_t peers_found2 = 0u; discovery_manager()->RequestDiscovery( - [&session2, &devices_found2](auto status, auto cb_session) { + [&session2, &peers_found2](auto status, auto cb_session) { EXPECT_TRUE(status); cb_session->set_result_callback( - [&devices_found2](const auto& device) { devices_found2++; }); + [&peers_found2](const auto&) { peers_found2++; }); session2 = std::move(cb_session); }); @@ -478,7 +478,7 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, RequestDiscoveryWhileStop) { RunLoopUntilIdle(); - EXPECT_EQ(1u, devices_found2); + EXPECT_EQ(1u, peers_found2); // Inquiry should be restarted when the Complete comes in because an active // session2 still exists. @@ -489,16 +489,16 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, RequestDiscoveryWhileStop) { RunLoopUntilIdle(); - EXPECT_EQ(1u, devices_found1); - EXPECT_EQ(2u, devices_found2); + EXPECT_EQ(1u, peers_found1); + EXPECT_EQ(2u, peers_found2); EXPECT_TRUE(discovery_manager()->discovering()); test_device()->SendCommandChannelPacket(kInquiryResult); RunLoopUntilIdle(); - EXPECT_EQ(1u, devices_found1); - EXPECT_EQ(3u, devices_found2); + EXPECT_EQ(1u, peers_found1); + EXPECT_EQ(3u, peers_found2); // TODO(jamuraa, NET-619): test InquiryCancel when it is implemented session2 = nullptr; @@ -509,8 +509,8 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, RequestDiscoveryWhileStop) { RunLoopUntilIdle(); - EXPECT_EQ(1u, devices_found1); - EXPECT_EQ(3u, devices_found2); + EXPECT_EQ(1u, peers_found1); + EXPECT_EQ(3u, peers_found2); } // Test: When Inquiry Fails to start, we report this back to the requester. @@ -522,10 +522,9 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, RequestDiscoveryError) { {&kRemoteNameRequestRsp, &kRemoteNameRequestComplete1})); std::unique_ptr<BrEdrDiscoverySession> session; - size_t devices_found = 0u; discovery_manager()->RequestDiscovery( - [&session, &devices_found](auto status, auto cb_session) { + [&session](auto status, auto cb_session) { EXPECT_FALSE(status); EXPECT_FALSE(cb_session); EXPECT_EQ(common::HostError::kProtocolError, status.error()); @@ -549,15 +548,14 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, ContinuingDiscoveryError) { {&kRemoteNameRequestRsp, &kRemoteNameRequestComplete1})); std::unique_ptr<BrEdrDiscoverySession> session; - size_t devices_found = 0u; + size_t peers_found = 0u; bool error_callback = false; discovery_manager()->RequestDiscovery( - [&session, &devices_found, &error_callback](auto status, - auto cb_session) { + [&session, &peers_found, &error_callback](auto status, auto cb_session) { EXPECT_TRUE(status); cb_session->set_result_callback( - [&devices_found](const auto& device) { devices_found++; }); + [&peers_found](const auto&) { peers_found++; }); cb_session->set_error_callback( [&error_callback]() { error_callback = true; }); session = std::move(cb_session); @@ -567,7 +565,7 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, ContinuingDiscoveryError) { RunLoopUntilIdle(); - EXPECT_EQ(1u, devices_found); + EXPECT_EQ(1u, peers_found); EXPECT_TRUE(discovery_manager()->discovering()); test_device()->SendCommandChannelPacket(kInquiryCompleteError); @@ -705,7 +703,7 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, DiscoverableRequestWhileStopping) { // Test: non-standard inquiry modes mean before the first discovery, the // inquiry mode is set. -// Test: extended inquiry is stored in the remote device +// Test: extended inquiry is stored in the remote peer TEST_F(GAP_BrEdrDiscoveryManagerTest, ExtendedInquiry) { NewDiscoveryManager(hci::InquiryMode::kExtended); @@ -718,13 +716,13 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, ExtendedInquiry) { {&kRemoteNameRequestRsp, &kRemoteNameRequestComplete2})); std::unique_ptr<BrEdrDiscoverySession> session1; - size_t devices_found1 = 0u; + size_t peers_found1 = 0u; discovery_manager()->RequestDiscovery( - [&session1, &devices_found1](auto status, auto cb_session) { + [&session1, &peers_found1](auto status, auto cb_session) { EXPECT_TRUE(status); cb_session->set_result_callback( - [&devices_found1](const auto& device) { devices_found1++; }); + [&peers_found1](const auto&) { peers_found1++; }); session1 = std::move(cb_session); }); @@ -733,18 +731,18 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, ExtendedInquiry) { RunLoopUntilIdle(); EXPECT_TRUE(session1); - EXPECT_EQ(2u, devices_found1); + EXPECT_EQ(2u, peers_found1); EXPECT_TRUE(discovery_manager()->discovering()); session1 = nullptr; - RemoteDevice* device1 = device_cache()->FindDeviceByAddress(kDeviceAddress2); - ASSERT_TRUE(device1); - EXPECT_EQ(-20, device1->rssi()); + Peer* peer1 = peer_cache()->FindByAddress(kDeviceAddress2); + ASSERT_TRUE(peer1); + EXPECT_EQ(-20, peer1->rssi()); - RemoteDevice* device2 = device_cache()->FindDeviceByAddress(kDeviceAddress3); - ASSERT_TRUE(device2); - ASSERT_TRUE(device2->name()); - EXPECT_EQ("Fuchsia💖", *device2->name()); + Peer* peer2 = peer_cache()->FindByAddress(kDeviceAddress3); + ASSERT_TRUE(peer2); + ASSERT_TRUE(peer2->name()); + EXPECT_EQ("Fuchsia💖", *peer2->name()); test_device()->SendCommandChannelPacket(kInquiryComplete); @@ -754,10 +752,10 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, ExtendedInquiry) { } TEST_F(GAP_BrEdrDiscoveryManagerTest, - InquiryResultUpgradesKnownLowEnergyDeviceToDualMode) { - RemoteDevice* device = device_cache()->NewDevice(kLeAliasAddress1, true); - ASSERT_TRUE(device); - ASSERT_EQ(TechnologyType::kLowEnergy, device->technology()); + InquiryResultUpgradesKnownLowEnergyPeerToDualMode) { + Peer* peer = peer_cache()->NewPeer(kLeAliasAddress1, true); + ASSERT_TRUE(peer); + ASSERT_EQ(TechnologyType::kLowEnergy, peer->technology()); test_device()->QueueCommandTransaction( CommandTransaction(kInquiry, {&kInquiryRsp, &kInquiryResult})); @@ -766,21 +764,20 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, {&kRemoteNameRequestRsp, &kRemoteNameRequestComplete1})); std::unique_ptr<BrEdrDiscoverySession> session; - size_t devices_found = 0u; + size_t peers_found = 0u; - discovery_manager()->RequestDiscovery( - [&session, &devices_found](auto status, auto cb_session) { - EXPECT_TRUE(status); - cb_session->set_result_callback( - [&devices_found](auto&) { devices_found++; }); - session = std::move(cb_session); - }); + discovery_manager()->RequestDiscovery([&session, &peers_found]( + auto status, auto cb_session) { + EXPECT_TRUE(status); + cb_session->set_result_callback([&peers_found](auto&) { peers_found++; }); + session = std::move(cb_session); + }); RunLoopUntilIdle(); session = nullptr; - EXPECT_EQ(1u, devices_found); - ASSERT_EQ(device, device_cache()->FindDeviceByAddress(kDeviceAddress1)); - EXPECT_EQ(TechnologyType::kDualMode, device->technology()); + EXPECT_EQ(1u, peers_found); + ASSERT_EQ(peer, peer_cache()->FindByAddress(kDeviceAddress1)); + EXPECT_EQ(TechnologyType::kDualMode, peer->technology()); test_device()->SendCommandChannelPacket(kInquiryComplete); @@ -788,10 +785,10 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, } TEST_F(GAP_BrEdrDiscoveryManagerTest, - ExtendedInquiryResultUpgradesKnownLowEnergyDeviceToDualMode) { - RemoteDevice* device = device_cache()->NewDevice(kLeAliasAddress2, true); - ASSERT_TRUE(device); - ASSERT_EQ(TechnologyType::kLowEnergy, device->technology()); + ExtendedInquiryResultUpgradesKnownLowEnergyPeerToDualMode) { + Peer* peer = peer_cache()->NewPeer(kLeAliasAddress2, true); + ASSERT_TRUE(peer); + ASSERT_EQ(TechnologyType::kLowEnergy, peer->technology()); NewDiscoveryManager(hci::InquiryMode::kExtended); @@ -804,21 +801,20 @@ TEST_F(GAP_BrEdrDiscoveryManagerTest, {&kRemoteNameRequestRsp, &kRemoteNameRequestComplete2})); std::unique_ptr<BrEdrDiscoverySession> session; - size_t devices_found = 0u; + size_t peers_found = 0u; - discovery_manager()->RequestDiscovery( - [&session, &devices_found](auto status, auto cb_session) { - EXPECT_TRUE(status); - cb_session->set_result_callback( - [&devices_found](auto&) { devices_found++; }); - session = std::move(cb_session); - }); + discovery_manager()->RequestDiscovery([&session, &peers_found]( + auto status, auto cb_session) { + EXPECT_TRUE(status); + cb_session->set_result_callback([&peers_found](auto&) { peers_found++; }); + session = std::move(cb_session); + }); RunLoopUntilIdle(); session = nullptr; - EXPECT_EQ(2u, devices_found); - ASSERT_EQ(device, device_cache()->FindDeviceByAddress(kDeviceAddress2)); - EXPECT_EQ(TechnologyType::kDualMode, device->technology()); + EXPECT_EQ(2u, peers_found); + ASSERT_EQ(peer, peer_cache()->FindByAddress(kDeviceAddress2)); + EXPECT_EQ(TechnologyType::kDualMode, peer->technology()); test_device()->SendCommandChannelPacket(kInquiryComplete); diff --git a/src/connectivity/bluetooth/core/bt-host/gap/bredr_interrogator.cc b/src/connectivity/bluetooth/core/bt-host/gap/bredr_interrogator.cc index f618af33eabe48197d8d0f2335c39004c3b23ef8..bc932e6215968027c6131aafa0d1de84c1fe30c2 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/bredr_interrogator.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/bredr_interrogator.cc @@ -6,7 +6,7 @@ #include <zircon/assert.h> -#include "src/connectivity/bluetooth/core/bt-host/gap/remote_device.h" +#include "src/connectivity/bluetooth/core/bt-host/gap/peer.h" #include "src/connectivity/bluetooth/core/bt-host/hci/transport.h" namespace bt { @@ -34,7 +34,7 @@ void BrEdrInterrogator::Interrogation::Finish(hci::Status status) { result_cb(status, std::move(conn_ptr)); } -BrEdrInterrogator::BrEdrInterrogator(RemoteDeviceCache* cache, +BrEdrInterrogator::BrEdrInterrogator(PeerCache* cache, fxl::RefPtr<hci::Transport> hci, async_dispatcher_t* dispatcher) : hci_(hci), @@ -62,7 +62,7 @@ void BrEdrInterrogator::Start(DeviceId device_id, hci::ConnectionPtr conn_ptr, pending_.emplace(device_id, std::make_unique<Interrogation>( std::move(conn_ptr), std::move(callback))); - RemoteDevice* device = cache_->FindDeviceById(device_id); + Peer* device = cache_->FindById(device_id); if (!device) { Complete(device_id, hci::Status(common::HostError::kFailed)); return; @@ -102,7 +102,7 @@ void BrEdrInterrogator::Cancel(DeviceId device_id) { } void BrEdrInterrogator::MaybeComplete(DeviceId device_id) { - RemoteDevice* device = cache_->FindDeviceById(device_id); + Peer* device = cache_->FindById(device_id); if (!device) { Complete(device_id, hci::Status(common::HostError::kFailed)); return; @@ -138,7 +138,7 @@ void BrEdrInterrogator::Complete(DeviceId device_id, hci::Status status) { } void BrEdrInterrogator::MakeRemoteNameRequest(DeviceId device_id) { - RemoteDevice* device = cache_->FindDeviceById(device_id); + Peer* device = cache_->FindById(device_id); if (!device) { Complete(device_id, hci::Status(common::HostError::kFailed)); return; @@ -187,7 +187,7 @@ void BrEdrInterrogator::MakeRemoteNameRequest(DeviceId device_id) { break; } } - RemoteDevice* device = self->cache_->FindDeviceById(device_id); + Peer* device = self->cache_->FindById(device_id); if (!device) { self->Complete(device_id, hci::Status(common::HostError::kFailed)); return; @@ -236,7 +236,7 @@ void BrEdrInterrogator::ReadRemoteVersionInformation( event.view() .template payload<hci::ReadRemoteVersionInfoCompleteEventParams>(); - RemoteDevice* device = self->cache_->FindDeviceById(device_id); + Peer* device = self->cache_->FindById(device_id); if (!device) { self->Complete(device_id, hci::Status(common::HostError::kFailed)); return; @@ -286,7 +286,7 @@ void BrEdrInterrogator::ReadRemoteFeatures(DeviceId device_id, .template payload< hci::ReadRemoteSupportedFeaturesCompleteEventParams>(); - RemoteDevice* device = self->cache_->FindDeviceById(device_id); + Peer* device = self->cache_->FindById(device_id); if (!device) { self->Complete(device_id, hci::Status(common::HostError::kFailed)); return; @@ -343,7 +343,7 @@ void BrEdrInterrogator::ReadRemoteExtendedFeatures(DeviceId device_id, .template payload< hci::ReadRemoteExtendedFeaturesCompleteEventParams>(); - RemoteDevice* device = self->cache_->FindDeviceById(device_id); + Peer* device = self->cache_->FindById(device_id); if (!device) { self->Complete(device_id, hci::Status(common::HostError::kFailed)); return; diff --git a/src/connectivity/bluetooth/core/bt-host/gap/bredr_interrogator.h b/src/connectivity/bluetooth/core/bt-host/gap/bredr_interrogator.h index 39c32ab22332c50ab941de98c751103375990233..5e4302936d78cb69834d6a5eecbeac47f420e865 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/bredr_interrogator.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/bredr_interrogator.h @@ -13,7 +13,7 @@ #include <memory> #include "src/connectivity/bluetooth/core/bt-host/common/device_address.h" -#include "src/connectivity/bluetooth/core/bt-host/gap/remote_device_cache.h" +#include "src/connectivity/bluetooth/core/bt-host/gap/peer_cache.h" #include "src/connectivity/bluetooth/core/bt-host/hci/command_channel.h" #include "src/connectivity/bluetooth/core/bt-host/hci/connection.h" #include "src/connectivity/bluetooth/core/bt-host/hci/connection_parameters.h" @@ -43,7 +43,7 @@ namespace gap { class BrEdrInterrogator { public: // |cache| must live longer than this object. - BrEdrInterrogator(RemoteDeviceCache* cache, fxl::RefPtr<hci::Transport> hci, + BrEdrInterrogator(PeerCache* cache, fxl::RefPtr<hci::Transport> hci, async_dispatcher_t* dispatcher); // Will cancel all uncompleted interrogations. @@ -109,7 +109,7 @@ class BrEdrInterrogator { async_dispatcher_t* dispatcher_; // Cache to retrieve devices from. - RemoteDeviceCache* cache_; + PeerCache* cache_; // The current set of interrogations // TODO(BT-750): Store Interrogations by value. diff --git a/src/connectivity/bluetooth/core/bt-host/gap/discovery_filter.h b/src/connectivity/bluetooth/core/bt-host/gap/discovery_filter.h index 948f07b2c555bbaea661709e5cdf203bc7be8db7..d3e4076d03fe9d9a7a9165bc86eade4463db2f86 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/discovery_filter.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/discovery_filter.h @@ -19,7 +19,7 @@ class ByteBuffer; namespace gap { -class RemoteDevice; +class Peer; // A DiscoveryFilter allows clients of discovery procedures to filter results // based on certain parameters, such as service UUIDs that might be present in diff --git a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_advertising_manager.cc b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_advertising_manager.cc index 5c38ecc6f5ef41d063590c216fc105be62f14007..c63fadf0e96f104a883358828f34d44e714ab9c6 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_advertising_manager.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_advertising_manager.cc @@ -7,7 +7,7 @@ #include <zircon/assert.h> #include "low_energy_address_manager.h" -#include "remote_device.h" +#include "peer.h" #include "src/connectivity/bluetooth/core/bt-host/common/log.h" #include "src/connectivity/bluetooth/core/bt-host/common/random.h" #include "src/connectivity/bluetooth/core/bt-host/common/slab_allocator.h" diff --git a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager.cc b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager.cc index 967775c0201283ee60a347d0670818012b54cb66..7043f9a7d266301fbca21572a756b6211bed1c82 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager.cc @@ -8,8 +8,8 @@ #include <zircon/syscalls.h> #include "pairing_delegate.h" -#include "remote_device.h" -#include "remote_device_cache.h" +#include "peer.h" +#include "peer_cache.h" #include "src/connectivity/bluetooth/core/bt-host/gatt/local_service_manager.h" #include "src/connectivity/bluetooth/core/bt-host/hci/defaults.h" #include "src/connectivity/bluetooth/core/bt-host/hci/hci.h" @@ -135,12 +135,12 @@ class LowEnergyConnection final : public sm::PairingState::Delegate { // Obtain existing pairing data, if any. std::optional<sm::LTK> ltk; - auto* dev = conn_mgr_->device_cache()->FindDeviceById(peer_id()); - ZX_DEBUG_ASSERT_MSG(dev, "connected device must be present in cache!"); + auto* peer = conn_mgr_->peer_cache()->FindById(peer_id()); + ZX_DEBUG_ASSERT_MSG(peer, "connected peer must be present in cache!"); - if (dev->le() && dev->le()->bond_data()) { + if (peer->le() && peer->le()->bond_data()) { // |ltk| will remain as std::nullopt if bonding data contains no LTK. - ltk = dev->le()->bond_data()->ltk; + ltk = peer->le()->bond_data()->ltk; } // Obtain the local I/O capabilities from the delegate. Default to @@ -190,7 +190,7 @@ class LowEnergyConnection final : public sm::PairingState::Delegate { // TODO(armansito): Support bonding with just the CSRK for LE security mode // 2. if (!pairing_data.ltk) { - bt_log(INFO, "gap-le", "temporarily paired with device (id: %s)", + bt_log(INFO, "gap-le", "temporarily paired with peer (id: %s)", bt_str(peer_id())); return; } @@ -205,8 +205,7 @@ class LowEnergyConnection final : public sm::PairingState::Delegate { : "", pairing_data.csrk ? "csrk " : "", bt_str(peer_id())); - if (!conn_mgr_->device_cache()->StoreLowEnergyBond(peer_id_, - pairing_data)) { + if (!conn_mgr_->peer_cache()->StoreLowEnergyBond(peer_id_, pairing_data)) { bt_log(ERROR, "gap-le", "failed to cache bonding data (id: %s)", bt_str(peer_id())); } @@ -224,7 +223,7 @@ class LowEnergyConnection final : public sm::PairingState::Delegate { // sm::PairingState::Delegate override: void OnAuthenticationFailure(hci::Status status) override { - // TODO(armansito): Clear bonding data from the remote device cache as any + // TODO(armansito): Clear bonding data from the remote peer cache as any // stored link key is not valid. bt_log(ERROR, "gap-le", "link layer authentication failed: %s", status.ToString().c_str()); @@ -342,10 +341,10 @@ class LowEnergyConnection final : public sm::PairingState::Delegate { } // namespace internal LowEnergyConnectionRef::LowEnergyConnectionRef( - DeviceId device_id, hci::ConnectionHandle handle, + DeviceId peer_id, hci::ConnectionHandle handle, fxl::WeakPtr<LowEnergyConnectionManager> manager) - : active_(true), device_id_(device_id), handle_(handle), manager_(manager) { - ZX_DEBUG_ASSERT(device_id_.IsValid()); + : active_(true), peer_id_(peer_id), handle_(handle), manager_(manager) { + ZX_DEBUG_ASSERT(peer_id_.IsValid()); ZX_DEBUG_ASSERT(manager_); ZX_DEBUG_ASSERT(handle_); } @@ -392,19 +391,19 @@ void LowEnergyConnectionManager::PendingRequestData::NotifyCallbacks( LowEnergyConnectionManager::LowEnergyConnectionManager( fxl::RefPtr<hci::Transport> hci, hci::LocalAddressDelegate* addr_delegate, - hci::LowEnergyConnector* connector, RemoteDeviceCache* device_cache, + hci::LowEnergyConnector* connector, PeerCache* peer_cache, fbl::RefPtr<data::Domain> data_domain, fbl::RefPtr<gatt::GATT> gatt) : hci_(hci), request_timeout_(kLECreateConnectionTimeout), dispatcher_(async_get_default_dispatcher()), - device_cache_(device_cache), + peer_cache_(peer_cache), data_domain_(data_domain), gatt_(gatt), connector_(connector), local_address_delegate_(addr_delegate), weak_ptr_factory_(this) { ZX_DEBUG_ASSERT(dispatcher_); - ZX_DEBUG_ASSERT(device_cache_); + ZX_DEBUG_ASSERT(peer_cache_); ZX_DEBUG_ASSERT(data_domain_); ZX_DEBUG_ASSERT(gatt_); ZX_DEBUG_ASSERT(hci_); @@ -462,37 +461,37 @@ LowEnergyConnectionManager::~LowEnergyConnectionManager() { connections_.clear(); } -bool LowEnergyConnectionManager::Connect(DeviceId device_id, +bool LowEnergyConnectionManager::Connect(DeviceId peer_id, ConnectionResultCallback callback) { if (!connector_) { bt_log(WARN, "gap-le", "connect called during shutdown!"); return false; } - RemoteDevice* peer = device_cache_->FindDeviceById(device_id); + Peer* peer = peer_cache_->FindById(peer_id); if (!peer) { - bt_log(WARN, "gap-le", "device not found (id: %s)", bt_str(device_id)); + bt_log(WARN, "gap-le", "peer not found (id: %s)", bt_str(peer_id)); return false; } if (peer->technology() == TechnologyType::kClassic) { - bt_log(ERROR, "gap-le", "device does not support LE: %s", + bt_log(ERROR, "gap-le", "peer does not support LE: %s", peer->ToString().c_str()); return false; } if (!peer->connectable()) { - bt_log(ERROR, "gap-le", "device not connectable: %s", + bt_log(ERROR, "gap-le", "peer not connectable: %s", peer->ToString().c_str()); return false; } - // If we are already waiting to connect to |device_id| then we store + // If we are already waiting to connect to |peer_id| then we store // |callback| to be processed after the connection attempt completes (in // either success of failure). - auto pending_iter = pending_requests_.find(device_id); + auto pending_iter = pending_requests_.find(peer_id); if (pending_iter != pending_requests_.end()) { - ZX_DEBUG_ASSERT(connections_.find(device_id) == connections_.end()); + ZX_DEBUG_ASSERT(connections_.find(peer_id) == connections_.end()); ZX_DEBUG_ASSERT(connector_->request_pending()); pending_iter->second.AddCallback(std::move(callback)); @@ -501,7 +500,7 @@ bool LowEnergyConnectionManager::Connect(DeviceId device_id, // If there is already an active connection then we add a new reference and // succeed. - auto conn_ref = AddConnectionRef(device_id); + auto conn_ref = AddConnectionRef(peer_id); if (conn_ref) { async::PostTask(dispatcher_, [conn_ref = std::move(conn_ref), callback = std::move(callback)]() mutable { @@ -518,9 +517,8 @@ bool LowEnergyConnectionManager::Connect(DeviceId device_id, return true; } - peer->MutLe().SetConnectionState( - RemoteDevice::ConnectionState::kInitializing); - pending_requests_[device_id] = + peer->MutLe().SetConnectionState(Peer::ConnectionState::kInitializing); + pending_requests_[peer_id] = PendingRequestData(peer->address(), std::move(callback)); TryCreateNextConnection(); @@ -528,10 +526,10 @@ bool LowEnergyConnectionManager::Connect(DeviceId device_id, return true; } -bool LowEnergyConnectionManager::Disconnect(DeviceId device_id) { - auto iter = connections_.find(device_id); +bool LowEnergyConnectionManager::Disconnect(DeviceId peer_id) { + auto iter = connections_.find(peer_id); if (iter == connections_.end()) { - bt_log(WARN, "gap-le", "device not connected (id: %s)", bt_str(device_id)); + bt_log(WARN, "gap-le", "peer not connected (id: %s)", bt_str(peer_id)); return false; } @@ -552,14 +550,14 @@ LowEnergyConnectionManager::RegisterRemoteInitiatedLink( bt_log(TRACE, "gap-le", "new remote-initiated link (local addr: %s): %s", link->local_address().ToString().c_str(), link->ToString().c_str()); - RemoteDevice* peer = UpdateRemoteDeviceWithLink(*link); + Peer* peer = UpdatePeerWithLink(*link); // TODO(armansito): Use own address when storing the connection (NET-321). // Currently this will refuse the connection and disconnect the link if |peer| // is already connected to us by a different local address. auto conn_ref = InitializeConnection(peer->identifier(), std::move(link)); if (conn_ref) { - peer->MutLe().SetConnectionState(RemoteDevice::ConnectionState::kConnected); + peer->MutLe().SetConnectionState(Peer::ConnectionState::kConnected); } return conn_ref; } @@ -593,7 +591,7 @@ void LowEnergyConnectionManager::ReleaseReference( LowEnergyConnectionRef* conn_ref) { ZX_DEBUG_ASSERT(conn_ref); - auto iter = connections_.find(conn_ref->device_identifier()); + auto iter = connections_.find(conn_ref->peer_identifier()); ZX_DEBUG_ASSERT(iter != connections_.end()); iter->second->DropRef(conn_ref); @@ -623,28 +621,28 @@ void LowEnergyConnectionManager::TryCreateNextConnection() { bt_log(SPEW, "gap-le", "no pending requests remaining"); // TODO(armansito): Unpause discovery and disable background scanning if - // there aren't any devices to auto-connect to. + // there aren't any peers to auto-connect to. return; } for (auto& iter : pending_requests_) { - const auto& next_device_addr = iter.second.address(); - RemoteDevice* peer = device_cache_->FindDeviceByAddress(next_device_addr); + const auto& next_peer_addr = iter.second.address(); + Peer* peer = peer_cache_->FindByAddress(next_peer_addr); if (peer) { RequestCreateConnection(peer); break; } - bt_log(TRACE, "gap-le", "deferring connection attempt for device: %s", - next_device_addr.ToString().c_str()); + bt_log(TRACE, "gap-le", "deferring connection attempt for peer: %s", + next_peer_addr.ToString().c_str()); - // TODO(armansito): For now the requests for this device won't complete - // until the next device discovery. This will no longer be an issue when we + // TODO(armansito): For now the requests for this peer won't complete + // until the next peer discovery. This will no longer be an issue when we // use background scanning (see NET-187). } } -void LowEnergyConnectionManager::RequestCreateConnection(RemoteDevice* peer) { +void LowEnergyConnectionManager::RequestCreateConnection(Peer* peer) { ZX_DEBUG_ASSERT(peer); // During the initial connection to a peripheral we use the initial high @@ -661,10 +659,10 @@ void LowEnergyConnectionManager::RequestCreateConnection(RemoteDevice* peer) { hci::defaults::kLESupervisionTimeout); auto self = weak_ptr_factory_.GetWeakPtr(); - auto status_cb = [self, device_id = peer->identifier()](hci::Status status, - auto link) { + auto status_cb = [self, peer_id = peer->identifier()](hci::Status status, + auto link) { if (self) - self->OnConnectResult(device_id, status, std::move(link)); + self->OnConnectResult(peer_id, status, std::move(link)); }; // We set the scan window and interval to the same value for continuous @@ -675,15 +673,15 @@ void LowEnergyConnectionManager::RequestCreateConnection(RemoteDevice* peer) { } LowEnergyConnectionRefPtr LowEnergyConnectionManager::InitializeConnection( - DeviceId device_id, std::unique_ptr<hci::Connection> link) { + DeviceId peer_id, std::unique_ptr<hci::Connection> link) { ZX_DEBUG_ASSERT(link); ZX_DEBUG_ASSERT(link->ll_type() == hci::Connection::LinkType::kLE); // TODO(armansito): For now reject having more than one link with the same // peer. This should change once this has more context on the local // destination for remote initiated connections (see NET-321). - if (connections_.find(device_id) != connections_.end()) { - bt_log(TRACE, "gap-le", "multiple links from device; connection refused"); + if (connections_.find(peer_id) != connections_.end()) { + bt_log(TRACE, "gap-le", "multiple links from peer; connection refused"); link->Close(); return nullptr; } @@ -692,32 +690,32 @@ LowEnergyConnectionRefPtr LowEnergyConnectionManager::InitializeConnection( // the channels are open. auto self = weak_ptr_factory_.GetWeakPtr(); auto conn_param_update_cb = [self, handle = link->handle(), - device_id](const auto& params) { + peer_id](const auto& params) { if (self) { - self->OnNewLEConnectionParams(device_id, handle, params); + self->OnNewLEConnectionParams(peer_id, handle, params); } }; - auto link_error_cb = [self, device_id] { + auto link_error_cb = [self, peer_id] { bt_log(TRACE, "gap", "link error received from L2CAP"); if (self) { - self->Disconnect(device_id); + self->Disconnect(peer_id); } }; // Initialize connection. auto conn = std::make_unique<internal::LowEnergyConnection>( - device_id, std::move(link), dispatcher_, weak_ptr_factory_.GetWeakPtr(), + peer_id, std::move(link), dispatcher_, weak_ptr_factory_.GetWeakPtr(), data_domain_, gatt_); conn->InitializeFixedChannels(std::move(conn_param_update_cb), std::move(link_error_cb)); auto first_ref = conn->AddRef(); - connections_[device_id] = std::move(conn); + connections_[peer_id] = std::move(conn); // TODO(armansito): Should complete a few more things before returning the // connection: - // 1. If this is the first time we connected to this device: + // 1. If this is the first time we connected to this peer: // a. Obtain LE remote features // b. If master, obtain Peripheral Preferred Connection Parameters via // GATT if available @@ -730,8 +728,8 @@ LowEnergyConnectionRefPtr LowEnergyConnectionManager::InitializeConnection( } LowEnergyConnectionRefPtr LowEnergyConnectionManager::AddConnectionRef( - DeviceId device_id) { - auto iter = connections_.find(device_id); + DeviceId peer_id) { + auto iter = connections_.find(peer_id); if (iter == connections_.end()) return nullptr; @@ -742,11 +740,10 @@ void LowEnergyConnectionManager::CleanUpConnection( std::unique_ptr<internal::LowEnergyConnection> conn, bool close_link) { ZX_DEBUG_ASSERT(conn); - // Mark the peer device as no longer connected. - RemoteDevice* peer = device_cache_->FindDeviceById(conn->peer_id()); + // Mark the peer peer as no longer connected. + Peer* peer = peer_cache_->FindById(conn->peer_id()); ZX_DEBUG_ASSERT(peer); - peer->MutLe().SetConnectionState( - RemoteDevice::ConnectionState::kNotConnected); + peer->MutLe().SetConnectionState(Peer::ConnectionState::kNotConnected); if (!close_link) { // Mark the connection as already closed so that hci::Connection::Close() @@ -766,7 +763,7 @@ void LowEnergyConnectionManager::RegisterLocalInitiatedLink( ZX_DEBUG_ASSERT(link->ll_type() == hci::Connection::LinkType::kLE); bt_log(INFO, "gap-le", "new connection %s", link->ToString().c_str()); - RemoteDevice* peer = UpdateRemoteDeviceWithLink(*link); + Peer* peer = UpdatePeerWithLink(*link); // Initialize the connection and obtain the initial reference. // This reference lasts until this method returns to prevent it from dropping @@ -781,7 +778,7 @@ void LowEnergyConnectionManager::RegisterLocalInitiatedLink( ZX_DEBUG_ASSERT(conn_iter != connections_.end()); // For now, jump to the initialized state. - peer->MutLe().SetConnectionState(RemoteDevice::ConnectionState::kConnected); + peer->MutLe().SetConnectionState(Peer::ConnectionState::kConnected); auto iter = pending_requests_.find(peer->identifier()); if (iter != pending_requests_.end()) { @@ -801,21 +798,20 @@ void LowEnergyConnectionManager::RegisterLocalInitiatedLink( TryCreateNextConnection(); } -RemoteDevice* LowEnergyConnectionManager::UpdateRemoteDeviceWithLink( +Peer* LowEnergyConnectionManager::UpdatePeerWithLink( const hci::Connection& link) { - RemoteDevice* peer = device_cache_->FindDeviceByAddress(link.peer_address()); + Peer* peer = peer_cache_->FindByAddress(link.peer_address()); if (!peer) { - peer = - device_cache_->NewDevice(link.peer_address(), true /* connectable */); + peer = peer_cache_->NewPeer(link.peer_address(), true /* connectable */); } peer->MutLe().SetConnectionParameters(link.low_energy_parameters()); return peer; } -void LowEnergyConnectionManager::OnConnectResult(DeviceId device_id, +void LowEnergyConnectionManager::OnConnectResult(DeviceId peer_id, hci::Status status, hci::ConnectionPtr link) { - ZX_DEBUG_ASSERT(connections_.find(device_id) == connections_.end()); + ZX_DEBUG_ASSERT(connections_.find(peer_id) == connections_.end()); if (status) { bt_log(TRACE, "gap-le", "connection request successful"); @@ -824,14 +820,14 @@ void LowEnergyConnectionManager::OnConnectResult(DeviceId device_id, } // The request failed or timed out. - bt_log(ERROR, "gap-le", "failed to connect to device (id: %s)", - bt_str(device_id)); - RemoteDevice* dev = device_cache_->FindDeviceById(device_id); - ZX_ASSERT(dev); - dev->MutLe().SetConnectionState(RemoteDevice::ConnectionState::kNotConnected); + bt_log(ERROR, "gap-le", "failed to connect to peer (id: %s)", + bt_str(peer_id)); + Peer* peer = peer_cache_->FindById(peer_id); + ZX_ASSERT(peer); + peer->MutLe().SetConnectionState(Peer::ConnectionState::kNotConnected); // Notify the matching pending callbacks about the failure. - auto iter = pending_requests_.find(device_id); + auto iter = pending_requests_.find(peer_id); ZX_DEBUG_ASSERT(iter != pending_requests_.end()); // Remove the entry from |pending_requests_| before notifying callbacks. @@ -923,7 +919,7 @@ void LowEnergyConnectionManager::OnLEConnectionUpdateComplete( le16toh(payload->supervision_timeout)); conn.link()->set_low_energy_parameters(params); - RemoteDevice* peer = device_cache_->FindDeviceById(conn.peer_id()); + Peer* peer = peer_cache_->FindById(conn.peer_id()); if (!peer) { bt_log(ERROR, "gap-le", "conn. parameters updated for unknown peer!"); return; @@ -936,11 +932,11 @@ void LowEnergyConnectionManager::OnLEConnectionUpdateComplete( } void LowEnergyConnectionManager::OnNewLEConnectionParams( - DeviceId device_id, hci::ConnectionHandle handle, + DeviceId peer_id, hci::ConnectionHandle handle, const hci::LEPreferredConnectionParameters& params) { bt_log(TRACE, "gap-le", "conn. parameters received (handle: %#.4x)", handle); - RemoteDevice* peer = device_cache_->FindDeviceById(device_id); + Peer* peer = peer_cache_->FindById(peer_id); if (!peer) { bt_log(ERROR, "gap-le", "conn. parameters received from unknown peer!"); return; diff --git a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager.h b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager.h index fec6b83ebc5056b7255701cdc92ec294577d83d0..4c9dbb7de0c48645d723f60615673dc6a9fa1d4b 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager.h @@ -41,8 +41,8 @@ class LowEnergyConnection; class LowEnergyConnectionManager; class PairingDelegate; -class RemoteDevice; -class RemoteDeviceCache; +class Peer; +class PeerCache; class LowEnergyConnectionRef final { public: @@ -60,14 +60,14 @@ class LowEnergyConnectionRef final { closed_cb_ = std::move(callback); } - DeviceId device_identifier() const { return device_id_; } + DeviceId peer_identifier() const { return peer_id_; } hci::ConnectionHandle handle() const { return handle_; } private: friend class LowEnergyConnectionManager; friend class internal::LowEnergyConnection; - LowEnergyConnectionRef(DeviceId device_id, hci::ConnectionHandle handle, + LowEnergyConnectionRef(DeviceId peer_id, hci::ConnectionHandle handle, fxl::WeakPtr<LowEnergyConnectionManager> manager); // Called by LowEnergyConnectionManager when the underlying connection is @@ -75,7 +75,7 @@ class LowEnergyConnectionRef final { void MarkClosed(); bool active_; - DeviceId device_id_; + DeviceId peer_id_; hci::ConnectionHandle handle_; fxl::WeakPtr<LowEnergyConnectionManager> manager_; fit::closure closed_cb_; @@ -94,32 +94,32 @@ class LowEnergyConnectionManager final { // procedures. // |connector|: Adapter object for initiating link layer connections. This // object abstracts the legacy and extended HCI command sets. - // |device_cache|: The cache that stores peer device data. The connection + // |peer_cache|: The cache that stores peer peer data. The connection // manager stores and retrieves pairing data and connection // parameters to/from the cache. It also updates the - // connection and bonding state of a device via the cache. + // connection and bonding state of a peer via the cache. // |data_domain|: Used to interact with the L2CAP layer. // |gatt|: Used to interact with the GATT profile layer. LowEnergyConnectionManager(fxl::RefPtr<hci::Transport> hci, hci::LocalAddressDelegate* addr_delegate, hci::LowEnergyConnector* connector, - RemoteDeviceCache* device_cache, + PeerCache* peer_cache, fbl::RefPtr<data::Domain> data_domain, fbl::RefPtr<gatt::GATT> gatt); ~LowEnergyConnectionManager(); // Allows a caller to claim shared ownership over a connection to the - // requested remote LE device identified by |device_id|. Returns - // false, if |device_id| is not recognized, otherwise: + // requested remote LE peer identified by |peer_id|. Returns + // false, if |peer_id| is not recognized, otherwise: // - // * If the requested device is already connected, this method + // * If the requested peer is already connected, this method // asynchronously returns a LowEnergyConnectionRef without sending any // requests to the controller. This is done for both local and remote // initiated connections (i.e. the local adapter can either be in the LE // central or peripheral roles). |callback| always succeeds. // - // * If the requested device is NOT connected, then this method initiates a - // connection to the requested device using one of the GAP central role + // * If the requested peer is NOT connected, then this method initiates a + // connection to the requested peer using one of the GAP central role // connection establishment procedures described in Core Spec v5.0, Vol 3, // Part C, Section 9.3. A LowEnergyConnectionRef is asynchronously // returned to the caller once the connection has been set up. @@ -130,17 +130,17 @@ class LowEnergyConnectionManager final { // |callback| is posted on the creation thread's dispatcher. using ConnectionResultCallback = fit::function<void(hci::Status, LowEnergyConnectionRefPtr)>; - bool Connect(DeviceId device_id, ConnectionResultCallback callback); + bool Connect(DeviceId peer_id, ConnectionResultCallback callback); - RemoteDeviceCache* device_cache() { return device_cache_; } + PeerCache* peer_cache() { return peer_cache_; } hci::LocalAddressDelegate* local_address_delegate() const { return local_address_delegate_; } - // Disconnects any existing LE connection to |device_id|, invalidating - // all active LowEnergyConnectionRefs. Returns false if |device_id| is - // not recognized or the corresponding remote device is not connected. - bool Disconnect(DeviceId device_id); + // Disconnects any existing LE connection to |peer_id|, invalidating + // all active LowEnergyConnectionRefs. Returns false if |peer_id| is + // not recognized or the corresponding remote peer is not connected. + bool Disconnect(DeviceId peer_id); // Initializes a new connection over the given |link| and returns a connection // reference. Returns nullptr if the connection was rejected. @@ -163,11 +163,11 @@ class LowEnergyConnectionManager final { // rejected. void SetPairingDelegate(fxl::WeakPtr<PairingDelegate> delegate); - // TODO(armansito): Add a RemoteDeviceCache::Observer interface and move these + // TODO(armansito): Add a PeerCache::Observer interface and move these // callbacks there. // Called when the connection parameters on a link have been updated. - using ConnectionParametersCallback = fit::function<void(const RemoteDevice&)>; + using ConnectionParametersCallback = fit::function<void(const Peer&)>; void SetConnectionParametersCallbackForTesting( ConnectionParametersCallback callback); @@ -190,7 +190,7 @@ class LowEnergyConnectionManager final { private: friend class LowEnergyConnectionRef; - // Mapping from device identifiers to open LE connections. + // Mapping from peer identifiers to open LE connections. using ConnectionMap = std::unordered_map<DeviceId, std::unique_ptr<internal::LowEnergyConnection>>; @@ -227,27 +227,27 @@ class LowEnergyConnectionManager final { void ReleaseReference(LowEnergyConnectionRef* conn_ref); // Called when |connector_| completes a pending request. Initiates a new - // connection attempt for the next device in the pending list, if any. + // connection attempt for the next peer in the pending list, if any. void TryCreateNextConnection(); // Initiates a connection attempt to |peer|. - void RequestCreateConnection(RemoteDevice* peer); + void RequestCreateConnection(Peer* peer); // Initializes the connection to the peer with the given identifier and // returns the initial reference to it. This method is responsible for setting // up all data bearers. - LowEnergyConnectionRefPtr InitializeConnection(DeviceId device_id, + LowEnergyConnectionRefPtr InitializeConnection(DeviceId peer_id, hci::ConnectionPtr link); - // Adds a new connection reference to an existing connection to the device - // with the ID |device_id| and returns it. Returns nullptr if - // |device_id| is not recognized. - LowEnergyConnectionRefPtr AddConnectionRef(DeviceId device_id); + // Adds a new connection reference to an existing connection to the peer + // with the ID |peer_id| and returns it. Returns nullptr if + // |peer_id| is not recognized. + LowEnergyConnectionRefPtr AddConnectionRef(DeviceId peer_id); // Cleans up a connection state. This results in a HCI_Disconnect command // if |close_link| is true, and notifies any referenced // LowEnergyConnectionRefs of the disconnection. Marks the corresponding - // RemoteDeviceCache entry as disconnected and cleans up all data bearers. + // PeerCache entry as disconnected and cleans up all data bearers. // // |conn_state| will have been removed from the underlying map at the time of // a call. Its ownership is passed to the method for disposal. @@ -261,21 +261,21 @@ class LowEnergyConnectionManager final { // created. void RegisterLocalInitiatedLink(hci::ConnectionPtr link); - // Updates |device_cache_| with the given |link| and returns the corresponding - // RemoteDevice. + // Updates |peer_cache_| with the given |link| and returns the corresponding + // Peer. // - // Creates a new RemoteDevice if |link| matches a peer that did not + // Creates a new Peer if |link| matches a peer that did not // previously exist in the cache. Otherwise this updates and returns an - // existing RemoteDevice. + // existing Peer. // - // The returned device is marked as non-temporary and its connection + // The returned peer is marked as non-temporary and its connection // parameters are updated. // // Called by RegisterRemoteInitiatedLink() and RegisterLocalInitiatedLink(). - RemoteDevice* UpdateRemoteDeviceWithLink(const hci::Connection& link); + Peer* UpdatePeerWithLink(const hci::Connection& link); // Called by |connector_| to indicate the result of a connect request. - void OnConnectResult(DeviceId device_id, hci::Status status, + void OnConnectResult(DeviceId peer_id, hci::Status status, hci::ConnectionPtr link); // Event handler for the HCI Disconnection Complete event. @@ -303,10 +303,10 @@ class LowEnergyConnectionManager final { // discovery, as recommended by the specification in v5.0, Vol 3, Part C, // Section 9.3.12.1). // - // |device_id| uniquely identifies the peer. |handle| represents + // |peer_id| uniquely identifies the peer. |handle| represents // the logical link that |params| should be applied to. void OnNewLEConnectionParams( - DeviceId device_id, hci::ConnectionHandle handle, + DeviceId peer_id, hci::ConnectionHandle handle, const hci::LEPreferredConnectionParameters& params); // Tells the controller to use the given connection |params| on the given @@ -336,10 +336,10 @@ class LowEnergyConnectionManager final { // The dispatcher for all asynchronous tasks. async_dispatcher_t* dispatcher_; - // The device cache is used to look up and persist remote device data that is + // The peer cache is used to look up and persist remote peer data that is // relevant during connection establishment (such as the address, preferred // connection parameters, etc). Expected to outlive this instance. - RemoteDeviceCache* device_cache_; // weak + PeerCache* peer_cache_; // weak // The reference to the data domain, used to interact with the L2CAP layer to // manage LE logical links, fixed channels, and LE-specific L2CAP signaling @@ -363,10 +363,10 @@ class LowEnergyConnectionManager final { ConnectionParametersCallback test_conn_params_cb_; DisconnectCallback test_disconn_cb_; - // Outstanding connection requests based on remote device ID. + // Outstanding connection requests based on remote peer ID. std::unordered_map<DeviceId, PendingRequestData> pending_requests_; - // Mapping from device identifiers to currently open LE connections. + // Mapping from peer identifiers to currently open LE connections. ConnectionMap connections_; // Performs the Direct Connection Establishment procedure. |connector_| must diff --git a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager_unittest.cc index b9af18ad80e6e482b667936568bda4be4ca62e40..02229dd169570c2d52c157dde914b8e60d22838c 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_connection_manager_unittest.cc @@ -11,8 +11,8 @@ #include <vector> #include "src/connectivity/bluetooth/core/bt-host/data/fake_domain.h" -#include "src/connectivity/bluetooth/core/bt-host/gap/remote_device.h" -#include "src/connectivity/bluetooth/core/bt-host/gap/remote_device_cache.h" +#include "src/connectivity/bluetooth/core/bt-host/gap/peer.h" +#include "src/connectivity/bluetooth/core/bt-host/gap/peer_cache.h" #include "src/connectivity/bluetooth/core/bt-host/gatt/fake_layer.h" #include "src/connectivity/bluetooth/core/bt-host/hci/fake_local_address_delegate.h" #include "src/connectivity/bluetooth/core/bt-host/hci/hci_constants.h" @@ -58,7 +58,7 @@ class LowEnergyConnectionManagerTest : public TestingBase { settings.ApplyLegacyLEConfig(); test_device()->set_settings(settings); - dev_cache_ = std::make_unique<RemoteDeviceCache>(); + peer_cache_ = std::make_unique<PeerCache>(); l2cap_ = data::testing::FakeDomain::Create(); l2cap_->Initialize(); @@ -68,7 +68,7 @@ class LowEnergyConnectionManagerTest : public TestingBase { this, &LowEnergyConnectionManagerTest::OnIncomingConnection)); conn_mgr_ = std::make_unique<LowEnergyConnectionManager>( - transport(), &addr_delegate_, connector_.get(), dev_cache_.get(), + transport(), &addr_delegate_, connector_.get(), peer_cache_.get(), l2cap_, gatt::testing::FakeLayer::Create()); test_device()->SetConnectionStateCallback( @@ -81,7 +81,7 @@ class LowEnergyConnectionManagerTest : public TestingBase { void TearDown() override { if (conn_mgr_) conn_mgr_ = nullptr; - dev_cache_ = nullptr; + peer_cache_ = nullptr; l2cap_->ShutDown(); l2cap_ = nullptr; @@ -92,16 +92,16 @@ class LowEnergyConnectionManagerTest : public TestingBase { // Deletes |conn_mgr_|. void DeleteConnMgr() { conn_mgr_ = nullptr; } - RemoteDeviceCache* dev_cache() const { return dev_cache_.get(); } + PeerCache* peer_cache() const { return peer_cache_.get(); } LowEnergyConnectionManager* conn_mgr() const { return conn_mgr_.get(); } data::testing::FakeDomain* fake_l2cap() const { return l2cap_.get(); } - // Addresses of currently connected fake devices. - using DeviceList = std::unordered_set<common::DeviceAddress>; - const DeviceList& connected_devices() const { return connected_devices_; } + // Addresses of currently connected fake peers. + using PeerList = std::unordered_set<common::DeviceAddress>; + const PeerList& connected_peers() const { return connected_peers_; } - // Addresses of devices with a canceled connection attempt. - const DeviceList& canceled_devices() const { return canceled_devices_; } + // Addresses of peers with a canceled connection attempt. + const PeerList& canceled_peers() const { return canceled_peers_; } hci::ConnectionPtr MoveLastRemoteInitiated() { return std::move(last_remote_initiated_); @@ -130,62 +130,60 @@ class LowEnergyConnectionManagerTest : public TestingBase { address.ToString().c_str(), connected ? "true" : "false", canceled ? "true" : "false"); if (canceled) { - canceled_devices_.insert(address); + canceled_peers_.insert(address); } else if (connected) { - ZX_DEBUG_ASSERT(connected_devices_.find(address) == - connected_devices_.end()); - connected_devices_.insert(address); + ZX_DEBUG_ASSERT(connected_peers_.find(address) == connected_peers_.end()); + connected_peers_.insert(address); } else { - ZX_DEBUG_ASSERT(connected_devices_.find(address) != - connected_devices_.end()); - connected_devices_.erase(address); + ZX_DEBUG_ASSERT(connected_peers_.find(address) != connected_peers_.end()); + connected_peers_.erase(address); } } fbl::RefPtr<data::testing::FakeDomain> l2cap_; hci::FakeLocalAddressDelegate addr_delegate_; - std::unique_ptr<RemoteDeviceCache> dev_cache_; + std::unique_ptr<PeerCache> peer_cache_; std::unique_ptr<hci::LowEnergyConnector> connector_; std::unique_ptr<LowEnergyConnectionManager> conn_mgr_; // The most recent remote-initiated connection reported by |connector_|. hci::ConnectionPtr last_remote_initiated_; - DeviceList connected_devices_; - DeviceList canceled_devices_; + PeerList connected_peers_; + PeerList canceled_peers_; DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(LowEnergyConnectionManagerTest); }; using GAP_LowEnergyConnectionManagerTest = LowEnergyConnectionManagerTest; -TEST_F(GAP_LowEnergyConnectionManagerTest, ConnectUnknownDevice) { +TEST_F(GAP_LowEnergyConnectionManagerTest, ConnectUnknownPeer) { constexpr DeviceId kUnknownId(1); EXPECT_FALSE(conn_mgr()->Connect(kUnknownId, {})); } -TEST_F(GAP_LowEnergyConnectionManagerTest, ConnectClassicDevice) { - auto* dev = dev_cache()->NewDevice(kAddress2, true); +TEST_F(GAP_LowEnergyConnectionManagerTest, ConnectClassicPeer) { + auto* dev = peer_cache()->NewPeer(kAddress2, true); EXPECT_FALSE(conn_mgr()->Connect(dev->identifier(), {})); } -TEST_F(GAP_LowEnergyConnectionManagerTest, ConnectNonConnectableDevice) { - auto* dev = dev_cache()->NewDevice(kAddress0, false); +TEST_F(GAP_LowEnergyConnectionManagerTest, ConnectNonConnectablePeer) { + auto* dev = peer_cache()->NewPeer(kAddress0, false); EXPECT_FALSE(conn_mgr()->Connect(dev->identifier(), {})); } // An error is received via the HCI Command cb_status event -TEST_F(GAP_LowEnergyConnectionManagerTest, ConnectSingleDeviceErrorStatus) { - auto* dev = dev_cache()->NewDevice(kAddress0, true); +TEST_F(GAP_LowEnergyConnectionManagerTest, ConnectSinglePeerErrorStatus) { + auto* peer = peer_cache()->NewPeer(kAddress0, true); auto fake_peer = std::make_unique<FakePeer>(kAddress0); fake_peer->set_connect_status( hci::StatusCode::kConnectionFailedToBeEstablished); test_device()->AddPeer(std::move(fake_peer)); - ASSERT_TRUE(dev->le()); - EXPECT_EQ(RemoteDevice::ConnectionState::kNotConnected, - dev->le()->connection_state()); + ASSERT_TRUE(peer->le()); + EXPECT_EQ(Peer::ConnectionState::kNotConnected, + peer->le()->connection_state()); hci::Status status; auto callback = [&status](auto cb_status, auto conn_ref) { @@ -193,22 +191,22 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, ConnectSingleDeviceErrorStatus) { status = cb_status; }; - EXPECT_TRUE(conn_mgr()->Connect(dev->identifier(), callback)); - EXPECT_EQ(RemoteDevice::ConnectionState::kInitializing, - dev->le()->connection_state()); + EXPECT_TRUE(conn_mgr()->Connect(peer->identifier(), callback)); + EXPECT_EQ(Peer::ConnectionState::kInitializing, + peer->le()->connection_state()); RunLoopUntilIdle(); EXPECT_TRUE(status.is_protocol_error()); EXPECT_EQ(hci::StatusCode::kConnectionFailedToBeEstablished, status.protocol_error()); - EXPECT_EQ(RemoteDevice::ConnectionState::kNotConnected, - dev->le()->connection_state()); + EXPECT_EQ(Peer::ConnectionState::kNotConnected, + peer->le()->connection_state()); } // LE Connection Complete event reports error -TEST_F(GAP_LowEnergyConnectionManagerTest, ConnectSingleDeviceFailure) { - auto* dev = dev_cache()->NewDevice(kAddress0, true); +TEST_F(GAP_LowEnergyConnectionManagerTest, ConnectSinglePeerFailure) { + auto* peer = peer_cache()->NewPeer(kAddress0, true); auto fake_peer = std::make_unique<FakePeer>(kAddress0); fake_peer->set_connect_response( hci::StatusCode::kConnectionFailedToBeEstablished); @@ -220,26 +218,26 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, ConnectSingleDeviceFailure) { status = cb_status; }; - EXPECT_TRUE(conn_mgr()->Connect(dev->identifier(), callback)); - ASSERT_TRUE(dev->le()); - EXPECT_EQ(RemoteDevice::ConnectionState::kInitializing, - dev->le()->connection_state()); + EXPECT_TRUE(conn_mgr()->Connect(peer->identifier(), callback)); + ASSERT_TRUE(peer->le()); + EXPECT_EQ(Peer::ConnectionState::kInitializing, + peer->le()->connection_state()); RunLoopUntilIdle(); EXPECT_TRUE(status.is_protocol_error()); EXPECT_EQ(hci::StatusCode::kConnectionFailedToBeEstablished, status.protocol_error()); - EXPECT_EQ(RemoteDevice::ConnectionState::kNotConnected, - dev->le()->connection_state()); + EXPECT_EQ(Peer::ConnectionState::kNotConnected, + peer->le()->connection_state()); } -TEST_F(GAP_LowEnergyConnectionManagerTest, ConnectSingleDeviceTimeout) { +TEST_F(GAP_LowEnergyConnectionManagerTest, ConnectSinglePeerTimeout) { constexpr zx::duration kTestRequestTimeout = zx::sec(20); - auto* dev = dev_cache()->NewDevice(kAddress0, true); + auto* peer = peer_cache()->NewPeer(kAddress0, true); - // We add no fake devices to cause the request to time out. + // We add no fake peers to cause the request to time out. hci::Status status; auto callback = [&status](auto cb_status, auto conn_ref) { @@ -248,23 +246,23 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, ConnectSingleDeviceTimeout) { }; conn_mgr()->set_request_timeout_for_testing(kTestRequestTimeout); - EXPECT_TRUE(conn_mgr()->Connect(dev->identifier(), callback)); - ASSERT_TRUE(dev->le()); - EXPECT_EQ(RemoteDevice::ConnectionState::kInitializing, - dev->le()->connection_state()); + EXPECT_TRUE(conn_mgr()->Connect(peer->identifier(), callback)); + ASSERT_TRUE(peer->le()); + EXPECT_EQ(Peer::ConnectionState::kInitializing, + peer->le()->connection_state()); RunLoopFor(kTestRequestTimeout); EXPECT_FALSE(status); EXPECT_EQ(common::HostError::kTimedOut, status.error()) << status.ToString(); - EXPECT_EQ(RemoteDevice::ConnectionState::kNotConnected, - dev->le()->connection_state()); + EXPECT_EQ(Peer::ConnectionState::kNotConnected, + peer->le()->connection_state()); } // Tests that an entry in the cache does not expire while a connection attempt // is pending. TEST_F(GAP_LowEnergyConnectionManagerTest, PeerDoesNotExpireDuringTimeout) { - // Set a connection timeout that is longer than the RemoteDeviceCache expiry + // Set a connection timeout that is longer than the PeerCache expiry // timeout. // TODO(BT-825): Consider configuring the cache timeout explicitly rather than // relying on the kCacheTimeout constant. @@ -272,26 +270,26 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, PeerDoesNotExpireDuringTimeout) { conn_mgr()->set_request_timeout_for_testing(kTestRequestTimeout); // Note: Use a random address so that the peer becomes temporary upon failure. - auto* dev = dev_cache()->NewDevice(kAddress1, true); - EXPECT_TRUE(dev->temporary()); + auto* peer = peer_cache()->NewPeer(kAddress1, true); + EXPECT_TRUE(peer->temporary()); hci::Status status; auto callback = [&status](auto cb_status, auto conn_ref) { EXPECT_FALSE(conn_ref); status = cb_status; }; - EXPECT_TRUE(conn_mgr()->Connect(dev->identifier(), callback)); - ASSERT_TRUE(dev->le()); - EXPECT_EQ(RemoteDevice::ConnectionState::kInitializing, - dev->le()->connection_state()); - EXPECT_FALSE(dev->temporary()); + EXPECT_TRUE(conn_mgr()->Connect(peer->identifier(), callback)); + ASSERT_TRUE(peer->le()); + EXPECT_EQ(Peer::ConnectionState::kInitializing, + peer->le()->connection_state()); + EXPECT_FALSE(peer->temporary()); RunLoopFor(kTestRequestTimeout); EXPECT_EQ(common::HostError::kTimedOut, status.error()) << status.ToString(); - EXPECT_EQ(dev, dev_cache()->FindDeviceByAddress(kAddress1)); - EXPECT_EQ(RemoteDevice::ConnectionState::kNotConnected, - dev->le()->connection_state()); - EXPECT_TRUE(dev->temporary()); + EXPECT_EQ(peer, peer_cache()->FindByAddress(kAddress1)); + EXPECT_EQ(Peer::ConnectionState::kNotConnected, + peer->le()->connection_state()); + EXPECT_TRUE(peer->temporary()); } TEST_F(GAP_LowEnergyConnectionManagerTest, @@ -304,9 +302,9 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, settings.le_connection_delay = kConnectionDelay; test_device()->set_settings(settings); - auto* dev = dev_cache()->NewDevice(kAddress0, true); - auto id = dev->identifier(); - EXPECT_TRUE(dev->temporary()); + auto* peer = peer_cache()->NewPeer(kAddress0, true); + auto id = peer->identifier(); + EXPECT_TRUE(peer->temporary()); auto fake_peer = std::make_unique<FakePeer>(kAddress0); test_device()->AddPeer(std::move(fake_peer)); @@ -327,26 +325,26 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, EXPECT_TRUE(conn_ref->active()); }; EXPECT_TRUE(conn_mgr()->Connect(id, callback)); - ASSERT_TRUE(dev->le()); - EXPECT_EQ(RemoteDevice::ConnectionState::kInitializing, - dev->le()->connection_state()); + ASSERT_TRUE(peer->le()); + EXPECT_EQ(Peer::ConnectionState::kInitializing, + peer->le()->connection_state()); RunLoopFor(kConnectionDelay); ASSERT_TRUE(conn_ref); EXPECT_TRUE(status); - // The device should not have expired during this time. - dev = dev_cache()->FindDeviceByAddress(kAddress0); - ASSERT_TRUE(dev); - EXPECT_EQ(id, dev->identifier()); - EXPECT_TRUE(dev->connected()); - EXPECT_FALSE(dev->temporary()); + // The peer should not have expired during this time. + peer = peer_cache()->FindByAddress(kAddress0); + ASSERT_TRUE(peer); + EXPECT_EQ(id, peer->identifier()); + EXPECT_TRUE(peer->connected()); + EXPECT_FALSE(peer->temporary()); } -// Successful connection to single device -TEST_F(GAP_LowEnergyConnectionManagerTest, ConnectSingleDevice) { - auto* dev = dev_cache()->NewDevice(kAddress0, true); - EXPECT_TRUE(dev->temporary()); +// Successful connection to single peer +TEST_F(GAP_LowEnergyConnectionManagerTest, ConnectSinglePeer) { + auto* peer = peer_cache()->NewPeer(kAddress0, true); + EXPECT_TRUE(peer->temporary()); auto fake_peer = std::make_unique<FakePeer>(kAddress0); test_device()->AddPeer(std::move(fake_peer)); @@ -361,24 +359,23 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, ConnectSingleDevice) { EXPECT_TRUE(conn_ref->active()); }; - EXPECT_TRUE(connected_devices().empty()); - EXPECT_TRUE(conn_mgr()->Connect(dev->identifier(), callback)); - ASSERT_TRUE(dev->le()); - EXPECT_EQ(RemoteDevice::ConnectionState::kInitializing, - dev->le()->connection_state()); + EXPECT_TRUE(connected_peers().empty()); + EXPECT_TRUE(conn_mgr()->Connect(peer->identifier(), callback)); + ASSERT_TRUE(peer->le()); + EXPECT_EQ(Peer::ConnectionState::kInitializing, + peer->le()->connection_state()); RunLoopUntilIdle(); EXPECT_TRUE(status); - EXPECT_EQ(1u, connected_devices().size()); - EXPECT_EQ(1u, connected_devices().count(kAddress0)); + EXPECT_EQ(1u, connected_peers().size()); + EXPECT_EQ(1u, connected_peers().count(kAddress0)); ASSERT_TRUE(conn_ref); EXPECT_TRUE(conn_ref->active()); - EXPECT_EQ(dev->identifier(), conn_ref->device_identifier()); - EXPECT_FALSE(dev->temporary()); - EXPECT_EQ(RemoteDevice::ConnectionState::kConnected, - dev->le()->connection_state()); + EXPECT_EQ(peer->identifier(), conn_ref->peer_identifier()); + EXPECT_FALSE(peer->temporary()); + EXPECT_EQ(Peer::ConnectionState::kConnected, peer->le()->connection_state()); } struct TestObject final : fbl::RefCounted<TestObject> { @@ -393,7 +390,7 @@ struct TestObject final : fbl::RefCounted<TestObject> { }; TEST_F(GAP_LowEnergyConnectionManagerTest, DeleteRefInClosedCallback) { - auto* dev = dev_cache()->NewDevice(kAddress0, true); + auto* peer = peer_cache()->NewPeer(kAddress0, true); test_device()->AddPeer(std::make_unique<FakePeer>(kAddress0)); bool deleted = false; @@ -416,18 +413,18 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, DeleteRefInClosedCallback) { conn_ref->set_closed_callback(std::move(closed_cb)); }; - ASSERT_TRUE(conn_mgr()->Connect(dev->identifier(), success_cb)); + ASSERT_TRUE(conn_mgr()->Connect(peer->identifier(), success_cb)); RunLoopUntilIdle(); ASSERT_TRUE(conn_ref); ASSERT_TRUE(conn_ref->active()); // This will trigger the closed callback. - EXPECT_TRUE(conn_mgr()->Disconnect(dev->identifier())); + EXPECT_TRUE(conn_mgr()->Disconnect(peer->identifier())); RunLoopUntilIdle(); EXPECT_EQ(1, closed_count); - EXPECT_TRUE(connected_devices().empty()); + EXPECT_TRUE(connected_peers().empty()); EXPECT_FALSE(conn_ref); // The object should be deleted. @@ -435,7 +432,7 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, DeleteRefInClosedCallback) { } TEST_F(GAP_LowEnergyConnectionManagerTest, ReleaseRef) { - auto* dev = dev_cache()->NewDevice(kAddress0, true); + auto* peer = peer_cache()->NewPeer(kAddress0, true); auto fake_peer = std::make_unique<FakePeer>(kAddress0); test_device()->AddPeer(std::move(fake_peer)); @@ -449,32 +446,30 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, ReleaseRef) { EXPECT_TRUE(conn_ref->active()); }; - EXPECT_TRUE(connected_devices().empty()); - EXPECT_TRUE(conn_mgr()->Connect(dev->identifier(), callback)); + EXPECT_TRUE(connected_peers().empty()); + EXPECT_TRUE(conn_mgr()->Connect(peer->identifier(), callback)); RunLoopUntilIdle(); EXPECT_TRUE(status); - EXPECT_EQ(1u, connected_devices().size()); - ASSERT_TRUE(dev->le()); - EXPECT_EQ(RemoteDevice::ConnectionState::kConnected, - dev->le()->connection_state()); + EXPECT_EQ(1u, connected_peers().size()); + ASSERT_TRUE(peer->le()); + EXPECT_EQ(Peer::ConnectionState::kConnected, peer->le()->connection_state()); ASSERT_TRUE(conn_ref); conn_ref = nullptr; RunLoopUntilIdle(); - EXPECT_TRUE(connected_devices().empty()); - EXPECT_EQ(RemoteDevice::ConnectionState::kNotConnected, - dev->le()->connection_state()); + EXPECT_TRUE(connected_peers().empty()); + EXPECT_EQ(Peer::ConnectionState::kNotConnected, + peer->le()->connection_state()); } -TEST_F(GAP_LowEnergyConnectionManagerTest, - OneDeviceTwoPendingRequestsBothFail) { +TEST_F(GAP_LowEnergyConnectionManagerTest, OnePeerTwoPendingRequestsBothFail) { constexpr int kRequestCount = 2; - auto* dev = dev_cache()->NewDevice(kAddress0, true); + auto* peer = peer_cache()->NewPeer(kAddress0, true); auto fake_peer = std::make_unique<FakePeer>(kAddress0); fake_peer->set_connect_response( hci::StatusCode::kConnectionFailedToBeEstablished); @@ -489,7 +484,7 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, }; for (int i = 0; i < kRequestCount; ++i) { - EXPECT_TRUE(conn_mgr()->Connect(dev->identifier(), callback)) + EXPECT_TRUE(conn_mgr()->Connect(peer->identifier(), callback)) << "request count: " << i + 1; } @@ -504,10 +499,10 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, } } -TEST_F(GAP_LowEnergyConnectionManagerTest, OneDeviceManyPendingRequests) { +TEST_F(GAP_LowEnergyConnectionManagerTest, OnePeerManyPendingRequests) { constexpr size_t kRequestCount = 50; - auto* dev = dev_cache()->NewDevice(kAddress0, true); + auto* peer = peer_cache()->NewPeer(kAddress0, true); auto fake_peer = std::make_unique<FakePeer>(kAddress0); test_device()->AddPeer(std::move(fake_peer)); @@ -519,20 +514,20 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, OneDeviceManyPendingRequests) { }; for (size_t i = 0; i < kRequestCount; ++i) { - EXPECT_TRUE(conn_mgr()->Connect(dev->identifier(), callback)) + EXPECT_TRUE(conn_mgr()->Connect(peer->identifier(), callback)) << "request count: " << i + 1; } RunLoopUntilIdle(); - EXPECT_EQ(1u, connected_devices().size()); - EXPECT_EQ(1u, connected_devices().count(kAddress0)); + EXPECT_EQ(1u, connected_peers().size()); + EXPECT_EQ(1u, connected_peers().count(kAddress0)); EXPECT_EQ(kRequestCount, conn_refs.size()); for (size_t i = 0; i < kRequestCount; ++i) { ASSERT_TRUE(conn_refs[i]); EXPECT_TRUE(conn_refs[i]->active()); - EXPECT_EQ(dev->identifier(), conn_refs[i]->device_identifier()); + EXPECT_EQ(peer->identifier(), conn_refs[i]->peer_identifier()); } // Release one reference. The rest should be active. @@ -550,13 +545,13 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, OneDeviceManyPendingRequests) { RunLoopUntilIdle(); - EXPECT_TRUE(connected_devices().empty()); + EXPECT_TRUE(connected_peers().empty()); } TEST_F(GAP_LowEnergyConnectionManagerTest, AddRefAfterConnection) { constexpr size_t kRefCount = 50; - auto* dev = dev_cache()->NewDevice(kAddress0, true); + auto* peer = peer_cache()->NewPeer(kAddress0, true); auto fake_peer = std::make_unique<FakePeer>(kAddress0); test_device()->AddPeer(std::move(fake_peer)); @@ -567,23 +562,23 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, AddRefAfterConnection) { conn_refs.emplace_back(std::move(conn_ref)); }; - EXPECT_TRUE(conn_mgr()->Connect(dev->identifier(), callback)); + EXPECT_TRUE(conn_mgr()->Connect(peer->identifier(), callback)); RunLoopUntilIdle(); - EXPECT_EQ(1u, connected_devices().size()); - EXPECT_EQ(1u, connected_devices().count(kAddress0)); + EXPECT_EQ(1u, connected_peers().size()); + EXPECT_EQ(1u, connected_peers().count(kAddress0)); EXPECT_EQ(1u, conn_refs.size()); // Add new references. for (size_t i = 1; i < kRefCount; ++i) { - EXPECT_TRUE(conn_mgr()->Connect(dev->identifier(), callback)) + EXPECT_TRUE(conn_mgr()->Connect(peer->identifier(), callback)) << "request count: " << i + 1; RunLoopUntilIdle(); } - EXPECT_EQ(1u, connected_devices().size()); - EXPECT_EQ(1u, connected_devices().count(kAddress0)); + EXPECT_EQ(1u, connected_peers().size()); + EXPECT_EQ(1u, connected_peers().count(kAddress0)); EXPECT_EQ(kRefCount, conn_refs.size()); // Disconnect. @@ -591,12 +586,12 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, AddRefAfterConnection) { RunLoopUntilIdle(); - EXPECT_TRUE(connected_devices().empty()); + EXPECT_TRUE(connected_peers().empty()); } -TEST_F(GAP_LowEnergyConnectionManagerTest, PendingRequestsOnTwoDevices) { - auto* dev0 = dev_cache()->NewDevice(kAddress0, true); - auto* dev1 = dev_cache()->NewDevice(kAddress1, true); +TEST_F(GAP_LowEnergyConnectionManagerTest, PendingRequestsOnTwoPeers) { + auto* peer0 = peer_cache()->NewPeer(kAddress0, true); + auto* peer1 = peer_cache()->NewPeer(kAddress1, true); test_device()->AddPeer(std::make_unique<FakePeer>(kAddress0)); test_device()->AddPeer(std::make_unique<FakePeer>(kAddress1)); @@ -608,39 +603,38 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, PendingRequestsOnTwoDevices) { conn_refs.emplace_back(std::move(conn_ref)); }; - EXPECT_TRUE(conn_mgr()->Connect(dev0->identifier(), callback)); - EXPECT_TRUE(conn_mgr()->Connect(dev1->identifier(), callback)); + EXPECT_TRUE(conn_mgr()->Connect(peer0->identifier(), callback)); + EXPECT_TRUE(conn_mgr()->Connect(peer1->identifier(), callback)); RunLoopUntilIdle(); - EXPECT_EQ(2u, connected_devices().size()); - EXPECT_EQ(1u, connected_devices().count(kAddress0)); - EXPECT_EQ(1u, connected_devices().count(kAddress1)); + EXPECT_EQ(2u, connected_peers().size()); + EXPECT_EQ(1u, connected_peers().count(kAddress0)); + EXPECT_EQ(1u, connected_peers().count(kAddress1)); ASSERT_EQ(2u, conn_refs.size()); ASSERT_TRUE(conn_refs[0]); ASSERT_TRUE(conn_refs[1]); - EXPECT_EQ(dev0->identifier(), conn_refs[0]->device_identifier()); - EXPECT_EQ(dev1->identifier(), conn_refs[1]->device_identifier()); + EXPECT_EQ(peer0->identifier(), conn_refs[0]->peer_identifier()); + EXPECT_EQ(peer1->identifier(), conn_refs[1]->peer_identifier()); - // |dev1| should disconnect first. + // |peer1| should disconnect first. conn_refs[1] = nullptr; RunLoopUntilIdle(); - EXPECT_EQ(1u, connected_devices().size()); - EXPECT_EQ(1u, connected_devices().count(kAddress0)); + EXPECT_EQ(1u, connected_peers().size()); + EXPECT_EQ(1u, connected_peers().count(kAddress0)); conn_refs.clear(); RunLoopUntilIdle(); - EXPECT_TRUE(connected_devices().empty()); + EXPECT_TRUE(connected_peers().empty()); } -TEST_F(GAP_LowEnergyConnectionManagerTest, - PendingRequestsOnTwoDevicesOneFails) { - auto* dev0 = dev_cache()->NewDevice(kAddress0, true); - auto* dev1 = dev_cache()->NewDevice(kAddress1, true); +TEST_F(GAP_LowEnergyConnectionManagerTest, PendingRequestsOnTwoPeersOneFails) { + auto* peer0 = peer_cache()->NewPeer(kAddress0, true); + auto* peer1 = peer_cache()->NewPeer(kAddress1, true); auto fake_peer0 = std::make_unique<FakePeer>(kAddress0); fake_peer0->set_connect_response( @@ -653,34 +647,34 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, conn_refs.emplace_back(std::move(conn_ref)); }; - EXPECT_TRUE(conn_mgr()->Connect(dev0->identifier(), callback)); - EXPECT_TRUE(conn_mgr()->Connect(dev1->identifier(), callback)); + EXPECT_TRUE(conn_mgr()->Connect(peer0->identifier(), callback)); + EXPECT_TRUE(conn_mgr()->Connect(peer1->identifier(), callback)); RunLoopUntilIdle(); - EXPECT_EQ(1u, connected_devices().size()); - EXPECT_EQ(1u, connected_devices().count(kAddress1)); + EXPECT_EQ(1u, connected_peers().size()); + EXPECT_EQ(1u, connected_peers().count(kAddress1)); ASSERT_EQ(2u, conn_refs.size()); EXPECT_FALSE(conn_refs[0]); ASSERT_TRUE(conn_refs[1]); - EXPECT_EQ(dev1->identifier(), conn_refs[1]->device_identifier()); + EXPECT_EQ(peer1->identifier(), conn_refs[1]->peer_identifier()); // Both connections should disconnect. conn_refs.clear(); RunLoopUntilIdle(); - EXPECT_TRUE(connected_devices().empty()); + EXPECT_TRUE(connected_peers().empty()); } TEST_F(GAP_LowEnergyConnectionManagerTest, Destructor) { - auto* dev0 = dev_cache()->NewDevice(kAddress0, true); - auto* dev1 = dev_cache()->NewDevice(kAddress1, true); + auto* peer0 = peer_cache()->NewPeer(kAddress0, true); + auto* peer1 = peer_cache()->NewPeer(kAddress1, true); - // Connecting to this device will succeed. + // Connecting to this peer will succeed. test_device()->AddPeer(std::make_unique<FakePeer>(kAddress0)); - // Connecting to this device will remain pending. + // Connecting to this peer will remain pending. auto pending_peer = std::make_unique<FakePeer>(kAddress1); pending_peer->set_force_pending_connect(true); test_device()->AddPeer(std::move(pending_peer)); @@ -696,7 +690,7 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, Destructor) { conn_ref = std::move(cb_conn_ref); }; - EXPECT_TRUE(conn_mgr()->Connect(dev0->identifier(), success_cb)); + EXPECT_TRUE(conn_mgr()->Connect(peer0->identifier(), success_cb)); RunLoopUntilIdle(); ASSERT_TRUE(conn_ref); @@ -713,27 +707,27 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, Destructor) { // This will send an HCI command to the fake controller. We delete the // connection manager before a connection event gets received which should // cancel the connection. - EXPECT_TRUE(conn_mgr()->Connect(dev1->identifier(), error_cb)); + EXPECT_TRUE(conn_mgr()->Connect(peer1->identifier(), error_cb)); DeleteConnMgr(); RunLoopUntilIdle(); EXPECT_TRUE(error_cb_called); EXPECT_TRUE(conn_closed); - EXPECT_EQ(1u, canceled_devices().size()); - EXPECT_EQ(1u, canceled_devices().count(kAddress1)); + EXPECT_EQ(1u, canceled_peers().size()); + EXPECT_EQ(1u, canceled_peers().count(kAddress1)); } TEST_F(GAP_LowEnergyConnectionManagerTest, DisconnectError) { - auto* dev = dev_cache()->NewDevice(kAddress0, true); + auto* peer = peer_cache()->NewPeer(kAddress0, true); test_device()->AddPeer(std::make_unique<FakePeer>(kAddress0)); - // This should fail as |dev0| is not connected. - EXPECT_FALSE(conn_mgr()->Disconnect(dev->identifier())); + // This should fail as |peer0| is not connected. + EXPECT_FALSE(conn_mgr()->Disconnect(peer->identifier())); } TEST_F(GAP_LowEnergyConnectionManagerTest, Disconnect) { - auto* dev = dev_cache()->NewDevice(kAddress0, true); + auto* peer = peer_cache()->NewPeer(kAddress0, true); test_device()->AddPeer(std::make_unique<FakePeer>(kAddress0)); int closed_count = 0; @@ -748,25 +742,25 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, Disconnect) { }; // Issue two connection refs. - EXPECT_TRUE(conn_mgr()->Connect(dev->identifier(), success_cb)); - EXPECT_TRUE(conn_mgr()->Connect(dev->identifier(), success_cb)); + EXPECT_TRUE(conn_mgr()->Connect(peer->identifier(), success_cb)); + EXPECT_TRUE(conn_mgr()->Connect(peer->identifier(), success_cb)); RunLoopUntilIdle(); ASSERT_EQ(2u, conn_refs.size()); - EXPECT_TRUE(conn_mgr()->Disconnect(dev->identifier())); + EXPECT_TRUE(conn_mgr()->Disconnect(peer->identifier())); RunLoopUntilIdle(); EXPECT_EQ(2, closed_count); - EXPECT_TRUE(connected_devices().empty()); - EXPECT_TRUE(canceled_devices().empty()); + EXPECT_TRUE(connected_peers().empty()); + EXPECT_TRUE(canceled_peers().empty()); } // Tests when a link is lost without explicitly disconnecting TEST_F(GAP_LowEnergyConnectionManagerTest, DisconnectEvent) { - auto* dev = dev_cache()->NewDevice(kAddress0, true); + auto* peer = peer_cache()->NewPeer(kAddress0, true); test_device()->AddPeer(std::make_unique<FakePeer>(kAddress0)); @@ -782,8 +776,8 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, DisconnectEvent) { }; // Issue two connection refs. - EXPECT_TRUE(conn_mgr()->Connect(dev->identifier(), success_cb)); - EXPECT_TRUE(conn_mgr()->Connect(dev->identifier(), success_cb)); + EXPECT_TRUE(conn_mgr()->Connect(peer->identifier(), success_cb)); + EXPECT_TRUE(conn_mgr()->Connect(peer->identifier(), success_cb)); RunLoopUntilIdle(); @@ -798,7 +792,7 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, DisconnectEvent) { } TEST_F(GAP_LowEnergyConnectionManagerTest, DisconnectWhileRefPending) { - auto* dev = dev_cache()->NewDevice(kAddress0, true); + auto* peer = peer_cache()->NewPeer(kAddress0, true); test_device()->AddPeer(std::make_unique<FakePeer>(kAddress0)); LowEnergyConnectionRefPtr conn_ref; @@ -810,7 +804,7 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, DisconnectWhileRefPending) { conn_ref = std::move(cb_conn_ref); }; - EXPECT_TRUE(conn_mgr()->Connect(dev->identifier(), success_cb)); + EXPECT_TRUE(conn_mgr()->Connect(peer->identifier(), success_cb)); RunLoopUntilIdle(); ASSERT_TRUE(conn_ref); @@ -820,10 +814,10 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, DisconnectWhileRefPending) { EXPECT_EQ(common::HostError::kFailed, status.error()); }; - EXPECT_TRUE(conn_mgr()->Connect(dev->identifier(), ref_cb)); + EXPECT_TRUE(conn_mgr()->Connect(peer->identifier(), ref_cb)); // This should invalidate the ref that was bound to |ref_cb|. - EXPECT_TRUE(conn_mgr()->Disconnect(dev->identifier())); + EXPECT_TRUE(conn_mgr()->Disconnect(peer->identifier())); RunLoopUntilIdle(); } @@ -832,7 +826,7 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, DisconnectWhileRefPending) { // Disconnection Complete event is received for the corresponding ACL link // BEFORE the callback gets run. TEST_F(GAP_LowEnergyConnectionManagerTest, DisconnectEventWhileRefPending) { - auto* dev = dev_cache()->NewDevice(kAddress0, true); + auto* peer = peer_cache()->NewPeer(kAddress0, true); test_device()->AddPeer(std::make_unique<FakePeer>(kAddress0)); LowEnergyConnectionRefPtr conn_ref; @@ -844,7 +838,7 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, DisconnectEventWhileRefPending) { conn_ref = std::move(cb_conn_ref); }; - EXPECT_TRUE(conn_mgr()->Connect(dev->identifier(), success_cb)); + EXPECT_TRUE(conn_mgr()->Connect(peer->identifier(), success_cb)); RunLoopUntilIdle(); ASSERT_TRUE(conn_ref); @@ -856,11 +850,11 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, DisconnectEventWhileRefPending) { EXPECT_EQ(common::HostError::kFailed, status.error()); }; - auto disconn_cb = [this, ref_cb, dev](auto) { + auto disconn_cb = [this, ref_cb, peer](auto) { // The link is gone but conn_mgr() hasn't updated the connection state yet. // The request to connect will attempt to add a new reference which will be // invalidated before |ref_cb| gets called. - EXPECT_TRUE(conn_mgr()->Connect(dev->identifier(), ref_cb)); + EXPECT_TRUE(conn_mgr()->Connect(peer->identifier(), ref_cb)); }; conn_mgr()->SetDisconnectCallbackForTesting(disconn_cb); @@ -885,27 +879,27 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, RegisterRemoteInitiatedLink) { ASSERT_TRUE(conn_ref); EXPECT_TRUE(conn_ref->active()); - // A RemoteDevice should now exist in the cache. - auto* dev = dev_cache()->FindDeviceByAddress(kAddress0); - ASSERT_TRUE(dev); - EXPECT_EQ(dev->identifier(), conn_ref->device_identifier()); - EXPECT_TRUE(dev->connected()); - EXPECT_TRUE(dev->le()->connected()); + // A Peer should now exist in the cache. + auto* peer = peer_cache()->FindByAddress(kAddress0); + ASSERT_TRUE(peer); + EXPECT_EQ(peer->identifier(), conn_ref->peer_identifier()); + EXPECT_TRUE(peer->connected()); + EXPECT_TRUE(peer->le()->connected()); conn_ref = nullptr; RunLoopUntilIdle(); - EXPECT_TRUE(connected_devices().empty()); + EXPECT_TRUE(connected_peers().empty()); } -// Listener receives remote initiated connection ref for a known device with the +// Listener receives remote initiated connection ref for a known peer with the // same BR/EDR address. TEST_F(GAP_LowEnergyConnectionManagerTest, - IncomingConnectionUpgradesKnownBrEdrDeviceToDualMode) { - RemoteDevice* device = dev_cache()->NewDevice(kAddrAlias0, true); - ASSERT_TRUE(device); - ASSERT_EQ(device, dev_cache()->FindDeviceByAddress(kAddress0)); - ASSERT_EQ(TechnologyType::kClassic, device->technology()); + IncomingConnectionUpgradesKnownBrEdrPeerToDualMode) { + Peer* peer = peer_cache()->NewPeer(kAddrAlias0, true); + ASSERT_TRUE(peer); + ASSERT_EQ(peer, peer_cache()->FindByAddress(kAddress0)); + ASSERT_EQ(TechnologyType::kClassic, peer->technology()); test_device()->AddPeer(std::make_unique<FakePeer>(kAddress0)); @@ -921,24 +915,24 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, conn_mgr()->RegisterRemoteInitiatedLink(std::move(link)); ASSERT_TRUE(conn_ref); - EXPECT_EQ(device->identifier(), conn_ref->device_identifier()); - EXPECT_EQ(TechnologyType::kDualMode, device->technology()); + EXPECT_EQ(peer->identifier(), conn_ref->peer_identifier()); + EXPECT_EQ(TechnologyType::kDualMode, peer->technology()); } // Tests that the master accepts the connection parameters that are sent from // a fake slave and eventually applies them to the link. TEST_F(GAP_LowEnergyConnectionManagerTest, L2CAPLEConnectionParameterUpdate) { - // Set up a fake device and a connection over which to process the L2CAP + // Set up a fake peer and a connection over which to process the L2CAP // request. test_device()->AddPeer(std::make_unique<FakePeer>(kAddress0)); - auto* dev = dev_cache()->NewDevice(kAddress0, true); - ASSERT_TRUE(dev); + auto* peer = peer_cache()->NewPeer(kAddress0, true); + ASSERT_TRUE(peer); LowEnergyConnectionRefPtr conn_ref; - auto conn_cb = [&conn_ref](const auto& dev_id, auto cr) { + auto conn_cb = [&conn_ref](const auto& peer_id, auto cr) { conn_ref = std::move(cr); }; - ASSERT_TRUE(conn_mgr()->Connect(dev->identifier(), conn_cb)); + ASSERT_TRUE(conn_mgr()->Connect(peer->identifier(), conn_cb)); RunLoopUntilIdle(); ASSERT_TRUE(conn_ref); @@ -948,18 +942,18 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, L2CAPLEConnectionParameterUpdate) { hci::kLEConnectionLatencyMax, hci::kLEConnectionSupervisionTimeoutMax); hci::LEConnectionParameters actual; - bool fake_dev_cb_called = false; + bool fake_peer_cb_called = false; bool conn_params_cb_called = false; - auto fake_dev_cb = [&actual, &fake_dev_cb_called](const auto& addr, - const auto& params) { - fake_dev_cb_called = true; + auto fake_peer_cb = [&actual, &fake_peer_cb_called](const auto& addr, + const auto& params) { + fake_peer_cb_called = true; actual = params; }; - test_device()->SetLEConnectionParametersCallback(fake_dev_cb, dispatcher()); + test_device()->SetLEConnectionParametersCallback(fake_peer_cb, dispatcher()); - auto conn_params_cb = [&conn_params_cb_called, &conn_ref](const auto& dev) { - EXPECT_EQ(conn_ref->device_identifier(), dev.identifier()); + auto conn_params_cb = [&conn_params_cb_called, &conn_ref](const auto& peer) { + EXPECT_EQ(conn_ref->peer_identifier(), peer.identifier()); conn_params_cb_called = true; }; conn_mgr()->SetConnectionParametersCallbackForTesting(conn_params_cb); @@ -969,41 +963,41 @@ TEST_F(GAP_LowEnergyConnectionManagerTest, L2CAPLEConnectionParameterUpdate) { RunLoopUntilIdle(); - EXPECT_TRUE(fake_dev_cb_called); + EXPECT_TRUE(fake_peer_cb_called); ASSERT_TRUE(conn_params_cb_called); - ASSERT_TRUE(dev->le()); - EXPECT_EQ(preferred, *dev->le()->preferred_connection_parameters()); - EXPECT_EQ(actual, *dev->le()->connection_parameters()); + ASSERT_TRUE(peer->le()); + EXPECT_EQ(preferred, *peer->le()->preferred_connection_parameters()); + EXPECT_EQ(actual, *peer->le()->connection_parameters()); } TEST_F(GAP_LowEnergyConnectionManagerTest, L2CAPSignalLinkError) { - // Set up a fake device and a connection over which to process the L2CAP + // Set up a fake peer and a connection over which to process the L2CAP // request. test_device()->AddPeer(std::make_unique<FakePeer>(kAddress0)); - auto* dev = dev_cache()->NewDevice(kAddress0, true); - ASSERT_TRUE(dev); + auto* peer = peer_cache()->NewPeer(kAddress0, true); + ASSERT_TRUE(peer); fbl::RefPtr<l2cap::Channel> att_chan; auto l2cap_chan_cb = [&att_chan](auto chan) { att_chan = chan; }; fake_l2cap()->set_channel_callback(l2cap_chan_cb); LowEnergyConnectionRefPtr conn_ref; - auto conn_cb = [&conn_ref](const auto& dev_id, auto cr) { + auto conn_cb = [&conn_ref](const auto& peer_id, auto cr) { conn_ref = std::move(cr); }; - ASSERT_TRUE(conn_mgr()->Connect(dev->identifier(), conn_cb)); + ASSERT_TRUE(conn_mgr()->Connect(peer->identifier(), conn_cb)); RunLoopUntilIdle(); ASSERT_TRUE(conn_ref); ASSERT_TRUE(att_chan); - ASSERT_EQ(1u, connected_devices().size()); + ASSERT_EQ(1u, connected_peers().size()); // Signaling a link error through the channel should disconnect the link. att_chan->SignalLinkError(); RunLoopUntilIdle(); - EXPECT_TRUE(connected_devices().empty()); + EXPECT_TRUE(connected_peers().empty()); } } // namespace diff --git a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager.cc b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager.cc index 6a557184307bae00cd3f15f879bec780767bb405..9fbf7773847a3a92323d8e509cdf61130c8a4a6c 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager.cc @@ -6,11 +6,10 @@ #include <zircon/assert.h> +#include "peer.h" +#include "peer_cache.h" #include "src/connectivity/bluetooth/core/bt-host/hci/transport.h" -#include "remote_device.h" -#include "remote_device_cache.h" - namespace bt { namespace gap { @@ -26,15 +25,14 @@ LowEnergyDiscoverySession::~LowEnergyDiscoverySession() { Stop(); } -void LowEnergyDiscoverySession::SetResultCallback( - DeviceFoundCallback callback) { - device_found_callback_ = std::move(callback); +void LowEnergyDiscoverySession::SetResultCallback(PeerFoundCallback callback) { + peer_found_callback_ = std::move(callback); if (!manager_) return; - for (DeviceId cached_device_id : manager_->cached_scan_results()) { - auto device = manager_->device_cache()->FindDeviceById(cached_device_id); - ZX_DEBUG_ASSERT(device); - NotifyDiscoveryResult(*device); + for (DeviceId cached_peer_id : manager_->cached_scan_results()) { + auto peer = manager_->peer_cache()->FindById(cached_peer_id); + ZX_DEBUG_ASSERT(peer); + NotifyDiscoveryResult(*peer); } } @@ -47,13 +45,12 @@ void LowEnergyDiscoverySession::Stop() { active_ = false; } -void LowEnergyDiscoverySession::NotifyDiscoveryResult( - const RemoteDevice& device) const { - ZX_DEBUG_ASSERT(device.le()); - if (device_found_callback_ && - filter_.MatchLowEnergyResult(device.le()->advertising_data(), - device.connectable(), device.rssi())) { - device_found_callback_(device); +void LowEnergyDiscoverySession::NotifyDiscoveryResult(const Peer& peer) const { + ZX_DEBUG_ASSERT(peer.le()); + if (peer_found_callback_ && + filter_.MatchLowEnergyResult(peer.le()->advertising_data(), + peer.connectable(), peer.rssi())) { + peer_found_callback_(peer); } } @@ -65,16 +62,16 @@ void LowEnergyDiscoverySession::NotifyError() { LowEnergyDiscoveryManager::LowEnergyDiscoveryManager( fxl::RefPtr<hci::Transport> hci, hci::LowEnergyScanner* scanner, - RemoteDeviceCache* device_cache) + PeerCache* peer_cache) : dispatcher_(async_get_default_dispatcher()), - device_cache_(device_cache), + peer_cache_(peer_cache), background_scan_enabled_(false), scanner_(scanner), weak_ptr_factory_(this) { ZX_DEBUG_ASSERT(hci); ZX_DEBUG_ASSERT(dispatcher_); ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); - ZX_DEBUG_ASSERT(device_cache_); + ZX_DEBUG_ASSERT(peer_cache_); ZX_DEBUG_ASSERT(scanner_); scanner_->set_delegate(this); @@ -103,7 +100,7 @@ void LowEnergyDiscoveryManager::StartDiscovery(SessionCallback callback) { return; } - // If a device scan is already in progress, then the request succeeds (this + // If a peer scan is already in progress, then the request succeeds (this // includes the state in which we are stopping and restarting scan in between // scan periods). if (!sessions_.empty()) { @@ -179,7 +176,7 @@ void LowEnergyDiscoveryManager::RemoveSession( scanner_->StopScan(); } -void LowEnergyDiscoveryManager::OnDeviceFound( +void LowEnergyDiscoveryManager::OnPeerFound( const hci::LowEnergyScanResult& result, const common::ByteBuffer& data) { ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); @@ -188,16 +185,16 @@ void LowEnergyDiscoveryManager::OnDeviceFound( return; } - auto device = device_cache_->FindDeviceByAddress(result.address); - if (!device) { - device = device_cache_->NewDevice(result.address, result.connectable); + auto peer = peer_cache_->FindByAddress(result.address); + if (!peer) { + peer = peer_cache_->NewPeer(result.address, result.connectable); } - device->MutLe().SetAdvertisingData(result.rssi, data); + peer->MutLe().SetAdvertisingData(result.rssi, data); - cached_scan_results_.insert(device->identifier()); + cached_scan_results_.insert(peer->identifier()); for (const auto& session : sessions_) { - session->NotifyDiscoveryResult(*device); + session->NotifyDiscoveryResult(*peer); } } @@ -211,15 +208,15 @@ void LowEnergyDiscoveryManager::OnDirectedAdvertisement( result.address.ToString().c_str(), (result.resolved ? "resolved" : "not resolved")); - auto device = device_cache_->FindDeviceByAddress(result.address); - if (!device) { + auto peer = peer_cache_->FindByAddress(result.address); + if (!peer) { bt_log(TRACE, "gap", "ignoring connection request from unknown peripheral: %s", result.address.ToString().c_str()); return; } - if (!device->le() || !device->le()->bonded()) { + if (!peer->le() || !peer->le()->bonded()) { bt_log(TRACE, "gap", "rejecting connection request from unbonded peripheral: %s", result.address.ToString().c_str()); @@ -228,9 +225,9 @@ void LowEnergyDiscoveryManager::OnDirectedAdvertisement( // TODO(armansito): We shouldn't always accept connection requests from all // bonded peripherals (e.g. if one is explicitly disconnected). Maybe add an - // "auto_connect()" property to RemoteDevice? + // "auto_connect()" property to Peer? if (directed_conn_cb_) { - directed_conn_cb_(device->identifier()); + directed_conn_cb_(peer->identifier()); } } @@ -361,7 +358,9 @@ void LowEnergyDiscoveryManager::DeactivateAndNotifySessions() { // additional sessions they will be added to pending_ auto sessions = std::move(sessions_); for (const auto& session : sessions) { - if (session->active()) { session->NotifyError(); } + if (session->active()) { + session->NotifyError(); + } } // Due to the move, sessions_ should be empty before the loop and any diff --git a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager.h b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager.h index 5313bcba190b03c626b8f86f65d4b002cae8d57e..b297f183e25e14fadd279a0b529607355af84ea4 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager.h @@ -31,12 +31,12 @@ class Transport; namespace gap { class LowEnergyDiscoveryManager; -class RemoteDevice; -class RemoteDeviceCache; +class Peer; +class PeerCache; -// LowEnergyDiscoveryManager implements GAP LE central/observer role device +// LowEnergyDiscoveryManager implements GAP LE central/observer role // discovery procedures. This class provides mechanisms for multiple clients to -// simultaneously scan for nearby devices filtered by adveritising data +// simultaneously scan for nearby peers filtered by adveritising data // contents. This class also provides hooks for other layers to manage the // Adapter's scan state for other procedures that require it (e.g. connection // establishment, pairing procedures, and other scan and advertising @@ -63,7 +63,7 @@ class RemoteDeviceCache; // PROCEDURE: // // Starting the first discovery session initiates a periodic scan procedure, in -// which the device scan is stopped and restarted for a given scan period (10.24 +// which the scan is stopped and restarted for a given scan period (10.24 // seconds by default). This continues until all sessions have been removed. // // By default duplicate filtering is used which means that a new advertising @@ -83,7 +83,7 @@ class RemoteDeviceCache; // // this callback returns. // session = std::move(new_session); // -// // Only scan for devices advertising the "Heart Rate" GATT Service. +// // Only scan for peers advertising the "Heart Rate" GATT Service. // uint16_t uuid = 0x180d; // session->filter()->set_service_uuids({bt::common::UUID(uuid)}); // session->SetResultCallback([](const @@ -99,7 +99,7 @@ class RemoteDeviceCache; // LowEnergyDiscoveryManager is bound to its creation thread and the associated // dispatcher and must be accessed and destroyed on the same thread. -// Represents a LE device discovery session initiated via +// Represents a LE discovery session initiated via // LowEnergyDiscoveryManager::StartDiscovery(). Instances cannot be created // directly; instead they are handed to callers by LowEnergyDiscoveryManager. // @@ -112,7 +112,7 @@ class LowEnergyDiscoverySession final { // this instance. ~LowEnergyDiscoverySession(); - // Sets a callback for receiving notifications on newly discovered devices. + // Sets a callback for receiving notifications on newly discovered peers. // |data| contains advertising and scan response data (if any) obtained during // discovery. // @@ -120,8 +120,8 @@ class LowEnergyDiscoverySession final { // the cached results from the most recent scan period. If a filter was // assigned earlier, then the callback will only receive results that match // the filter. - using DeviceFoundCallback = fit::function<void(const RemoteDevice& device)>; - void SetResultCallback(DeviceFoundCallback callback); + using PeerFoundCallback = fit::function<void(const Peer& peer)>; + void SetResultCallback(PeerFoundCallback callback); // Sets a callback to get notified when the session becomes inactive due to an // internal error. @@ -130,14 +130,14 @@ class LowEnergyDiscoverySession final { } // Returns the filter that belongs to this session. The caller may modify the - // filter as desired. By default no devices are filtered. + // filter as desired. By default no peers are filtered. // // NOTE: The client is responsible for setting up the filter's "flags" field // for discovery procedures. DiscoveryFilter* filter() { return &filter_; } // Ends this session. This instance will stop receiving notifications for - // devices. + // peers. void Stop(); // Returns true if this session is active. A session is considered inactive @@ -152,7 +152,7 @@ class LowEnergyDiscoverySession final { fxl::WeakPtr<LowEnergyDiscoveryManager> manager); // Called by LowEnergyDiscoveryManager on newly discovered scan results. - void NotifyDiscoveryResult(const RemoteDevice& device) const; + void NotifyDiscoveryResult(const Peer& peer) const; // Marks this session as inactive and notifies the error handler. void NotifyError(); @@ -160,7 +160,7 @@ class LowEnergyDiscoverySession final { bool active_; fxl::WeakPtr<LowEnergyDiscoveryManager> manager_; fit::closure error_callback_; - DeviceFoundCallback device_found_callback_; + PeerFoundCallback peer_found_callback_; DiscoveryFilter filter_; fxl::ThreadChecker thread_checker_; @@ -172,10 +172,10 @@ using LowEnergyDiscoverySessionPtr = std::unique_ptr<LowEnergyDiscoverySession>; // See comments above. class LowEnergyDiscoveryManager final : public hci::LowEnergyScanner::Delegate { public: - // |device_cache| MUST out-live this LowEnergyDiscoveryManager. + // |peer_cache| MUST out-live this LowEnergyDiscoveryManager. LowEnergyDiscoveryManager(fxl::RefPtr<hci::Transport> hci, hci::LowEnergyScanner* scanner, - RemoteDeviceCache* device_cache); + PeerCache* peer_cache); virtual ~LowEnergyDiscoveryManager(); // Starts a new discovery session and reports the result via |callback|. If a @@ -200,7 +200,7 @@ class LowEnergyDiscoveryManager final : public hci::LowEnergyScanner::Delegate { bool discovering() const { return !sessions_.empty(); } // Registers a callback which runs after a directed connectable advertisement - // is received from a bonded device with the given |id|. + // is received from a bonded peer with the given |id|. using DirectedConnectableCallback = fit::function<void(DeviceId id)>; void set_directed_connectable_callback(DirectedConnectableCallback callback) { directed_conn_cb_ = std::move(callback); @@ -209,7 +209,7 @@ class LowEnergyDiscoveryManager final : public hci::LowEnergyScanner::Delegate { private: friend class LowEnergyDiscoverySession; - const RemoteDeviceCache* device_cache() const { return device_cache_; } + const PeerCache* peer_cache() const { return peer_cache_; } const std::unordered_set<DeviceId>& cached_scan_results() const { return cached_scan_results_; @@ -223,8 +223,8 @@ class LowEnergyDiscoveryManager final : public hci::LowEnergyScanner::Delegate { void RemoveSession(LowEnergyDiscoverySession* session); // hci::LowEnergyScanner::Delegate override: - void OnDeviceFound(const hci::LowEnergyScanResult& result, - const common::ByteBuffer& data) override; + void OnPeerFound(const hci::LowEnergyScanResult& result, + const common::ByteBuffer& data) override; void OnDirectedAdvertisement(const hci::LowEnergyScanResult& result) override; // Called by hci::LowEnergyScanner @@ -242,9 +242,9 @@ class LowEnergyDiscoveryManager final : public hci::LowEnergyScanner::Delegate { // The dispatcher that we use for invoking callbacks asynchronously. async_dispatcher_t* dispatcher_; - // The device cache that we use for storing and looking up scan results. We + // The peer cache that we use for storing and looking up scan results. We // hold a raw pointer as we expect this to out-live us. - RemoteDeviceCache* const device_cache_; + PeerCache* const peer_cache_; // True if background scanning is enabled. bool background_scan_enabled_; @@ -266,7 +266,7 @@ class LowEnergyDiscoveryManager final : public hci::LowEnergyScanner::Delegate { std::unordered_set<LowEnergyDiscoverySession*> sessions_; // Identifiers for the cached scan results for the current scan period during - // device discovery. The minimum (and default) scan period is 10.24 seconds + // discovery. The minimum (and default) scan period is 10.24 seconds // when performing LE discovery. This can cause a long wait for a discovery // session that joined in the middle of a scan period and duplicate filtering // is enabled. We maintain this cache to immediately notify new sessions of diff --git a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager_unittest.cc index 527bb075104241e1b2ab300e5bb0cb68b4125abd..cca8ee4cafc399612bfffaa83b0ce79f671ae401 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/low_energy_discovery_manager_unittest.cc @@ -10,8 +10,8 @@ #include <unordered_set> #include <vector> -#include "src/connectivity/bluetooth/core/bt-host/gap/remote_device.h" -#include "src/connectivity/bluetooth/core/bt-host/gap/remote_device_cache.h" +#include "src/connectivity/bluetooth/core/bt-host/gap/peer.h" +#include "src/connectivity/bluetooth/core/bt-host/gap/peer_cache.h" #include "src/connectivity/bluetooth/core/bt-host/hci/fake_local_address_delegate.h" #include "src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner.h" #include "src/connectivity/bluetooth/core/bt-host/testing/fake_controller.h" @@ -62,7 +62,7 @@ class LowEnergyDiscoveryManagerTest : public TestingBase { scanner_ = std::make_unique<hci::LegacyLowEnergyScanner>( &fake_address_delegate_, transport(), dispatcher()); discovery_manager_ = std::make_unique<LowEnergyDiscoveryManager>( - transport(), scanner_.get(), &device_cache_); + transport(), scanner_.get(), &peer_cache_); test_device()->SetScanStateCallback( std::bind(&LowEnergyDiscoveryManagerTest::OnScanStateChanged, this, std::placeholders::_1), @@ -87,7 +87,7 @@ class LowEnergyDiscoveryManagerTest : public TestingBase { // Deletes |discovery_manager_|. void DeleteDiscoveryManager() { discovery_manager_ = nullptr; } - RemoteDeviceCache* device_cache() { return &device_cache_; } + PeerCache* peer_cache() { return &peer_cache_; } // Returns the last reported scan state of the FakeController. bool scan_enabled() const { return scan_enabled_; } @@ -114,30 +114,30 @@ class LowEnergyDiscoveryManagerTest : public TestingBase { } } - // Registers the following fake devices with the FakeController: + // Registers the following fake peers with the FakeController: // - // Device 0: + // Peer 0: // - Connectable, not scannable; // - General discoverable; // - UUIDs: 0x180d, 0x180f; // - has name: "Device 0" // - // Device 1: + // Peer 1: // - Connectable, not scannable; // - Limited discoverable; // - UUIDs: 0x180d; // - has name: "Device 1" // - // Device 2: + // Peer 2: // - Not connectable, not scannable; // - General discoverable; // - UUIDs: none; // - has name: "Device 2" // - // Device 3: + // Peer 3: // - Not discoverable; void AddFakePeers() { - // Device 0 + // Peer 0 const auto kAdvData0 = common::CreateStaticByteBuffer( // Flags 0x02, 0x01, 0x02, @@ -151,7 +151,7 @@ class LowEnergyDiscoveryManagerTest : public TestingBase { fake_peer->SetAdvertisingData(kAdvData0); test_device()->AddPeer(std::move(fake_peer)); - // Device 1 + // Peer 1 const auto kAdvData1 = common::CreateStaticByteBuffer( // Flags 0x02, 0x01, 0x01, @@ -162,7 +162,7 @@ class LowEnergyDiscoveryManagerTest : public TestingBase { fake_peer->SetAdvertisingData(kAdvData1); test_device()->AddPeer(std::move(fake_peer)); - // Device 2 + // Peer 2 const auto kAdvData2 = common::CreateStaticByteBuffer( // Flags 0x02, 0x01, 0x02, @@ -173,7 +173,7 @@ class LowEnergyDiscoveryManagerTest : public TestingBase { fake_peer->SetAdvertisingData(kAdvData2); test_device()->AddPeer(std::move(fake_peer)); - // Device 3 + // Peer 3 const auto kAdvData3 = common::CreateStaticByteBuffer( // Flags 0x02, 0x01, 0x00, @@ -199,7 +199,7 @@ class LowEnergyDiscoveryManagerTest : public TestingBase { } private: - RemoteDeviceCache device_cache_; + PeerCache peer_cache_; hci::FakeLocalAddressDelegate fake_address_delegate_; std::unique_ptr<hci::LegacyLowEnergyScanner> scanner_; std::unique_ptr<LowEnergyDiscoveryManager> discovery_manager_; @@ -273,9 +273,7 @@ TEST_F(GAP_LowEnergyDiscoveryManagerTest, Destructor) { EXPECT_TRUE(session->active()); size_t num_errors = 0u; - session->set_error_callback([&num_errors](){ - num_errors++; - }); + session->set_error_callback([&num_errors]() { num_errors++; }); EXPECT_EQ(0u, num_errors); DeleteDiscoveryManager(); @@ -623,29 +621,29 @@ TEST_F(GAP_LowEnergyDiscoveryManagerTest, StartDiscoveryWithFilters) { discovery_manager()->set_scan_period(zx::msec(200)); // Session 0 is interested in performing general discovery. - std::unordered_set<common::DeviceAddress> devices_session0; - LowEnergyDiscoverySession::DeviceFoundCallback result_cb = - [&devices_session0](const auto& device) { - devices_session0.insert(device.address()); + std::unordered_set<common::DeviceAddress> peers_session0; + LowEnergyDiscoverySession::PeerFoundCallback result_cb = + [&peers_session0](const auto& peer) { + peers_session0.insert(peer.address()); }; sessions.push_back(StartDiscoverySession()); sessions[0]->filter()->SetGeneralDiscoveryFlags(); sessions[0]->SetResultCallback(std::move(result_cb)); // Session 1 is interested in performing limited discovery. - std::unordered_set<common::DeviceAddress> devices_session1; - result_cb = [&devices_session1](const auto& device) { - devices_session1.insert(device.address()); + std::unordered_set<common::DeviceAddress> peers_session1; + result_cb = [&peers_session1](const auto& peer) { + peers_session1.insert(peer.address()); }; sessions.push_back(StartDiscoverySession()); sessions[1]->filter()->set_flags( static_cast<uint8_t>(AdvFlag::kLELimitedDiscoverableMode)); sessions[1]->SetResultCallback(std::move(result_cb)); - // Session 2 is interested in devices with UUID 0x180d. - std::unordered_set<common::DeviceAddress> devices_session2; - result_cb = [&devices_session2](const auto& device) { - devices_session2.insert(device.address()); + // Session 2 is interested in peers with UUID 0x180d. + std::unordered_set<common::DeviceAddress> peers_session2; + result_cb = [&peers_session2](const auto& peer) { + peers_session2.insert(peer.address()); }; sessions.push_back(StartDiscoverySession()); @@ -653,19 +651,19 @@ TEST_F(GAP_LowEnergyDiscoveryManagerTest, StartDiscoveryWithFilters) { sessions[2]->filter()->set_service_uuids({common::UUID(uuid)}); sessions[2]->SetResultCallback(std::move(result_cb)); - // Session 3 is interested in devices whose names contain "Device". - std::unordered_set<common::DeviceAddress> devices_session3; - result_cb = [&devices_session3](const auto& device) { - devices_session3.insert(device.address()); + // Session 3 is interested in peers whose names contain "Device". + std::unordered_set<common::DeviceAddress> peers_session3; + result_cb = [&peers_session3](const auto& peer) { + peers_session3.insert(peer.address()); }; sessions.push_back(StartDiscoverySession()); sessions[3]->filter()->set_name_substring("Device"); sessions[3]->SetResultCallback(std::move(result_cb)); - // Session 4 is interested in non-connectable devices. - std::unordered_set<common::DeviceAddress> devices_session4; - result_cb = [&devices_session4](const auto& device) { - devices_session4.insert(device.address()); + // Session 4 is interested in non-connectable peers. + std::unordered_set<common::DeviceAddress> peers_session4; + result_cb = [&peers_session4](const auto& peer) { + peers_session4.insert(peer.address()); }; sessions.push_back(StartDiscoverySession()); sessions[4]->filter()->set_connectable(false); @@ -677,40 +675,40 @@ TEST_F(GAP_LowEnergyDiscoveryManagerTest, StartDiscoveryWithFilters) { #define EXPECT_CONTAINS(addr, dev_list) \ EXPECT_TRUE(dev_list.find(addr) != dev_list.end()) - // At this point all sessions should have processed all devices at least once. + // At this point all sessions should have processed all peers at least once. - // Session 0: Should have seen all devices except for device 3, which is + // Session 0: Should have seen all peers except for peer 3, which is // non-discoverable. - EXPECT_EQ(3u, devices_session0.size()); - EXPECT_CONTAINS(kAddress0, devices_session0); - EXPECT_CONTAINS(kAddress1, devices_session0); - EXPECT_CONTAINS(kAddress2, devices_session0); - - // Session 1: Should have only seen device 1. - EXPECT_EQ(1u, devices_session1.size()); - EXPECT_CONTAINS(kAddress1, devices_session1); - - // Session 2: Should have only seen devices 0 and 1 - EXPECT_EQ(2u, devices_session2.size()); - EXPECT_CONTAINS(kAddress0, devices_session2); - EXPECT_CONTAINS(kAddress1, devices_session2); - - // Session 3: Should have only seen devices 0, 2, and 3 - EXPECT_EQ(3u, devices_session3.size()); - EXPECT_CONTAINS(kAddress0, devices_session3); - EXPECT_CONTAINS(kAddress2, devices_session3); - EXPECT_CONTAINS(kAddress3, devices_session3); - - // Session 4: Should have seen devices 2 - EXPECT_EQ(2u, devices_session4.size()); - EXPECT_CONTAINS(kAddress2, devices_session4); - EXPECT_CONTAINS(kAddress3, devices_session4); + EXPECT_EQ(3u, peers_session0.size()); + EXPECT_CONTAINS(kAddress0, peers_session0); + EXPECT_CONTAINS(kAddress1, peers_session0); + EXPECT_CONTAINS(kAddress2, peers_session0); + + // Session 1: Should have only seen peer 1. + EXPECT_EQ(1u, peers_session1.size()); + EXPECT_CONTAINS(kAddress1, peers_session1); + + // Session 2: Should have only seen peers 0 and 1 + EXPECT_EQ(2u, peers_session2.size()); + EXPECT_CONTAINS(kAddress0, peers_session2); + EXPECT_CONTAINS(kAddress1, peers_session2); + + // Session 3: Should have only seen peers 0, 2, and 3 + EXPECT_EQ(3u, peers_session3.size()); + EXPECT_CONTAINS(kAddress0, peers_session3); + EXPECT_CONTAINS(kAddress2, peers_session3); + EXPECT_CONTAINS(kAddress3, peers_session3); + + // Session 4: Should have seen peers 2 and 3 + EXPECT_EQ(2u, peers_session4.size()); + EXPECT_CONTAINS(kAddress2, peers_session4); + EXPECT_CONTAINS(kAddress3, peers_session4); #undef EXPECT_CONTAINS } TEST_F(GAP_LowEnergyDiscoveryManagerTest, - StartDiscoveryWithFiltersCachedDeviceNotifications) { + StartDiscoveryWithFiltersCachedPeerNotifications) { AddFakePeers(); std::vector<std::unique_ptr<LowEnergyDiscoverySession>> sessions; @@ -720,32 +718,32 @@ TEST_F(GAP_LowEnergyDiscoveryManagerTest, discovery_manager()->set_scan_period(zx::sec(20)); // Session 0 is interested in performing general discovery. - std::unordered_set<common::DeviceAddress> devices_session0; - LowEnergyDiscoverySession::DeviceFoundCallback result_cb = - [this, &devices_session0](const auto& device) { - devices_session0.insert(device.address()); + std::unordered_set<common::DeviceAddress> peers_session0; + LowEnergyDiscoverySession::PeerFoundCallback result_cb = + [this, &peers_session0](const auto& peer) { + peers_session0.insert(peer.address()); }; sessions.push_back(StartDiscoverySession()); sessions[0]->filter()->SetGeneralDiscoveryFlags(); sessions[0]->SetResultCallback(std::move(result_cb)); RunLoopUntilIdle(); - ASSERT_EQ(3u, devices_session0.size()); + ASSERT_EQ(3u, peers_session0.size()); // Session 1 is interested in performing limited discovery. - std::unordered_set<common::DeviceAddress> devices_session1; - result_cb = [&devices_session1](const auto& device) { - devices_session1.insert(device.address()); + std::unordered_set<common::DeviceAddress> peers_session1; + result_cb = [&peers_session1](const auto& peer) { + peers_session1.insert(peer.address()); }; sessions.push_back(StartDiscoverySession()); sessions[1]->filter()->set_flags( static_cast<uint8_t>(AdvFlag::kLELimitedDiscoverableMode)); sessions[1]->SetResultCallback(std::move(result_cb)); - // Session 2 is interested in devices with UUID 0x180d. - std::unordered_set<common::DeviceAddress> devices_session2; - result_cb = [&devices_session2](const auto& device) { - devices_session2.insert(device.address()); + // Session 2 is interested in peers with UUID 0x180d. + std::unordered_set<common::DeviceAddress> peers_session2; + result_cb = [&peers_session2](const auto& peer) { + peers_session2.insert(peer.address()); }; sessions.push_back(StartDiscoverySession()); @@ -753,19 +751,19 @@ TEST_F(GAP_LowEnergyDiscoveryManagerTest, sessions[2]->filter()->set_service_uuids({common::UUID(uuid)}); sessions[2]->SetResultCallback(std::move(result_cb)); - // Session 3 is interested in devices whose names contain "Device". - std::unordered_set<common::DeviceAddress> devices_session3; - result_cb = [&devices_session3](const auto& device) { - devices_session3.insert(device.address()); + // Session 3 is interested in peers whose names contain "Device". + std::unordered_set<common::DeviceAddress> peers_session3; + result_cb = [&peers_session3](const auto& peer) { + peers_session3.insert(peer.address()); }; sessions.push_back(StartDiscoverySession()); sessions[3]->filter()->set_name_substring("Device"); sessions[3]->SetResultCallback(std::move(result_cb)); - // Session 4 is interested in non-connectable devices. - std::unordered_set<common::DeviceAddress> devices_session4; - result_cb = [&devices_session4](const auto& device) { - devices_session4.insert(device.address()); + // Session 4 is interested in non-connectable peers. + std::unordered_set<common::DeviceAddress> peers_session4; + result_cb = [&peers_session4](const auto& peer) { + peers_session4.insert(peer.address()); }; sessions.push_back(StartDiscoverySession()); sessions[4]->filter()->set_connectable(false); @@ -775,36 +773,36 @@ TEST_F(GAP_LowEnergyDiscoveryManagerTest, #define EXPECT_CONTAINS(addr, dev_list) \ EXPECT_TRUE(dev_list.find(addr) != dev_list.end()) - // At this point all sessions should have processed all devices at least once + // At this point all sessions should have processed all peers at least once // without running the message loop; results for Sessions 1, 2, 3, and 4 // should have come from the cache. - // Session 0: Should have seen all devices except for device 3, which is + // Session 0: Should have seen all peers except for peer 3, which is // non-discoverable. - EXPECT_EQ(3u, devices_session0.size()); - EXPECT_CONTAINS(kAddress0, devices_session0); - EXPECT_CONTAINS(kAddress1, devices_session0); - EXPECT_CONTAINS(kAddress2, devices_session0); - - // Session 1: Should have only seen device 1. - EXPECT_EQ(1u, devices_session1.size()); - EXPECT_CONTAINS(kAddress1, devices_session1); - - // Session 2: Should have only seen devices 0 and 1 - EXPECT_EQ(2u, devices_session2.size()); - EXPECT_CONTAINS(kAddress0, devices_session2); - EXPECT_CONTAINS(kAddress1, devices_session2); - - // Session 3: Should have only seen devices 0, 2, and 3 - EXPECT_EQ(3u, devices_session3.size()); - EXPECT_CONTAINS(kAddress0, devices_session3); - EXPECT_CONTAINS(kAddress2, devices_session3); - EXPECT_CONTAINS(kAddress3, devices_session3); - - // Session 4: Should have seen devices 2 and 3 - EXPECT_EQ(2u, devices_session4.size()); - EXPECT_CONTAINS(kAddress2, devices_session4); - EXPECT_CONTAINS(kAddress3, devices_session4); + EXPECT_EQ(3u, peers_session0.size()); + EXPECT_CONTAINS(kAddress0, peers_session0); + EXPECT_CONTAINS(kAddress1, peers_session0); + EXPECT_CONTAINS(kAddress2, peers_session0); + + // Session 1: Should have only seen peer 1. + EXPECT_EQ(1u, peers_session1.size()); + EXPECT_CONTAINS(kAddress1, peers_session1); + + // Session 2: Should have only seen peers 0 and 1 + EXPECT_EQ(2u, peers_session2.size()); + EXPECT_CONTAINS(kAddress0, peers_session2); + EXPECT_CONTAINS(kAddress1, peers_session2); + + // Session 3: Should have only seen peers 0, 2, and 3 + EXPECT_EQ(3u, peers_session3.size()); + EXPECT_CONTAINS(kAddress0, peers_session3); + EXPECT_CONTAINS(kAddress2, peers_session3); + EXPECT_CONTAINS(kAddress3, peers_session3); + + // Session 4: Should have seen peers 2 and 3 + EXPECT_EQ(2u, peers_session4.size()); + EXPECT_CONTAINS(kAddress2, peers_session4); + EXPECT_CONTAINS(kAddress3, peers_session4); #undef EXPECT_CONTAINS } @@ -819,19 +817,19 @@ TEST_F(GAP_LowEnergyDiscoveryManagerTest, DirectedConnectableEvent) { [&](const auto&) { count++; }); discovery_manager()->set_scan_period(kTestScanPeriod); - // Start discovery. Advertisements from the device should be ignored since the - // device is not bonded. + // Start discovery. Advertisements from the peer should be ignored since the + // peer is not bonded. auto session = StartDiscoverySession(); RunLoopUntilIdle(); ASSERT_TRUE(session); EXPECT_EQ(0, count); - // Mark the device as bonded. + // Mark the peer as bonded. constexpr DeviceId kDeviceId(1); sm::PairingData pdata; pdata.ltk = sm::LTK(); - device_cache()->AddBondedDevice(kDeviceId, kAddress0, pdata, {}); - EXPECT_EQ(1u, device_cache()->count()); + peer_cache()->AddBondedPeer(kDeviceId, kAddress0, pdata, {}); + EXPECT_EQ(1u, peer_cache()->count()); // Advance to the next scan period. We should receive a new notification. RunLoopFor(kTestScanPeriod); @@ -839,20 +837,20 @@ TEST_F(GAP_LowEnergyDiscoveryManagerTest, DirectedConnectableEvent) { } TEST_F(GAP_LowEnergyDiscoveryManagerTest, - ScanResuiltUpgradesKnownBrEdrDeviceToDualMode) { - RemoteDevice* device = device_cache()->NewDevice(kAddrAlias0, true); - ASSERT_TRUE(device); - ASSERT_EQ(device, device_cache()->FindDeviceByAddress(kAddress0)); - ASSERT_EQ(TechnologyType::kClassic, device->technology()); + ScanResuiltUpgradesKnownBrEdrPeerToDualMode) { + Peer* peer = peer_cache()->NewPeer(kAddrAlias0, true); + ASSERT_TRUE(peer); + ASSERT_EQ(peer, peer_cache()->FindByAddress(kAddress0)); + ASSERT_EQ(TechnologyType::kClassic, peer->technology()); AddFakePeers(); discovery_manager()->set_scan_period(kTestScanPeriod); std::unordered_set<common::DeviceAddress> addresses_found; - LowEnergyDiscoverySession::DeviceFoundCallback result_cb = - [&addresses_found](const auto& device) { - addresses_found.insert(device.address()); + LowEnergyDiscoverySession::PeerFoundCallback result_cb = + [&addresses_found](const auto& peer) { + addresses_found.insert(peer.address()); }; auto session = StartDiscoverySession(); session->filter()->SetGeneralDiscoveryFlags(); @@ -862,7 +860,7 @@ TEST_F(GAP_LowEnergyDiscoveryManagerTest, ASSERT_EQ(3u, addresses_found.size()); EXPECT_TRUE(addresses_found.find(kAddrAlias0) != addresses_found.end()); - EXPECT_EQ(TechnologyType::kDualMode, device->technology()); + EXPECT_EQ(TechnologyType::kDualMode, peer->technology()); } TEST_F(GAP_LowEnergyDiscoveryManagerTest, EnableBackgroundScan) { @@ -1022,22 +1020,22 @@ TEST_F(GAP_LowEnergyDiscoveryManagerTest, } TEST_F(GAP_LowEnergyDiscoveryManagerTest, - BackgroundScanOnlyHandlesDirectedEventsFromBondedDevices) { + BackgroundScanOnlyHandlesDirectedEventsFromBondedPeers) { DeviceId kBondedDeviceId(1); AddFakePeers(); - // Add a bonded device. + // Add a bonded peer. auto fake_peer = std::make_unique<FakePeer>(kAddress0, true, false); fake_peer->enable_directed_advertising(true); test_device()->AddPeer(std::move(fake_peer)); sm::PairingData pdata; pdata.ltk = sm::LTK(); - device_cache()->AddBondedDevice(kBondedDeviceId, kAddress0, pdata, {}); - EXPECT_EQ(1u, device_cache()->count()); + peer_cache()->AddBondedPeer(kBondedDeviceId, kAddress0, pdata, {}); + EXPECT_EQ(1u, peer_cache()->count()); - // Add a second device the sends directed advertisements but do not mark it as - // bonded. Advertisements from this device should be ignored. + // Add a second peer the sends directed advertisements but do not mark it as + // bonded. Advertisements from this peer should be ignored. fake_peer = std::make_unique<FakePeer>(kAddress1, true, false); fake_peer->enable_directed_advertising(true); test_device()->AddPeer(std::move(fake_peer)); @@ -1051,8 +1049,8 @@ TEST_F(GAP_LowEnergyDiscoveryManagerTest, RunLoopUntilIdle(); EXPECT_EQ(1, count); - // No new remote device cache entries should have been created. - EXPECT_EQ(1u, device_cache()->count()); + // No new remote peer cache entries should have been created. + EXPECT_EQ(1u, peer_cache()->count()); } TEST_F(GAP_LowEnergyDiscoveryManagerTest, BackgroundScanPeriodRestart) { diff --git a/src/connectivity/bluetooth/core/bt-host/gap/remote_device.cc b/src/connectivity/bluetooth/core/bt-host/gap/peer.cc similarity index 65% rename from src/connectivity/bluetooth/core/bt-host/gap/remote_device.cc rename to src/connectivity/bluetooth/core/bt-host/gap/peer.cc index ecc23a8c6484d6e84a686b5a0fa240238bdd8680..34ec8edd5785397bb42ae28d3b0e6317c957ef82 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/remote_device.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/peer.cc @@ -2,16 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "remote_device.h" +#include "peer.h" #include <zircon/assert.h> +#include "advertising_data.h" #include "src/connectivity/bluetooth/core/bt-host/gap/advertising_data.h" #include "src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.h" #include "src/lib/fxl/strings/string_printf.h" -#include "advertising_data.h" - namespace bt { using common::BufferView; @@ -22,13 +21,13 @@ using common::DynamicByteBuffer; namespace gap { namespace { -std::string ConnectionStateToString(RemoteDevice::ConnectionState state) { +std::string ConnectionStateToString(Peer::ConnectionState state) { switch (state) { - case RemoteDevice::ConnectionState::kNotConnected: + case Peer::ConnectionState::kNotConnected: return "not connected"; - case RemoteDevice::ConnectionState::kInitializing: + case Peer::ConnectionState::kInitializing: return "connecting"; - case RemoteDevice::ConnectionState::kConnected: + case Peer::ConnectionState::kConnected: return "connected"; } @@ -38,19 +37,19 @@ std::string ConnectionStateToString(RemoteDevice::ConnectionState state) { } // namespace -RemoteDevice::LowEnergyData::LowEnergyData(RemoteDevice* owner) - : dev_(owner), +Peer::LowEnergyData::LowEnergyData(Peer* owner) + : peer_(owner), conn_state_(ConnectionState::kNotConnected), adv_data_len_(0u) { - ZX_DEBUG_ASSERT(dev_); + ZX_DEBUG_ASSERT(peer_); } -void RemoteDevice::LowEnergyData::SetAdvertisingData( - int8_t rssi, const common::ByteBuffer& adv) { - // Prolong this device's expiration in case it is temporary. - dev_->UpdateExpiry(); +void Peer::LowEnergyData::SetAdvertisingData(int8_t rssi, + const common::ByteBuffer& adv) { + // Prolong this peer's expiration in case it is temporary. + peer_->UpdateExpiry(); - bool notify_listeners = dev_->SetRssiInternal(rssi); + bool notify_listeners = peer_->SetRssiInternal(rssi); // Update the advertising data // TODO(armansito): Validate that the advertising data is not malformed? @@ -60,7 +59,7 @@ void RemoteDevice::LowEnergyData::SetAdvertisingData( adv_data_len_ = adv.size(); adv.Copy(&adv_data_buffer_); - // Walk through the advertising data and update common device fields. + // Walk through the advertising data and update common fields. AdvertisingDataReader reader(adv); gap::DataType type; BufferView data; @@ -71,20 +70,20 @@ void RemoteDevice::LowEnergyData::SetAdvertisingData( // connection parameters. // TODO(NET-607): SetName should be a no-op if a name was obtained via // the name discovery procedure. - if (dev_->SetNameInternal(data.ToString())) { + if (peer_->SetNameInternal(data.ToString())) { notify_listeners = true; } } } if (notify_listeners) { - dev_->UpdateExpiry(); - dev_->NotifyListeners(); + peer_->UpdateExpiry(); + peer_->NotifyListeners(); } } -void RemoteDevice::LowEnergyData::SetConnectionState(ConnectionState state) { - ZX_DEBUG_ASSERT(dev_->connectable() || +void Peer::LowEnergyData::SetConnectionState(ConnectionState state) { + ZX_DEBUG_ASSERT(peer_->connectable() || state == ConnectionState::kNotConnected); if (state == connection_state()) { @@ -95,7 +94,7 @@ void RemoteDevice::LowEnergyData::SetConnectionState(ConnectionState state) { bt_log(TRACE, "gap-le", "peer (%s) LE connection state changed from \"%s\" to \"%s\"", - bt_str(dev_->identifier()), + bt_str(peer_->identifier()), ConnectionStateToString(connection_state()).c_str(), ConnectionStateToString(state).c_str()); @@ -105,94 +104,92 @@ void RemoteDevice::LowEnergyData::SetConnectionState(ConnectionState state) { // Otherwise, become temporary again if the identity is unknown. if (state == ConnectionState::kInitializing || state == ConnectionState::kConnected) { - dev_->TryMakeNonTemporary(); + peer_->TryMakeNonTemporary(); } else if (state == ConnectionState::kNotConnected && - !dev_->identity_known()) { - bt_log(TRACE, "gap", "became temporary: %s:", bt_str(*dev_)); - dev_->temporary_ = true; + !peer_->identity_known()) { + bt_log(TRACE, "gap", "became temporary: %s:", bt_str(*peer_)); + peer_->temporary_ = true; } - dev_->UpdateExpiry(); - dev_->NotifyListeners(); + peer_->UpdateExpiry(); + peer_->NotifyListeners(); } -void RemoteDevice::LowEnergyData::SetConnectionParameters( +void Peer::LowEnergyData::SetConnectionParameters( const hci::LEConnectionParameters& params) { - ZX_DEBUG_ASSERT(dev_->connectable()); + ZX_DEBUG_ASSERT(peer_->connectable()); conn_params_ = params; } -void RemoteDevice::LowEnergyData::SetPreferredConnectionParameters( +void Peer::LowEnergyData::SetPreferredConnectionParameters( const hci::LEPreferredConnectionParameters& params) { - ZX_DEBUG_ASSERT(dev_->connectable()); + ZX_DEBUG_ASSERT(peer_->connectable()); preferred_conn_params_ = params; } -void RemoteDevice::LowEnergyData::SetBondData( - const sm::PairingData& bond_data) { - ZX_DEBUG_ASSERT(dev_->connectable()); - ZX_DEBUG_ASSERT(dev_->address().type() != DeviceAddress::Type::kLEAnonymous); +void Peer::LowEnergyData::SetBondData(const sm::PairingData& bond_data) { + ZX_DEBUG_ASSERT(peer_->connectable()); + ZX_DEBUG_ASSERT(peer_->address().type() != DeviceAddress::Type::kLEAnonymous); - // Make sure the device is non-temporary. - dev_->TryMakeNonTemporary(); + // Make sure the peer is non-temporary. + peer_->TryMakeNonTemporary(); - // This will mark the device as bonded + // This will mark the peer as bonded bond_data_ = bond_data; // Update to the new identity address if the current address is random. - if (dev_->address().type() == DeviceAddress::Type::kLERandom && + if (peer_->address().type() == DeviceAddress::Type::kLERandom && bond_data.identity_address) { - dev_->set_identity_known(true); - dev_->set_address(*bond_data.identity_address); + peer_->set_identity_known(true); + peer_->set_address(*bond_data.identity_address); } - dev_->NotifyListeners(); + peer_->NotifyListeners(); } -void RemoteDevice::LowEnergyData::ClearBondData() { +void Peer::LowEnergyData::ClearBondData() { ZX_ASSERT(bond_data_); if (bond_data_->irk) { - dev_->set_identity_known(false); + peer_->set_identity_known(false); } bond_data_ = std::nullopt; } -RemoteDevice::BrEdrData::BrEdrData(RemoteDevice* owner) - : dev_(owner), conn_state_(ConnectionState::kNotConnected), eir_len_(0u) { - ZX_DEBUG_ASSERT(dev_); - ZX_DEBUG_ASSERT(dev_->identity_known()); +Peer::BrEdrData::BrEdrData(Peer* owner) + : peer_(owner), conn_state_(ConnectionState::kNotConnected), eir_len_(0u) { + ZX_DEBUG_ASSERT(peer_); + ZX_DEBUG_ASSERT(peer_->identity_known()); // Devices that are capable of BR/EDR and use a LE random device address will // end up with separate entries for the BR/EDR and LE addresses. - ZX_DEBUG_ASSERT(dev_->address().type() != DeviceAddress::Type::kLERandom && - dev_->address().type() != DeviceAddress::Type::kLEAnonymous); - address_ = {DeviceAddress::Type::kBREDR, dev_->address().value()}; + ZX_DEBUG_ASSERT(peer_->address().type() != DeviceAddress::Type::kLERandom && + peer_->address().type() != DeviceAddress::Type::kLEAnonymous); + address_ = {DeviceAddress::Type::kBREDR, peer_->address().value()}; } -void RemoteDevice::BrEdrData::SetInquiryData(const hci::InquiryResult& value) { - ZX_DEBUG_ASSERT(dev_->address().value() == value.bd_addr); +void Peer::BrEdrData::SetInquiryData(const hci::InquiryResult& value) { + ZX_DEBUG_ASSERT(peer_->address().value() == value.bd_addr); SetInquiryData(value.class_of_device, value.clock_offset, value.page_scan_repetition_mode); } -void RemoteDevice::BrEdrData::SetInquiryData( - const hci::InquiryResultRSSI& value) { - ZX_DEBUG_ASSERT(dev_->address().value() == value.bd_addr); +void Peer::BrEdrData::SetInquiryData(const hci::InquiryResultRSSI& value) { + ZX_DEBUG_ASSERT(peer_->address().value() == value.bd_addr); SetInquiryData(value.class_of_device, value.clock_offset, value.page_scan_repetition_mode, value.rssi); } -void RemoteDevice::BrEdrData::SetInquiryData( +void Peer::BrEdrData::SetInquiryData( const hci::ExtendedInquiryResultEventParams& value) { - ZX_DEBUG_ASSERT(dev_->address().value() == value.bd_addr); + ZX_DEBUG_ASSERT(peer_->address().value() == value.bd_addr); SetInquiryData(value.class_of_device, value.clock_offset, value.page_scan_repetition_mode, value.rssi, BufferView(value.extended_inquiry_response, sizeof(value.extended_inquiry_response))); } -void RemoteDevice::BrEdrData::SetConnectionState(ConnectionState state) { - ZX_DEBUG_ASSERT(dev_->connectable() || +void Peer::BrEdrData::SetConnectionState(ConnectionState state) { + ZX_DEBUG_ASSERT(peer_->connectable() || state == ConnectionState::kNotConnected); if (state == connection_state()) { @@ -203,32 +200,32 @@ void RemoteDevice::BrEdrData::SetConnectionState(ConnectionState state) { bt_log(TRACE, "gap-bredr", "peer (%s) BR/EDR connection state changed from \"%s\" to \"%s\"", - bt_str(dev_->identifier()), + bt_str(peer_->identifier()), ConnectionStateToString(connection_state()).c_str(), ConnectionStateToString(state).c_str()); conn_state_ = state; - dev_->UpdateExpiry(); - dev_->NotifyListeners(); + peer_->UpdateExpiry(); + peer_->NotifyListeners(); // Become non-temporary if we became connected. BR/EDR device remain // non-temporary afterwards. if (state == ConnectionState::kConnected) { - dev_->TryMakeNonTemporary(); + peer_->TryMakeNonTemporary(); } } -void RemoteDevice::BrEdrData::SetInquiryData( +void Peer::BrEdrData::SetInquiryData( common::DeviceClass device_class, uint16_t clock_offset, hci::PageScanRepetitionMode page_scan_rep_mode, int8_t rssi, const common::BufferView& eir_data) { - dev_->UpdateExpiry(); + peer_->UpdateExpiry(); bool notify_listeners = false; // TODO(armansito): Consider sending notifications for RSSI updates perhaps // with throttling to avoid spamming. - dev_->SetRssiInternal(rssi); + peer_->SetRssiInternal(rssi); page_scan_rep_mode_ = page_scan_rep_mode; clock_offset_ = static_cast<uint16_t>(hci::kClockOffsetValidFlagBit | @@ -244,11 +241,11 @@ void RemoteDevice::BrEdrData::SetInquiryData( } if (notify_listeners) { - dev_->NotifyListeners(); + peer_->NotifyListeners(); } } -bool RemoteDevice::BrEdrData::SetEirData(const common::ByteBuffer& eir) { +bool Peer::BrEdrData::SetEirData(const common::ByteBuffer& eir) { ZX_DEBUG_ASSERT(eir.size()); // TODO(armansito): Validate that the EIR data is not malformed? @@ -268,34 +265,33 @@ bool RemoteDevice::BrEdrData::SetEirData(const common::ByteBuffer& eir) { // TODO(armansito): Parse more fields. // TODO(armansito): SetName should be a no-op if a name was obtained via // the name discovery procedure. - changed = dev_->SetNameInternal(data.ToString()); + changed = peer_->SetNameInternal(data.ToString()); } } return changed; } -void RemoteDevice::BrEdrData::SetBondData(const sm::LTK& link_key) { - ZX_DEBUG_ASSERT(dev_->connectable()); +void Peer::BrEdrData::SetBondData(const sm::LTK& link_key) { + ZX_DEBUG_ASSERT(peer_->connectable()); - // Make sure the device is non-temporary. - dev_->TryMakeNonTemporary(); + // Make sure the peer is non-temporary. + peer_->TryMakeNonTemporary(); // Storing the key establishes the bond. link_key_ = link_key; - dev_->NotifyListeners(); + peer_->NotifyListeners(); } -void RemoteDevice::BrEdrData::ClearBondData() { +void Peer::BrEdrData::ClearBondData() { ZX_ASSERT(link_key_); link_key_ = std::nullopt; } -RemoteDevice::RemoteDevice(DeviceCallback notify_listeners_callback, - DeviceCallback update_expiry_callback, - DeviceCallback dual_mode_callback, - DeviceId identifier, const DeviceAddress& address, - bool connectable) +Peer::Peer(DeviceCallback notify_listeners_callback, + DeviceCallback update_expiry_callback, + DeviceCallback dual_mode_callback, DeviceId identifier, + const DeviceAddress& address, bool connectable) : notify_listeners_callback_(std::move(notify_listeners_callback)), update_expiry_callback_(std::move(update_expiry_callback)), dual_mode_callback_(std::move(dual_mode_callback)), @@ -326,7 +322,7 @@ RemoteDevice::RemoteDevice(DeviceCallback notify_listeners_callback, } } -RemoteDevice::LowEnergyData& RemoteDevice::MutLe() { +Peer::LowEnergyData& Peer::MutLe() { if (le_data_) { return *le_data_; } @@ -340,7 +336,7 @@ RemoteDevice::LowEnergyData& RemoteDevice::MutLe() { return *le_data_; } -RemoteDevice::BrEdrData& RemoteDevice::MutBrEdr() { +Peer::BrEdrData& Peer::MutBrEdr() { if (bredr_data_) { return *bredr_data_; } @@ -354,12 +350,12 @@ RemoteDevice::BrEdrData& RemoteDevice::MutBrEdr() { return *bredr_data_; } -std::string RemoteDevice::ToString() const { - return fxl::StringPrintf("{remote-device id: %s, address: %s}", - bt_str(identifier_), bt_str(address_)); +std::string Peer::ToString() const { + return fxl::StringPrintf("{peer id: %s, address: %s}", bt_str(identifier_), + bt_str(address_)); } -void RemoteDevice::SetName(const std::string& name) { +void Peer::SetName(const std::string& name) { if (SetNameInternal(name)) { UpdateExpiry(); NotifyListeners(); @@ -368,7 +364,7 @@ void RemoteDevice::SetName(const std::string& name) { // Private methods below: -bool RemoteDevice::SetRssiInternal(int8_t rssi) { +bool Peer::SetRssiInternal(int8_t rssi) { if (rssi != hci::kRSSIInvalid && rssi_ != rssi) { rssi_ = rssi; return true; @@ -376,7 +372,7 @@ bool RemoteDevice::SetRssiInternal(int8_t rssi) { return false; } -bool RemoteDevice::SetNameInternal(const std::string& name) { +bool Peer::SetNameInternal(const std::string& name) { if (!name_ || *name_ != name) { name_ = name; return true; @@ -384,7 +380,7 @@ bool RemoteDevice::SetNameInternal(const std::string& name) { return false; } -bool RemoteDevice::TryMakeNonTemporary() { +bool Peer::TryMakeNonTemporary() { // TODO(armansito): Since we don't currently support address resolution, // random addresses should never be persisted. if (!connectable()) { @@ -403,17 +399,17 @@ bool RemoteDevice::TryMakeNonTemporary() { return true; } -void RemoteDevice::UpdateExpiry() { +void Peer::UpdateExpiry() { ZX_DEBUG_ASSERT(update_expiry_callback_); update_expiry_callback_(*this); } -void RemoteDevice::NotifyListeners() { +void Peer::NotifyListeners() { ZX_DEBUG_ASSERT(notify_listeners_callback_); notify_listeners_callback_(*this); } -void RemoteDevice::MakeDualMode() { +void Peer::MakeDualMode() { technology_ = TechnologyType::kDualMode; ZX_DEBUG_ASSERT(dual_mode_callback_); dual_mode_callback_(*this); diff --git a/src/connectivity/bluetooth/core/bt-host/gap/remote_device.h b/src/connectivity/bluetooth/core/bt-host/gap/peer.h similarity index 82% rename from src/connectivity/bluetooth/core/bt-host/gap/remote_device.h rename to src/connectivity/bluetooth/core/bt-host/gap/peer.h index 5c5111bafdab889676ec76c755407c30ac652e2c..6fab1be6e904cf22dd0f777a4d3ae7a35fdf6057 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/remote_device.h +++ b/src/connectivity/bluetooth/core/bt-host/gap/peer.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_GAP_REMOTE_DEVICE_H_ -#define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_GAP_REMOTE_DEVICE_H_ +#ifndef SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_GAP_PEER_H_ +#define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_GAP_PEER_H_ #include <fbl/macros.h> @@ -21,23 +21,23 @@ namespace bt { namespace gap { -class RemoteDeviceCache; +class PeerCache; // Represents a remote Bluetooth device that is known to the current system due // to discovery and/or connection and bonding procedures. These devices can be // LE-only, Classic-only, or dual-mode. // // Instances should not be created directly and must be obtained via a -// RemoteDeviceCache. -class RemoteDevice final { +// PeerCache. +class Peer final { public: - // Device connection state. + // Connection state. enum class ConnectionState { // No link exists between the local adapter and this device. kNotConnected, - // The device is currently establishing a link or performing service - // discovery or encryption setup. In this state, a link may have been + // Currently establishing a link, performing service discovery, or + // setting up encryption. In this state, a link may have been // established but it is not ready to use yet. kInitializing, @@ -45,10 +45,10 @@ class RemoteDevice final { kConnected }; - // Contains RemoteDevice data that apply only to the LE transport. + // Contains Peer data that apply only to the LE transport. class LowEnergyData final { public: - explicit LowEnergyData(RemoteDevice* owner); + explicit LowEnergyData(Peer* owner); // Current connection state. ConnectionState connection_state() const { return conn_state_; } @@ -63,27 +63,27 @@ class RemoteDevice final { return adv_data_buffer_.view(0, adv_data_len_); } - // Most recently used LE connection parameters. Has no value if this device + // Most recently used LE connection parameters. Has no value if the peer // has never been connected. const std::optional<hci::LEConnectionParameters>& connection_parameters() const { return conn_params_; } - // Preferred LE connection parameters as reported by this device. + // Preferred LE connection parameters as reported by the peer. const std::optional<hci::LEPreferredConnectionParameters>& preferred_connection_parameters() const { return preferred_conn_params_; } - // This device's LE bond data, if bonded. + // This peer's LE bond data, if bonded. const std::optional<sm::PairingData>& bond_data() const { return bond_data_; } // Setters: - // Updates the LE advertising and scan response data for this device. + // Updates the LE advertising and scan response data. // |rssi| corresponds to the most recent advertisement RSSI. // |advertising_data| should include any scan response data if obtained // during an active scan. @@ -92,26 +92,26 @@ class RemoteDevice final { // Updates the connection state and notifies listeners if necessary. void SetConnectionState(ConnectionState state); - // Modify the current or preferred connection parameters for this device. + // Modify the current or preferred connection parameters. // The device must be connectable. void SetConnectionParameters(const hci::LEConnectionParameters& value); void SetPreferredConnectionParameters( const hci::LEPreferredConnectionParameters& value); - // Stores LE bonding data and makes this device "bonded." Marks the device - // as non-temporary if necessary. + // Stores LE bonding data and makes this "bonded." + // Marks as non-temporary if necessary. void SetBondData(const sm::PairingData& bond_data); - // Removes any stored keys. Does not make the device temporary, even if it + // Removes any stored keys. Does not make the peer temporary, even if it // is disconnected. Does not notify listeners. void ClearBondData(); // TODO(armansito): Store most recently seen random address and identity - // address separately, once RemoteDeviceCache can index devices by multiple + // address separately, once PeerCache can index peers by multiple // addresses. private: - RemoteDevice* dev_; // weak + Peer* peer_; // weak ConnectionState conn_state_; size_t adv_data_len_; @@ -125,10 +125,10 @@ class RemoteDevice final { // TODO(armansito): Store GATT service UUIDs. }; - // Contains RemoteDevice data that apply only to the BR/EDR transport. + // Contains Peer data that apply only to the BR/EDR transport. class BrEdrData final { public: - explicit BrEdrData(RemoteDevice* owner); + explicit BrEdrData(Peer* owner); // Current connection state. ConnectionState connection_state() const { return conn_state_; } @@ -137,21 +137,21 @@ class RemoteDevice final { } bool bonded() const { return link_key_.has_value(); } - // Returns the device's BD_ADDR. + // Returns the peer's BD_ADDR. const common::DeviceAddress& address() const { return address_; } - // Returns the device class of this device, if it is known. + // Returns the device class reported by the peer, if it is known. const std::optional<common::DeviceClass>& device_class() const { return device_class_; } - // Returns the page scan repetition mode of this device, if known. + // Returns the page scan repetition mode of the peer, if known. const std::optional<hci::PageScanRepetitionMode>& page_scan_repetition_mode() const { return page_scan_rep_mode_; } - // Returns the clock offset reported by the device, if known and valid. The + // Returns the clock offset reported by the peer, if known and valid. The // clock offset will have the highest-order bit set and the rest represent // bits 16-2 of CLKNslave-CLK (see hci::kClockOffsetFlagBit in // hci/hci_constants.h). @@ -166,7 +166,7 @@ class RemoteDevice final { // Setters: - // Updates the inquiry data for this device and notifies listeners. These + // Updates the inquiry data and notifies listeners. These // methods expect HCI inquiry result structures as they are obtained from // the Bluetooth controller. Each field should be encoded in little-endian // byte order. @@ -178,7 +178,7 @@ class RemoteDevice final { void SetConnectionState(ConnectionState state); // Stores a link key resulting from Secure Simple Pairing and makes this - // device "bonded." Marks the device as non-temporary if necessary. All + // peer "bonded." Marks the peer as non-temporary if necessary. All // BR/EDR link keys are "long term" (reusable across sessions). void SetBondData(const sm::LTK& link_key); @@ -186,7 +186,7 @@ class RemoteDevice final { // it is disconnected. Does not notify listeners. void ClearBondData(); - // TODO(armansito): Store BD_ADDR here, once RemoteDeviceCache can index + // TODO(armansito): Store BD_ADDR here, once PeerCache can index // devices by multiple addresses. private: @@ -201,7 +201,7 @@ class RemoteDevice final { // Updates the EIR data field and returns true if any properties changed. bool SetEirData(const common::ByteBuffer& data); - RemoteDevice* dev_; // weak + Peer* peer_; // weak ConnectionState conn_state_; common::DeviceAddress address_; std::optional<common::DeviceClass> device_class_; @@ -241,7 +241,7 @@ class RemoteDevice final { // // * For BR/EDR/LE devices this is the BD_ADDR and the LE identity address. // If a BR/EDR/LE device uses an identity address that is different from - // its BD_ADDR, then there will be two separate RemoteDevice entries for + // its BD_ADDR, then there will be two separate Peer entries for // it. const common::DeviceAddress& address() const { return address_; } bool identity_known() const { return identity_known_; } @@ -262,7 +262,7 @@ class RemoteDevice final { return (le() && le()->bonded()) || (bredr() && bredr()->bonded()); } - // Returns the most recently observed RSSI for this remote device. Returns + // Returns the most recently observed RSSI for this peer. Returns // hci::kRSSIInvalid if the value is unknown. int8_t rssi() const { return rssi_; } @@ -274,7 +274,7 @@ class RemoteDevice final { // Returns the set of features of this device. const hci::LMPFeatureSet& features() const { return lmp_features_; } - // A temporary device gets removed from the RemoteDeviceCache after a period + // A temporary device gets removed from the PeerCache after a period // of inactivity (see the |update_expiry_callback| argument to the // constructor). The following rules determine the temporary state of a // device: @@ -307,7 +307,7 @@ class RemoteDevice final { // Returns a string representation of this device. std::string ToString() const; - // The following methods mutate RemoteDevice properties: + // The following methods mutate Peer properties: // Updates the name of this device. This will override the existing name (if // present) and notify listeners of the change. @@ -331,20 +331,20 @@ class RemoteDevice final { } private: - friend class RemoteDeviceCache; - using DeviceCallback = fit::function<void(const RemoteDevice&)>; + friend class PeerCache; + using DeviceCallback = fit::function<void(const Peer&)>; // Caller must ensure that callbacks are non-empty. - // Note that the ctor is only intended for use by RemoteDeviceCache. - // Expanding access would a) violate the constraint that all RemoteDevices - // are created through a RemoteDeviceCache, and b) introduce lifetime issues + // Note that the ctor is only intended for use by PeerCache. + // Expanding access would a) violate the constraint that all Peers + // are created through a PeerCache, and b) introduce lifetime issues // (do the callbacks outlive |this|?). - RemoteDevice(DeviceCallback notify_listeners_callback, - DeviceCallback update_expiry_callback, - DeviceCallback dual_mode_callback, DeviceId identifier, - const common::DeviceAddress& address, bool connectable); + Peer(DeviceCallback notify_listeners_callback, + DeviceCallback update_expiry_callback, DeviceCallback dual_mode_callback, + DeviceId identifier, const common::DeviceAddress& address, + bool connectable); - // Marks this device's identity as known. Called by RemoteDeviceCache when + // Marks this device's identity as known. Called by PeerCache when // initializing a bonded device and by LowEnergyData when setting bond data // with an identity address. void set_identity_known(bool value) { identity_known_ = value; } @@ -370,7 +370,7 @@ class RemoteDevice final { // conditions are subtle and not fully supported yet. bool TryMakeNonTemporary(); - // Tells the owning RemoteDeviceCache to update the expiry state of this + // Tells the owning PeerCache to update the expiry state of this // device. void UpdateExpiry(); @@ -408,10 +408,10 @@ class RemoteDevice final { // device is known to support BR/EDR. std::optional<BrEdrData> bredr_data_; - DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(RemoteDevice); + DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(Peer); }; } // namespace gap } // namespace bt -#endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_GAP_REMOTE_DEVICE_H_ +#endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_GAP_PEER_H_ diff --git a/src/connectivity/bluetooth/core/bt-host/gap/remote_device_cache.cc b/src/connectivity/bluetooth/core/bt-host/gap/peer_cache.cc similarity index 50% rename from src/connectivity/bluetooth/core/bt-host/gap/remote_device_cache.cc rename to src/connectivity/bluetooth/core/bt-host/gap/peer_cache.cc index 8a297b3ea9b0d5a2583d4ae97aa89d77ab27bd04..9b1db20f02ddc289ebae042a3627ea506e7975b1 100644 --- a/src/connectivity/bluetooth/core/bt-host/gap/remote_device_cache.cc +++ b/src/connectivity/bluetooth/core/bt-host/gap/peer_cache.cc @@ -2,16 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "remote_device_cache.h" +#include "peer_cache.h" #include <fbl/function.h> #include <zircon/assert.h> +#include "lib/async/default.h" #include "src/connectivity/bluetooth/core/bt-host/common/random.h" -#include "src/connectivity/bluetooth/core/bt-host/gap/remote_device.h" +#include "src/connectivity/bluetooth/core/bt-host/gap/peer.h" #include "src/connectivity/bluetooth/core/bt-host/hci/connection.h" #include "src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.h" -#include "lib/async/default.h" namespace bt { namespace gap { @@ -33,29 +33,28 @@ DeviceAddress GetAliasAddress(const DeviceAddress& address) { } // namespace -RemoteDevice* RemoteDeviceCache::NewDevice(const DeviceAddress& address, - bool connectable) { +Peer* PeerCache::NewPeer(const DeviceAddress& address, bool connectable) { ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); - auto* const device = - InsertDeviceRecord(common::RandomDeviceId(), address, connectable); - if (device) { - UpdateExpiry(*device); - NotifyDeviceUpdated(*device); + auto* const peer = + InsertPeerRecord(common::RandomDeviceId(), address, connectable); + if (peer) { + UpdateExpiry(*peer); + NotifyPeerUpdated(*peer); } - return device; + return peer; } -void RemoteDeviceCache::ForEach(DeviceCallback f) { +void PeerCache::ForEach(PeerCallback f) { ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); ZX_DEBUG_ASSERT(f); - for (const auto& iter : devices_) { - f(*iter.second.device()); + for (const auto& iter : peers_) { + f(*iter.second.peer()); } } -bool RemoteDeviceCache::AddBondedDevice( - DeviceId identifier, const DeviceAddress& address, - const sm::PairingData& bond_data, const std::optional<sm::LTK>& link_key) { +bool PeerCache::AddBondedPeer(DeviceId identifier, const DeviceAddress& address, + const sm::PairingData& bond_data, + const std::optional<sm::LTK>& link_key) { ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); ZX_DEBUG_ASSERT(!bond_data.identity_address || address.value() == bond_data.identity_address->value()); @@ -77,50 +76,50 @@ bool RemoteDeviceCache::AddBondedDevice( return false; } - auto* device = InsertDeviceRecord(identifier, address, true); - if (!device) { + auto* peer = InsertPeerRecord(identifier, address, true); + if (!peer) { return false; } - // A bonded device must have its identity known. - device->set_identity_known(true); + // A bonded peer must have its identity known. + peer->set_identity_known(true); if (bond_le) { - device->MutLe().SetBondData(bond_data); - ZX_DEBUG_ASSERT(device->le()->bonded()); + peer->MutLe().SetBondData(bond_data); + ZX_DEBUG_ASSERT(peer->le()->bonded()); - // Add the device to the resolving list if it has an IRK. + // Add the peer to the resolving list if it has an IRK. if (bond_data.irk) { - le_resolving_list_.Add(device->address(), bond_data.irk->value()); + le_resolving_list_.Add(peer->address(), bond_data.irk->value()); } } if (bond_bredr) { - device->MutBrEdr().SetBondData(*link_key); - ZX_DEBUG_ASSERT(device->bredr()->bonded()); + peer->MutBrEdr().SetBondData(*link_key); + ZX_DEBUG_ASSERT(peer->bredr()->bonded()); } - if (device->technology() == TechnologyType::kDualMode) { + if (peer->technology() == TechnologyType::kDualMode) { address_map_[GetAliasAddress(address)] = identifier; } - ZX_DEBUG_ASSERT(!device->temporary()); - ZX_DEBUG_ASSERT(device->bonded()); - bt_log(SPEW, "gap", "restored bonded device: %s, id: %s", bt_str(address), + ZX_DEBUG_ASSERT(!peer->temporary()); + ZX_DEBUG_ASSERT(peer->bonded()); + bt_log(SPEW, "gap", "restored bonded peer: %s, id: %s", bt_str(address), bt_str(identifier)); - // Don't call UpdateExpiry(). Since a bonded device starts out as + // Don't call UpdateExpiry(). Since a bonded peer starts out as // non-temporary it is not necessary to ever set up the expiration callback. - NotifyDeviceUpdated(*device); + NotifyPeerUpdated(*peer); return true; } -bool RemoteDeviceCache::StoreLowEnergyBond(DeviceId identifier, - const sm::PairingData& bond_data) { +bool PeerCache::StoreLowEnergyBond(DeviceId identifier, + const sm::PairingData& bond_data) { ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); - auto* device = FindDeviceById(identifier); - if (!device) { - bt_log(TRACE, "gap-le", "failed to store bond for unknown device: %s", + auto* peer = FindById(identifier); + if (!peer) { + bt_log(TRACE, "gap-le", "failed to store bond for unknown peer: %s", bt_str(identifier)); return false; } @@ -136,64 +135,64 @@ bool RemoteDeviceCache::StoreLowEnergyBond(DeviceId identifier, if (bond_data.identity_address) { auto existing_id = FindIdByAddress(*bond_data.identity_address); if (!existing_id) { - // Map the new address to |device|. We leave old addresses that map to - // this device in the cache in case there are any pending controller + // Map the new address to |peer|. We leave old addresses that map to + // this peer in the cache in case there are any pending controller // procedures that expect them. // TODO(armansito): Maybe expire the old address after a while? address_map_[*bond_data.identity_address] = identifier; } else if (*existing_id != identifier) { bt_log(TRACE, "gap-le", - "identity address %s for device %s belongs to another device %s!", + "identity address %s for peer %s belongs to another peer %s!", bt_str(*bond_data.identity_address), bt_str(identifier), bt_str(*existing_id)); return false; } // We have either created a new mapping or the identity address already - // maps to this device. + // maps to this peer. } // TODO(BT-619): Check that we're not downgrading the security level before // overwriting the bond. - device->MutLe().SetBondData(bond_data); - ZX_DEBUG_ASSERT(!device->temporary()); - ZX_DEBUG_ASSERT(device->le()->bonded()); + peer->MutLe().SetBondData(bond_data); + ZX_DEBUG_ASSERT(!peer->temporary()); + ZX_DEBUG_ASSERT(peer->le()->bonded()); - // Add the device to the resolving list if it has an IRK. - if (device->identity_known() && bond_data.irk) { - le_resolving_list_.Add(device->address(), bond_data.irk->value()); + // Add the peer to the resolving list if it has an IRK. + if (peer->identity_known() && bond_data.irk) { + le_resolving_list_.Add(peer->address(), bond_data.irk->value()); } - // Report the bond for persisting only if the identity of the device is known. - if (device->identity_known()) { - NotifyDeviceBonded(*device); + // Report the bond for persisting only if the identity of the peer is known. + if (peer->identity_known()) { + NotifyPeerBonded(*peer); } return true; } -bool RemoteDeviceCache::StoreBrEdrBond(const common::DeviceAddress& address, - const sm::LTK& link_key) { +bool PeerCache::StoreBrEdrBond(const common::DeviceAddress& address, + const sm::LTK& link_key) { ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); ZX_DEBUG_ASSERT(address.type() == common::DeviceAddress::Type::kBREDR); - auto* device = FindDeviceByAddress(address); - if (!device) { - bt_log(TRACE, "gap-bredr", "failed to store bond for unknown device: %s", + auto* peer = FindByAddress(address); + if (!peer) { + bt_log(TRACE, "gap-bredr", "failed to store bond for unknown peer: %s", address.ToString().c_str()); return false; } // TODO(BT-619): Check that we're not downgrading the security level before // overwriting the bond. - device->MutBrEdr().SetBondData(link_key); - ZX_DEBUG_ASSERT(!device->temporary()); - ZX_DEBUG_ASSERT(device->bredr()->bonded()); + peer->MutBrEdr().SetBondData(link_key); + ZX_DEBUG_ASSERT(!peer->temporary()); + ZX_DEBUG_ASSERT(peer->bredr()->bonded()); - NotifyDeviceBonded(*device); + NotifyPeerBonded(*peer); return true; } -bool RemoteDeviceCache::ForgetPeer(DeviceId peer_id) { +bool PeerCache::ForgetPeer(DeviceId peer_id) { ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); - auto* const peer = FindDeviceById(peer_id); + auto* const peer = FindById(peer_id); if (!peer) { bt_log(TRACE, "gap", "failed to unbond unknown peer %s", bt_str(peer_id)); return false; @@ -225,20 +224,19 @@ bool RemoteDeviceCache::ForgetPeer(DeviceId peer_id) { } if (bond_removed) { - NotifyDeviceUpdated(*peer); + NotifyPeerUpdated(*peer); } return bond_removed; } -RemoteDevice* RemoteDeviceCache::FindDeviceById(DeviceId identifier) const { +Peer* PeerCache::FindById(DeviceId peer_id) const { ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); - auto iter = devices_.find(identifier); - return iter != devices_.end() ? iter->second.device() : nullptr; + auto iter = peers_.find(peer_id); + return iter != peers_.end() ? iter->second.peer() : nullptr; } -RemoteDevice* RemoteDeviceCache::FindDeviceByAddress( - const DeviceAddress& in_address) const { +Peer* PeerCache::FindByAddress(const DeviceAddress& in_address) const { ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); std::optional<DeviceAddress> address; @@ -257,104 +255,104 @@ RemoteDevice* RemoteDeviceCache::FindDeviceByAddress( return nullptr; } - auto* dev = FindDeviceById(*identifier); - ZX_DEBUG_ASSERT(dev); - return dev; + auto* p = FindById(*identifier); + ZX_DEBUG_ASSERT(p); + return p; } // Private methods below. -RemoteDevice* RemoteDeviceCache::InsertDeviceRecord( - DeviceId identifier, const common::DeviceAddress& address, - bool connectable) { +Peer* PeerCache::InsertPeerRecord(DeviceId identifier, + const common::DeviceAddress& address, + bool connectable) { if (FindIdByAddress(address)) { - bt_log(WARN, "gap", "tried to insert device with existing address: %s", + bt_log(WARN, "gap", "tried to insert peer with existing address: %s", address.ToString().c_str()); return nullptr; } - std::unique_ptr<RemoteDevice> device(new RemoteDevice( - fit::bind_member(this, &RemoteDeviceCache::NotifyDeviceUpdated), - fit::bind_member(this, &RemoteDeviceCache::UpdateExpiry), - fit::bind_member(this, &RemoteDeviceCache::MakeDualMode), identifier, - address, connectable)); - // Note: we must construct the RemoteDeviceRecord in-place, because it doesn't + std::unique_ptr<Peer> peer( + new Peer(fit::bind_member(this, &PeerCache::NotifyPeerUpdated), + fit::bind_member(this, &PeerCache::UpdateExpiry), + fit::bind_member(this, &PeerCache::MakeDualMode), identifier, + address, connectable)); + // Note: we must construct the PeerRecord in-place, because it doesn't // support copy or move. auto [iter, inserted] = - devices_.try_emplace(device->identifier(), std::move(device), - [this, d = device.get()] { RemoveDevice(d); }); + peers_.try_emplace(peer->identifier(), std::move(peer), + [this, p = peer.get()] { RemovePeer(p); }); if (!inserted) { - bt_log(WARN, "gap", "tried to insert device with existing ID: %s", + bt_log(WARN, "gap", "tried to insert peer with existing ID: %s", bt_str(identifier)); return nullptr; } address_map_[address] = identifier; - return iter->second.device(); + return iter->second.peer(); } -void RemoteDeviceCache::NotifyDeviceBonded(const RemoteDevice& device) { - ZX_DEBUG_ASSERT(devices_.find(device.identifier()) != devices_.end()); - ZX_DEBUG_ASSERT(devices_.at(device.identifier()).device() == &device); - ZX_DEBUG_ASSERT_MSG(device.identity_known(), - "devices not allowed to bond with unknown identity!"); +void PeerCache::NotifyPeerBonded(const Peer& peer) { + ZX_DEBUG_ASSERT(peers_.find(peer.identifier()) != peers_.end()); + ZX_DEBUG_ASSERT(peers_.at(peer.identifier()).peer() == &peer); + ZX_DEBUG_ASSERT_MSG(peer.identity_known(), + "peers not allowed to bond with unknown identity!"); - bt_log(INFO, "gap", "peer bonded %s", device.ToString().c_str()); - if (device_bonded_callback_) { - device_bonded_callback_(device); + bt_log(INFO, "gap", "peer bonded %s", peer.ToString().c_str()); + if (peer_bonded_callback_) { + peer_bonded_callback_(peer); } } -void RemoteDeviceCache::NotifyDeviceUpdated(const RemoteDevice& device) { - ZX_DEBUG_ASSERT(devices_.find(device.identifier()) != devices_.end()); - ZX_DEBUG_ASSERT(devices_.at(device.identifier()).device() == &device); - if (device_updated_callback_) - device_updated_callback_(device); +void PeerCache::NotifyPeerUpdated(const Peer& peer) { + ZX_DEBUG_ASSERT(peers_.find(peer.identifier()) != peers_.end()); + ZX_DEBUG_ASSERT(peers_.at(peer.identifier()).peer() == &peer); + if (peer_updated_callback_) + peer_updated_callback_(peer); } -void RemoteDeviceCache::UpdateExpiry(const RemoteDevice& device) { - auto device_record_iter = devices_.find(device.identifier()); - ZX_DEBUG_ASSERT(device_record_iter != devices_.end()); +void PeerCache::UpdateExpiry(const Peer& peer) { + auto peer_record_iter = peers_.find(peer.identifier()); + ZX_DEBUG_ASSERT(peer_record_iter != peers_.end()); - auto& device_record = device_record_iter->second; - ZX_DEBUG_ASSERT(device_record.device() == &device); + auto& peer_record = peer_record_iter->second; + ZX_DEBUG_ASSERT(peer_record.peer() == &peer); - const auto cancel_res = device_record.removal_task()->Cancel(); + const auto cancel_res = peer_record.removal_task()->Cancel(); ZX_DEBUG_ASSERT(cancel_res == ZX_OK || cancel_res == ZX_ERR_NOT_FOUND); - // Previous expiry task has been canceled. Re-schedule only if the device is + // Previous expiry task has been canceled. Re-schedule only if the peer is // temporary. - if (device.temporary()) { - const auto schedule_res = device_record.removal_task()->PostDelayed( + if (peer.temporary()) { + const auto schedule_res = peer_record.removal_task()->PostDelayed( async_get_default_dispatcher(), kCacheTimeout); ZX_DEBUG_ASSERT(schedule_res == ZX_OK || schedule_res == ZX_ERR_BAD_STATE); } } -void RemoteDeviceCache::MakeDualMode(const RemoteDevice& device) { - ZX_DEBUG_ASSERT(address_map_.at(device.address()) == device.identifier()); - const auto address_alias = GetAliasAddress(device.address()); +void PeerCache::MakeDualMode(const Peer& peer) { + ZX_DEBUG_ASSERT(address_map_.at(peer.address()) == peer.identifier()); + const auto address_alias = GetAliasAddress(peer.address()); auto [iter, inserted] = - address_map_.try_emplace(address_alias, device.identifier()); - ZX_DEBUG_ASSERT_MSG(inserted || iter->second == device.identifier(), + address_map_.try_emplace(address_alias, peer.identifier()); + ZX_DEBUG_ASSERT_MSG(inserted || iter->second == peer.identifier(), "%s can't become dual-mode because %s maps to %s", - bt_str(device.identifier()), bt_str(address_alias), + bt_str(peer.identifier()), bt_str(address_alias), bt_str(iter->second)); - // The device became dual mode in lieu of adding a new device but is as + // The peer became dual mode in lieu of adding a new peer but is as // significant, so notify listeners of the change. - NotifyDeviceUpdated(device); + NotifyPeerUpdated(peer); } -void RemoteDeviceCache::RemoveDevice(RemoteDevice* device) { - ZX_DEBUG_ASSERT(device); +void PeerCache::RemovePeer(Peer* peer) { + ZX_DEBUG_ASSERT(peer); - auto device_record_it = devices_.find(device->identifier()); - ZX_DEBUG_ASSERT(device_record_it != devices_.end()); - ZX_DEBUG_ASSERT(device_record_it->second.device() == device); + auto peer_record_it = peers_.find(peer->identifier()); + ZX_DEBUG_ASSERT(peer_record_it != peers_.end()); + ZX_DEBUG_ASSERT(peer_record_it->second.peer() == peer); - DeviceId id = device->identifier(); - bt_log(SPEW, "gap", "removing device %s", bt_str(id)); + DeviceId id = peer->identifier(); + bt_log(SPEW, "gap", "removing peer %s", bt_str(id)); for (auto iter = address_map_.begin(); iter != address_map_.end();) { if (iter->second == id) { iter = address_map_.erase(iter); @@ -362,18 +360,18 @@ void RemoteDeviceCache::RemoveDevice(RemoteDevice* device) { iter++; } } - devices_.erase(device_record_it); // Destroys |device|. - if (device_removed_callback_) { - device_removed_callback_(id); + peers_.erase(peer_record_it); // Destroys |peer|. + if (peer_removed_callback_) { + peer_removed_callback_(id); } } -std::optional<DeviceId> RemoteDeviceCache::FindIdByAddress( +std::optional<DeviceId> PeerCache::FindIdByAddress( const common::DeviceAddress& address) const { auto iter = address_map_.find(address); if (iter == address_map_.end()) { // Search again using the other technology's address. This is necessary when - // a dual-mode device is known by only one technology and is then discovered + // a dual-mode peer is known by only one technology and is then discovered // or connected on its other technology. iter = address_map_.find(GetAliasAddress(address)); } diff --git a/src/connectivity/bluetooth/core/bt-host/gap/peer_cache.h b/src/connectivity/bluetooth/core/bt-host/gap/peer_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..65911f69196c99c58b2217238d3f1f80779934dc --- /dev/null +++ b/src/connectivity/bluetooth/core/bt-host/gap/peer_cache.h @@ -0,0 +1,230 @@ +// Copyright 2017 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_GAP_PEER_CACHE_H_ +#define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_GAP_PEER_CACHE_H_ + +#include <fbl/function.h> +#include <fbl/macros.h> +#include <lib/async/cpp/task.h> + +#include <unordered_map> + +#include "src/connectivity/bluetooth/core/bt-host/common/device_address.h" +#include "src/connectivity/bluetooth/core/bt-host/gap/identity_resolving_list.h" +#include "src/connectivity/bluetooth/core/bt-host/gap/peer.h" +#include "src/connectivity/bluetooth/core/bt-host/hci/connection.h" +#include "src/connectivity/bluetooth/core/bt-host/sm/types.h" +#include "src/lib/fxl/synchronization/thread_checker.h" + +namespace bt { + +namespace common { +class ByteBuffer; +} // namespace common + +namespace hci { +struct LowEnergyScanResult; +} // namespace hci + +namespace gap { + +// A PeerCache provides access to remote Bluetooth devices that are +// known to the system. +class PeerCache final { + public: + using PeerCallback = fit::function<void(const Peer& peer)>; + using PeerIdCallback = fit::function<void(DeviceId identifier)>; + + PeerCache() = default; + + // Creates a new peer entry using the given parameters, and returns a + // (non-owning) pointer to that peer. The caller must not retain the pointer + // beyond the current dispatcher task, as the underlying Peer is owned + // by |this| PeerCache, and may be invalidated spontaneously. + // + // Returns nullptr if an entry matching |address| already exists in the cache, + // including as a public identity of a peer with a different technology. + Peer* NewPeer(const common::DeviceAddress& address, bool connectable); + + // Iterates over all current peers in the map, running |f| on each entry + // synchronously. This is intended for IPC methods that request a list of + // peers. + // + // Clients should use the FindBy*() methods below to interact with + // Peer objects. + void ForEach(PeerCallback f); + + // Creates a new non-temporary peer entry using the given |identifier| and + // identity |address|. This is intended to initialize this PeerCache + // with previously bonded peers while bootstrapping a bt-host peer. The + // "peer bonded" callback will not be invoked. + // + // This method is not intended for updating the bonding data of a peer that + // already exists the cache and returns false if a mapping for |identifier| or + // |address| is already present. Use Store*Bond() methods to update pairing + // information of an existing peer. + // + // If a peer already exists that has the same public identity address with a + // different technology, this method will return false. The existing peer + // should be instead updated with new bond information to create a dual-mode + // peer. + // + bool AddBondedPeer(DeviceId identifier, const common::DeviceAddress& address, + const sm::PairingData& bond_data, + const std::optional<sm::LTK>& link_key); + + // Update the peer with the given identifier with new LE bonding + // information. The peer will be considered "bonded" and the bonded callback + // will be notified. If the peer is already bonded then bonding data will be + // updated. + // + // If |bond_data| contains an |identity_address|, the peer cache will be + // updated with a new mapping from that address to this peer identifier. If + // the identity address already maps to an existing peer, this method will + // return false. TODO(armansito): Merge the peers instead of failing? What + // happens if we obtain a LE identity address from a dual-mode peer that + // matches the BD_ADDR previously obtained from it over BR/EDR? + bool StoreLowEnergyBond(DeviceId identifier, + const sm::PairingData& bond_data); + + // Update a peer identified by BD_ADDR |address| with a new BR/EDR link key. + // The peer will be considered "bonded" and the bonded callback notified. If + // the peer is already bonded then the link key will be updated. Returns + // false if the address does not match that of a known peer. + bool StoreBrEdrBond(const common::DeviceAddress& address, + const sm::LTK& link_key); + + // Resets a peer |peer_id| to an unbonded state by removing secrets for its + // transports. The peer will become temporary and may expire. This does not + // otherwise disconnect the peer or remove its ID or address from the cache. + // Returns true if bonds were deleted from a known peer. + // + // TODO(BT-824): Delete the peer immediately after disconnecting. Will return + // true if a known peer was deleted or marked for deletion. + bool ForgetPeer(DeviceId peer_id); + + // Returns the remote peer with identifier |peer_id|. Returns nullptr if + // |peer_id| is not recognized. + Peer* FindById(DeviceId peer_id) const; + + // Finds and returns a Peer with address |address| if it exists, + // returns nullptr otherwise. Tries to resolve |address| if it is resolvable. + // If |address| is of type kBREDR or kLEPublic, then this searches for peers + // that have either type of address. + Peer* FindByAddress(const common::DeviceAddress& address) const; + + // When set, |callback| will be invoked whenever a peer is added or updated. + void set_peer_updated_callback(PeerCallback callback) { + ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); + peer_updated_callback_ = std::move(callback); + } + + // When set, |callback| will be invoked whenever a peer is removed. + void set_peer_removed_callback(PeerIdCallback callback) { + ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); + peer_removed_callback_ = std::move(callback); + } + + // When this callback is set, |callback| will be invoked whenever the bonding + // data of a peer is updated and should be persisted. The caller must ensure + // that |callback| outlives |this|. + void set_peer_bonded_callback(PeerCallback callback) { + ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); + peer_bonded_callback_ = std::move(callback); + } + + // Returns the number of peers that are currently in the peer cache. + size_t count() const { return peers_.size(); } + + private: + class PeerRecord final { + public: + PeerRecord(std::unique_ptr<Peer> peer, fbl::Closure remove_peer_callback) + : peer_(std::move(peer)), + removal_task_(std::move(remove_peer_callback)) {} + + // The copy and move ctors cannot be implicitly defined, since + // async::TaskClosure does not support those operations. Nor is any + // meaningful explicit definition possible. + PeerRecord(const PeerRecord&) = delete; + PeerRecord(PeerRecord&&) = delete; + + Peer* peer() const { return peer_.get(); } + + // Returns a pointer to removal_task_, which can be used to (re-)schedule or + // cancel |remove_peer_callback|. + async::TaskClosure* removal_task() { return &removal_task_; } + + private: + std::unique_ptr<Peer> peer_; + async::TaskClosure removal_task_; + }; + + // Create and track a record of a remote peer with a given |identifier|, + // |address|, and connectability (|connectable|). Returns a pointer to the + // inserted peer or nullptr if |identifier| or |address| already exists in + // the cache. + Peer* InsertPeerRecord(DeviceId identifier, + const common::DeviceAddress& address, + bool connectable); + + // Notifies interested parties that |peer| has bonded + // |peer| must already exist in the cache. + void NotifyPeerBonded(const Peer& peer); + + // Notifies interested parties that |peer| has seen a significant change. + // |peer| must already exist in the cache. + void NotifyPeerUpdated(const Peer& peer); + + // Updates the expiration time for |peer|, if a temporary. Cancels expiry, + // if a non-temporary. Pre-conditions: + // - |peer| must already exist in the cache + // - can only be called from the thread that created |peer| + void UpdateExpiry(const Peer& peer); + + // Updates the cache when an existing peer is found to be dual-mode. Also + // notifies listeners of the "peer updated" callback. + // |peer| must already exist in the cache. + void MakeDualMode(const Peer& peer); + + // Removes |peer| from this cache, and notifies listeners of the removal. + void RemovePeer(Peer* peer); + + // Search for an unique peer ID by its peer address |address|, by both + // technologies if it is a public address. |address| should be already + // resolved, if it is resolvable. If found, returns a valid peer ID; + // otherwise returns std::nullopt. + std::optional<DeviceId> FindIdByAddress( + const common::DeviceAddress& address) const; + + // Mapping from unique peer IDs to PeerRecords. + // Owns the corresponding Peers. + std::unordered_map<DeviceId, PeerRecord> peers_; + + // Mapping from peer addresses to unique peer identifiers for all known + // peers. This is used to look-up and update existing cached data for a + // particular scan result so as to avoid creating duplicate entries for the + // same peer. + // + // Dual-mode peers shall have identity addresses of both technologies + // mapped to the same ID, if the addresses have the same value. + std::unordered_map<common::DeviceAddress, DeviceId> address_map_; + + // The LE identity resolving list used to resolve RPAs. + IdentityResolvingList le_resolving_list_; + + PeerCallback peer_updated_callback_; + PeerIdCallback peer_removed_callback_; + PeerCallback peer_bonded_callback_; + + fxl::ThreadChecker thread_checker_; + + DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(PeerCache); +}; + +} // namespace gap +} // namespace bt + +#endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_GAP_PEER_CACHE_H_ diff --git a/src/connectivity/bluetooth/core/bt-host/gap/peer_cache_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gap/peer_cache_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..b144e85dee517a741d612be48d1151ec734d3ce8 --- /dev/null +++ b/src/connectivity/bluetooth/core/bt-host/gap/peer_cache_unittest.cc @@ -0,0 +1,1434 @@ +// Copyright 2017 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "src/connectivity/bluetooth/core/bt-host/gap/peer_cache.h" + +#include "gtest/gtest.h" +#include "lib/gtest/test_loop_fixture.h" +#include "src/connectivity/bluetooth/core/bt-host/common/device_class.h" +#include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" +#include "src/connectivity/bluetooth/core/bt-host/common/uint128.h" +#include "src/connectivity/bluetooth/core/bt-host/gap/peer.h" +#include "src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.h" +#include "src/connectivity/bluetooth/core/bt-host/sm/types.h" +#include "src/connectivity/bluetooth/core/bt-host/sm/util.h" + +namespace bt { +namespace gap { +namespace { + +using common::CreateStaticByteBuffer; +using common::DeviceAddress; +using common::MutableBufferView; +using common::StaticByteBuffer; + +// All fields are initialized to zero as they are unused in these tests. +const hci::LEConnectionParameters kTestParams; + +// Arbitrary ID value used by the bonding tests below. The actual value of this +// constant does not effect the test logic. +constexpr DeviceId kId(100); +constexpr int8_t kTestRSSI = 10; + +const DeviceAddress kAddrBrEdr(DeviceAddress::Type::kBREDR, + "AA:BB:CC:DD:EE:FF"); +const DeviceAddress kAddrLePublic(DeviceAddress::Type::kLEPublic, + "01:02:03:04:05:06"); +// LE Public Device Address that has the same value as a BR/EDR BD_ADDR, e.g. on +// a dual-mode device. +const DeviceAddress kAddrLeAlias(DeviceAddress::Type::kLEPublic, + "AA:BB:CC:DD:EE:FF"); + +// TODO(armansito): Make these adhere to privacy specification. +const DeviceAddress kAddrLeRandom(DeviceAddress::Type::kLERandom, + "06:05:04:03:02:01"); +const DeviceAddress kAddrLeRandom2(DeviceAddress::Type::kLERandom, + "FF:EE:DD:CC:BB:AA"); +const DeviceAddress kAddrLeAnon(DeviceAddress::Type::kLEAnonymous, + "06:05:04:03:02:01"); + +const auto kAdvData = + CreateStaticByteBuffer(0x05, // Length + 0x09, // AD type: Complete Local Name + 'T', 'e', 's', 't'); +const auto kEirData = kAdvData; + +const bt::sm::LTK kLTK; +const bt::sm::Key kKey{}; + +const bt::sm::LTK kBrEdrKey; + +// Phone (Networking) +const common::DeviceClass kTestDeviceClass({0x06, 0x02, 0x02}); + +class GAP_PeerCacheTest : public ::gtest::TestLoopFixture { + public: + void SetUp() override { TestLoopFixture::SetUp(); } + + void TearDown() override { + RunLoopUntilIdle(); + TestLoopFixture::TearDown(); + } + + protected: + // Creates a new Peer, and caches a pointer to that peer. + __WARN_UNUSED_RESULT bool NewPeer(const DeviceAddress& addr, + bool connectable) { + auto* peer = cache_.NewPeer(addr, connectable); + if (!peer) { + return false; + } + peer_ = peer; + return true; + } + + PeerCache* cache() { return &cache_; } + // Returns the cached pointer to the peer created in the most recent call to + // NewPeer(). The caller must ensure that the peer has not expired out of + // the cache. (Tests of cache expiration should generally subclass the + // GAP_PeerCacheExpirationTest fixture.) + Peer* peer() { return peer_; } + + private: + PeerCache cache_; + Peer* peer_; +}; + +TEST_F(GAP_PeerCacheTest, LookUp) { + auto kAdvData0 = CreateStaticByteBuffer(0x05, 0x09, 'T', 'e', 's', 't'); + auto kAdvData1 = CreateStaticByteBuffer(0x0C, 0x09, 'T', 'e', 's', 't', ' ', + 'D', 'e', 'v', 'i', 'c', 'e'); + + // These should return false regardless of the input while the cache is empty. + EXPECT_FALSE(cache()->FindByAddress(kAddrLePublic)); + EXPECT_FALSE(cache()->FindById(kId)); + + auto peer = cache()->NewPeer(kAddrLePublic, true); + ASSERT_TRUE(peer); + ASSERT_TRUE(peer->le()); + EXPECT_EQ(TechnologyType::kLowEnergy, peer->technology()); + EXPECT_TRUE(peer->connectable()); + EXPECT_TRUE(peer->temporary()); + EXPECT_EQ(kAddrLePublic, peer->address()); + EXPECT_EQ(0u, peer->le()->advertising_data().size()); + EXPECT_EQ(hci::kRSSIInvalid, peer->rssi()); + + // A look up should return the same instance. + EXPECT_EQ(peer, cache()->FindById(peer->identifier())); + EXPECT_EQ(peer, cache()->FindByAddress(peer->address())); + + // Adding a peer with the same address should return nullptr. + EXPECT_FALSE(cache()->NewPeer(kAddrLePublic, true)); + + peer->MutLe().SetAdvertisingData(kTestRSSI, kAdvData1); + EXPECT_TRUE( + common::ContainersEqual(kAdvData1, peer->le()->advertising_data())); + EXPECT_EQ(kTestRSSI, peer->rssi()); + + peer->MutLe().SetAdvertisingData(kTestRSSI, kAdvData0); + EXPECT_TRUE( + common::ContainersEqual(kAdvData0, peer->le()->advertising_data())); + EXPECT_EQ(kTestRSSI, peer->rssi()); +} + +TEST_F(GAP_PeerCacheTest, LookUpBrEdrPeerByLePublicAlias) { + ASSERT_FALSE(cache()->FindByAddress(kAddrLeAlias)); + ASSERT_TRUE(NewPeer(kAddrBrEdr, true)); + auto* p = cache()->FindByAddress(kAddrBrEdr); + ASSERT_TRUE(p); + EXPECT_EQ(peer(), p); + + p = cache()->FindByAddress(kAddrLeAlias); + ASSERT_TRUE(p); + EXPECT_EQ(peer(), p); + EXPECT_EQ(DeviceAddress::Type::kBREDR, p->address().type()); +} + +TEST_F(GAP_PeerCacheTest, LookUpLePeerByBrEdrAlias) { + EXPECT_FALSE(cache()->FindByAddress(kAddrBrEdr)); + ASSERT_TRUE(NewPeer(kAddrLeAlias, true)); + auto* p = cache()->FindByAddress(kAddrLeAlias); + ASSERT_TRUE(p); + EXPECT_EQ(peer(), p); + + p = cache()->FindByAddress(kAddrBrEdr); + ASSERT_TRUE(p); + EXPECT_EQ(peer(), p); + EXPECT_EQ(DeviceAddress::Type::kLEPublic, p->address().type()); +} + +TEST_F(GAP_PeerCacheTest, NewPeerDoesNotCrashWhenNoCallbackIsRegistered) { + PeerCache().NewPeer(kAddrLePublic, true); +} + +TEST_F(GAP_PeerCacheTest, ForEachEmpty) { + bool found = false; + cache()->ForEach([&](const auto&) { found = true; }); + EXPECT_FALSE(found); +} + +TEST_F(GAP_PeerCacheTest, ForEach) { + int count = 0; + ASSERT_TRUE(NewPeer(kAddrLePublic, true)); + cache()->ForEach([&](const auto& p) { + count++; + EXPECT_EQ(peer()->identifier(), p.identifier()); + EXPECT_EQ(peer()->address(), p.address()); + }); + EXPECT_EQ(1, count); +} + +TEST_F(GAP_PeerCacheTest, NewPeerInvokesCallbackWhenPeerIsFirstRegistered) { + bool was_called = false; + cache()->set_peer_updated_callback( + [&was_called](const auto&) { was_called = true; }); + cache()->NewPeer(kAddrLePublic, true); + EXPECT_TRUE(was_called); +} + +TEST_F(GAP_PeerCacheTest, NewPeerDoesNotInvokeCallbackWhenPeerIsReRegistered) { + int call_count = 0; + cache()->set_peer_updated_callback( + [&call_count](const auto&) { ++call_count; }); + cache()->NewPeer(kAddrLePublic, true); + cache()->NewPeer(kAddrLePublic, true); + EXPECT_EQ(1, call_count); +} + +TEST_F(GAP_PeerCacheTest, NewPeerIdentityKnown) { + EXPECT_TRUE(cache()->NewPeer(kAddrBrEdr, true)->identity_known()); + EXPECT_TRUE(cache()->NewPeer(kAddrLePublic, true)->identity_known()); + EXPECT_FALSE(cache()->NewPeer(kAddrLeRandom, true)->identity_known()); + EXPECT_FALSE(cache()->NewPeer(kAddrLeAnon, false)->identity_known()); +} + +TEST_F(GAP_PeerCacheTest, NewPeerInitialTechnologyIsClassic) { + ASSERT_TRUE(NewPeer(kAddrBrEdr, true)); + + // A peer initialized with a BR/EDR address should start out as a + // classic-only. + ASSERT_TRUE(peer()); + EXPECT_TRUE(peer()->bredr()); + EXPECT_FALSE(peer()->le()); + EXPECT_TRUE(peer()->identity_known()); + EXPECT_EQ(TechnologyType::kClassic, peer()->technology()); +} + +TEST_F(GAP_PeerCacheTest, NewPeerInitialTechnologyLowEnergy) { + // LE address types should initialize the peer as LE-only. + auto* le_publ_peer = cache()->NewPeer(kAddrLePublic, true /*connectable*/); + auto* le_rand_peer = cache()->NewPeer(kAddrLeRandom, true /*connectable*/); + auto* le_anon_peer = cache()->NewPeer(kAddrLeAnon, false /*connectable*/); + ASSERT_TRUE(le_publ_peer); + ASSERT_TRUE(le_rand_peer); + ASSERT_TRUE(le_anon_peer); + EXPECT_TRUE(le_publ_peer->le()); + EXPECT_TRUE(le_rand_peer->le()); + EXPECT_TRUE(le_anon_peer->le()); + EXPECT_FALSE(le_publ_peer->bredr()); + EXPECT_FALSE(le_rand_peer->bredr()); + EXPECT_FALSE(le_anon_peer->bredr()); + EXPECT_EQ(TechnologyType::kLowEnergy, le_publ_peer->technology()); + EXPECT_EQ(TechnologyType::kLowEnergy, le_rand_peer->technology()); + EXPECT_EQ(TechnologyType::kLowEnergy, le_anon_peer->technology()); + EXPECT_TRUE(le_publ_peer->identity_known()); + EXPECT_FALSE(le_rand_peer->identity_known()); + EXPECT_FALSE(le_anon_peer->identity_known()); +} + +TEST_F(GAP_PeerCacheTest, DisallowNewLowEnergyPeerIfBrEdrPeerExists) { + ASSERT_TRUE(NewPeer(kAddrBrEdr, true)); + + // Try to add new LE peer with a public identity address containing the same + // value as the existing BR/EDR peer's BD_ADDR. + auto* le_alias_peer = cache()->NewPeer(kAddrLeAlias, true); + EXPECT_FALSE(le_alias_peer); +} + +TEST_F(GAP_PeerCacheTest, DisallowNewBrEdrPeerIfLowEnergyPeerExists) { + ASSERT_TRUE(NewPeer(kAddrLeAlias, true)); + + // Try to add new BR/EDR peer with BD_ADDR containing the same value as the + // existing LE peer's public identity address. + auto* bredr_alias_peer = cache()->NewPeer(kAddrBrEdr, true); + ASSERT_FALSE(bredr_alias_peer); +} + +TEST_F(GAP_PeerCacheTest, BrEdrPeerBecomesDualModeWithAdvertisingData) { + ASSERT_TRUE(NewPeer(kAddrBrEdr, true)); + ASSERT_TRUE(peer()->bredr()); + ASSERT_FALSE(peer()->le()); + + peer()->MutLe().SetAdvertisingData(kTestRSSI, kAdvData); + EXPECT_TRUE(peer()->le()); + EXPECT_EQ(TechnologyType::kDualMode, peer()->technology()); + + // Searching by LE address should turn up this peer, which should retain its + // original address type. + auto* const le_peer = cache()->FindByAddress(kAddrLeAlias); + ASSERT_EQ(peer(), le_peer); + EXPECT_EQ(DeviceAddress::Type::kBREDR, peer()->address().type()); +} + +TEST_F(GAP_PeerCacheTest, BrEdrPeerBecomesDualModeWhenConnectedOverLowEnergy) { + ASSERT_TRUE(NewPeer(kAddrBrEdr, true)); + ASSERT_TRUE(peer()->bredr()); + ASSERT_FALSE(peer()->le()); + + peer()->MutLe().SetConnectionState(Peer::ConnectionState::kConnected); + EXPECT_TRUE(peer()->le()); + EXPECT_EQ(TechnologyType::kDualMode, peer()->technology()); + + auto* const le_peer = cache()->FindByAddress(kAddrLeAlias); + ASSERT_EQ(peer(), le_peer); + EXPECT_EQ(DeviceAddress::Type::kBREDR, peer()->address().type()); +} + +TEST_F(GAP_PeerCacheTest, BrEdrPeerBecomesDualModeWithLowEnergyConnParams) { + ASSERT_TRUE(NewPeer(kAddrBrEdr, true)); + ASSERT_TRUE(peer()->bredr()); + ASSERT_FALSE(peer()->le()); + + peer()->MutLe().SetConnectionParameters({}); + EXPECT_TRUE(peer()->le()); + EXPECT_EQ(TechnologyType::kDualMode, peer()->technology()); + + auto* const le_peer = cache()->FindByAddress(kAddrLeAlias); + ASSERT_EQ(peer(), le_peer); + EXPECT_EQ(DeviceAddress::Type::kBREDR, peer()->address().type()); +} + +TEST_F(GAP_PeerCacheTest, + BrEdrPeerBecomesDualModeWithLowEnergyPreferredConnParams) { + ASSERT_TRUE(NewPeer(kAddrBrEdr, true)); + ASSERT_TRUE(peer()->bredr()); + ASSERT_FALSE(peer()->le()); + + peer()->MutLe().SetPreferredConnectionParameters({}); + EXPECT_TRUE(peer()->le()); + EXPECT_EQ(TechnologyType::kDualMode, peer()->technology()); + + auto* const le_peer = cache()->FindByAddress(kAddrLeAlias); + ASSERT_EQ(peer(), le_peer); + EXPECT_EQ(DeviceAddress::Type::kBREDR, peer()->address().type()); +} + +TEST_F(GAP_PeerCacheTest, LowEnergyPeerBecomesDualModeWithInquiryData) { + ASSERT_TRUE(NewPeer(kAddrLeAlias, true)); + ASSERT_TRUE(peer()->le()); + ASSERT_FALSE(peer()->bredr()); + + hci::InquiryResult ir; + ir.bd_addr = kAddrLeAlias.value(); + peer()->MutBrEdr().SetInquiryData(ir); + EXPECT_TRUE(peer()->bredr()); + EXPECT_EQ(TechnologyType::kDualMode, peer()->technology()); + + // Searching by only BR/EDR technology should turn up this peer, which + // should still retain its original address type. + auto* const bredr_peer = cache()->FindByAddress(kAddrBrEdr); + ASSERT_EQ(peer(), bredr_peer); + EXPECT_EQ(DeviceAddress::Type::kLEPublic, peer()->address().type()); + EXPECT_EQ(kAddrBrEdr, peer()->bredr()->address()); +} + +TEST_F(GAP_PeerCacheTest, + LowEnergyPeerBecomesDualModeWhenConnectedOverClassic) { + ASSERT_TRUE(NewPeer(kAddrLeAlias, true)); + ASSERT_TRUE(peer()->le()); + ASSERT_FALSE(peer()->bredr()); + + peer()->MutBrEdr().SetConnectionState(Peer::ConnectionState::kConnected); + EXPECT_TRUE(peer()->bredr()); + EXPECT_EQ(TechnologyType::kDualMode, peer()->technology()); + + auto* const bredr_peer = cache()->FindByAddress(kAddrBrEdr); + ASSERT_EQ(peer(), bredr_peer); + EXPECT_EQ(DeviceAddress::Type::kLEPublic, peer()->address().type()); + EXPECT_EQ(kAddrBrEdr, peer()->bredr()->address()); +} + +class GAP_PeerCacheTest_BondingTest : public GAP_PeerCacheTest { + public: + void SetUp() override { + GAP_PeerCacheTest::SetUp(); + ASSERT_TRUE(NewPeer(kAddrLePublic, true)); + bonded_callback_called_ = false; + cache()->set_peer_bonded_callback( + [this](const auto&) { bonded_callback_called_ = true; }); + updated_callback_count_ = 0; + cache()->set_peer_updated_callback( + [this](auto&) { updated_callback_count_++; }); + } + + void TearDown() override { + cache()->set_peer_updated_callback(nullptr); + updated_callback_count_ = 0; + cache()->set_peer_bonded_callback(nullptr); + bonded_callback_called_ = false; + GAP_PeerCacheTest::TearDown(); + } + + protected: + bool bonded_callback_called() const { return bonded_callback_called_; } + + // Returns 0 at the beginning of each test case. + int updated_callback_count() const { return updated_callback_count_; } + + private: + bool bonded_callback_called_; + int updated_callback_count_; +}; + +TEST_F(GAP_PeerCacheTest_BondingTest, AddBondedPeerFailsWithExistingId) { + sm::PairingData data; + data.ltk = kLTK; + EXPECT_FALSE( + cache()->AddBondedPeer(peer()->identifier(), kAddrLeRandom, data, {})); + EXPECT_FALSE(bonded_callback_called()); +} + +TEST_F(GAP_PeerCacheTest_BondingTest, AddBondedPeerFailsWithExistingAddress) { + sm::PairingData data; + data.ltk = kLTK; + EXPECT_FALSE(cache()->AddBondedPeer(kId, peer()->address(), data, {})); + EXPECT_FALSE(bonded_callback_called()); +} + +TEST_F(GAP_PeerCacheTest_BondingTest, + AddBondedLowEnergyPeerFailsWithExistingBrEdrAliasAddress) { + EXPECT_TRUE(NewPeer(kAddrBrEdr, true)); + sm::PairingData data; + data.ltk = kLTK; + EXPECT_FALSE(cache()->AddBondedPeer(kId, kAddrLeAlias, data, {})); + EXPECT_FALSE(bonded_callback_called()); +} + +TEST_F(GAP_PeerCacheTest_BondingTest, + AddBondedBrEdrPeerFailsWithExistingLowEnergyAliasAddress) { + EXPECT_TRUE(NewPeer(kAddrLeAlias, true)); + EXPECT_FALSE(cache()->AddBondedPeer(kId, kAddrBrEdr, {}, kBrEdrKey)); + EXPECT_FALSE(bonded_callback_called()); +} + +TEST_F(GAP_PeerCacheTest_BondingTest, AddBondedPeerFailsWithoutMandatoryKeys) { + sm::PairingData data; + EXPECT_FALSE(cache()->AddBondedPeer(kId, kAddrLeAlias, data, kBrEdrKey)); + data.ltk = kLTK; + EXPECT_FALSE(cache()->AddBondedPeer(kId, kAddrBrEdr, data, {})); + EXPECT_FALSE(bonded_callback_called()); +} + +TEST_F(GAP_PeerCacheTest_BondingTest, AddLowEnergyBondedPeerSuccess) { + sm::PairingData data; + data.ltk = kLTK; + + EXPECT_TRUE(cache()->AddBondedPeer(kId, kAddrLeRandom, data, {})); + auto* peer = cache()->FindById(kId); + ASSERT_TRUE(peer); + EXPECT_EQ(peer, cache()->FindByAddress(kAddrLeRandom)); + EXPECT_EQ(kId, peer->identifier()); + EXPECT_EQ(kAddrLeRandom, peer->address()); + EXPECT_TRUE(peer->identity_known()); + ASSERT_TRUE(peer->le()); + EXPECT_TRUE(peer->le()->bonded()); + ASSERT_TRUE(peer->le()->bond_data()); + EXPECT_EQ(data, *peer->le()->bond_data()); + EXPECT_FALSE(peer->bredr()); + EXPECT_EQ(TechnologyType::kLowEnergy, peer->technology()); + + // The "new bond" callback should not be called when restoring a previously + // bonded peer. + EXPECT_FALSE(bonded_callback_called()); +} + +TEST_F(GAP_PeerCacheTest_BondingTest, AddBrEdrBondedPeerSuccess) { + DeviceId kId(5); + sm::PairingData data; + + EXPECT_TRUE(cache()->AddBondedPeer(kId, kAddrBrEdr, data, kBrEdrKey)); + auto* peer = cache()->FindById(kId); + ASSERT_TRUE(peer); + EXPECT_EQ(peer, cache()->FindByAddress(kAddrBrEdr)); + EXPECT_EQ(kId, peer->identifier()); + EXPECT_EQ(kAddrBrEdr, peer->address()); + EXPECT_TRUE(peer->identity_known()); + ASSERT_TRUE(peer->bredr()); + EXPECT_TRUE(peer->bredr()->bonded()); + ASSERT_TRUE(peer->bredr()->link_key()); + EXPECT_EQ(kBrEdrKey, *peer->bredr()->link_key()); + EXPECT_FALSE(peer->le()); + EXPECT_EQ(TechnologyType::kClassic, peer->technology()); + + // The "new bond" callback should not be called when restoring a previously + // bonded peer. + EXPECT_FALSE(bonded_callback_called()); +} + +TEST_F(GAP_PeerCacheTest_BondingTest, + AddBondedPeerWithIrkIsAddedToResolvingList) { + sm::PairingData data; + data.ltk = kLTK; + data.irk = sm::Key(sm::SecurityProperties(), common::RandomUInt128()); + + EXPECT_TRUE(cache()->AddBondedPeer(kId, kAddrLeRandom, data, {})); + auto* peer = cache()->FindByAddress(kAddrLeRandom); + ASSERT_TRUE(peer); + EXPECT_EQ(kAddrLeRandom, peer->address()); + + // Looking up the peer by RPA generated using the IRK should return the same + // peer. + DeviceAddress rpa = sm::util::GenerateRpa(data.irk->value()); + EXPECT_EQ(peer, cache()->FindByAddress(rpa)); +} + +TEST_F(GAP_PeerCacheTest_BondingTest, StoreLowEnergyBondFailsWithNoKeys) { + sm::PairingData data; + EXPECT_FALSE(cache()->StoreLowEnergyBond(peer()->identifier(), data)); +} + +TEST_F(GAP_PeerCacheTest_BondingTest, StoreLowEnergyBondPeerUnknown) { + sm::PairingData data; + data.ltk = kLTK; + EXPECT_FALSE(cache()->StoreLowEnergyBond(kId, data)); +} + +TEST_F(GAP_PeerCacheTest_BondingTest, StoreLowEnergyBondWithLtk) { + ASSERT_TRUE(peer()->temporary()); + ASSERT_TRUE(peer()->le()); + ASSERT_FALSE(peer()->le()->bonded()); + + sm::PairingData data; + data.ltk = kLTK; + EXPECT_TRUE(cache()->StoreLowEnergyBond(peer()->identifier(), data)); + + EXPECT_TRUE(bonded_callback_called()); + EXPECT_FALSE(peer()->temporary()); + EXPECT_TRUE(peer()->le()->bonded()); + EXPECT_TRUE(peer()->le()->bond_data()); + EXPECT_EQ(data, *peer()->le()->bond_data()); +} + +TEST_F(GAP_PeerCacheTest_BondingTest, StoreLowEnergyBondWithCsrk) { + ASSERT_TRUE(peer()->temporary()); + ASSERT_TRUE(peer()->le()); + ASSERT_FALSE(peer()->le()->bonded()); + + sm::PairingData data; + data.csrk = kKey; + EXPECT_TRUE(cache()->StoreLowEnergyBond(peer()->identifier(), data)); + + EXPECT_TRUE(bonded_callback_called()); + EXPECT_FALSE(peer()->temporary()); + EXPECT_TRUE(peer()->le()->bonded()); + EXPECT_TRUE(peer()->le()->bond_data()); + EXPECT_EQ(data, *peer()->le()->bond_data()); +} + +// StoreLowEnergyBond fails if it contains the address of a different, +// previously known peer. +TEST_F(GAP_PeerCacheTest_BondingTest, + StoreLowEnergyBondWithExistingDifferentIdentity) { + auto* p = cache()->NewPeer(kAddrLeRandom, true); + + // Assign the other peer's address as identity. + sm::PairingData data; + data.ltk = kLTK; + data.identity_address = peer()->address(); + EXPECT_FALSE(cache()->StoreLowEnergyBond(p->identifier(), data)); + EXPECT_FALSE(p->le()->bonded()); + EXPECT_TRUE(p->temporary()); +} + +// StoreLowEnergyBond fails if the new identity is the address of a "different" +// (another peer record with a distinct ID) BR/EDR peer. +TEST_F(GAP_PeerCacheTest_BondingTest, + StoreLowEnergyBondWithNewIdentityMatchingExistingBrEdrPeer) { + ASSERT_TRUE(NewPeer(kAddrBrEdr, true)); + ASSERT_TRUE(NewPeer(kAddrLeRandom, true)); + ASSERT_FALSE(peer()->identity_known()); + + sm::PairingData data; + data.ltk = kLTK; + // new identity address is same as another peer's BR/EDR identity + data.identity_address = kAddrLeAlias; + const auto old_address = peer()->address(); + ASSERT_EQ(peer(), cache()->FindByAddress(old_address)); + ASSERT_NE(peer(), cache()->FindByAddress(*data.identity_address)); + EXPECT_FALSE(cache()->StoreLowEnergyBond(peer()->identifier(), data)); + EXPECT_FALSE(peer()->identity_known()); +} + +// StoreLowEnergyBond succeeds if it contains an identity address that already +// matches the target peer. +TEST_F(GAP_PeerCacheTest_BondingTest, + StoreLowEnergyBondWithExistingMatchingIdentity) { + sm::PairingData data; + data.ltk = kLTK; + data.identity_address = peer()->address(); + EXPECT_TRUE(cache()->StoreLowEnergyBond(peer()->identifier(), data)); + EXPECT_TRUE(peer()->le()->bonded()); + EXPECT_EQ(peer(), cache()->FindByAddress(*data.identity_address)); +} + +TEST_F(GAP_PeerCacheTest_BondingTest, StoreLowEnergyBondWithNewIdentity) { + ASSERT_TRUE(NewPeer(kAddrLeRandom, true)); + ASSERT_FALSE(peer()->identity_known()); + + sm::PairingData data; + data.ltk = kLTK; + data.identity_address = kAddrLeRandom2; // assign a new identity address + const auto old_address = peer()->address(); + ASSERT_EQ(peer(), cache()->FindByAddress(old_address)); + ASSERT_EQ(nullptr, cache()->FindByAddress(*data.identity_address)); + + EXPECT_TRUE(cache()->StoreLowEnergyBond(peer()->identifier(), data)); + EXPECT_TRUE(peer()->le()->bonded()); + + // Address should have been updated. + ASSERT_NE(*data.identity_address, old_address); + EXPECT_EQ(*data.identity_address, peer()->address()); + EXPECT_TRUE(peer()->identity_known()); + EXPECT_EQ(peer(), cache()->FindByAddress(*data.identity_address)); + + // The old address should still map to |peer|. + ASSERT_EQ(peer(), cache()->FindByAddress(old_address)); +} + +TEST_F(GAP_PeerCacheTest_BondingTest, + StoreLowEnergyBondWithIrkIsAddedToResolvingList) { + ASSERT_TRUE(NewPeer(kAddrLeRandom, true)); + ASSERT_FALSE(peer()->identity_known()); + + sm::PairingData data; + data.ltk = kLTK; + data.identity_address = kAddrLeRandom; + data.irk = sm::Key(sm::SecurityProperties(), common::RandomUInt128()); + + EXPECT_TRUE(cache()->StoreLowEnergyBond(peer()->identifier(), data)); + ASSERT_TRUE(peer()->le()->bonded()); + ASSERT_TRUE(peer()->identity_known()); + + // Looking up the peer by RPA generated using the IRK should return the same + // peer. + DeviceAddress rpa = sm::util::GenerateRpa(data.irk->value()); + EXPECT_EQ(peer(), cache()->FindByAddress(rpa)); +} + +TEST_F(GAP_PeerCacheTest_BondingTest, StoreBrEdrBondWithUnknownAddress) { + ASSERT_EQ(nullptr, cache()->FindByAddress(kAddrBrEdr)); + EXPECT_FALSE(cache()->StoreBrEdrBond(kAddrBrEdr, kBrEdrKey)); +} + +TEST_F(GAP_PeerCacheTest_BondingTest, StoreBrEdrBond) { + ASSERT_TRUE(NewPeer(kAddrBrEdr, true)); + ASSERT_EQ(peer(), cache()->FindByAddress(kAddrBrEdr)); + ASSERT_TRUE(peer()->temporary()); + ASSERT_FALSE(peer()->bonded()); + ASSERT_TRUE(peer()->bredr()); + ASSERT_FALSE(peer()->bredr()->bonded()); + + EXPECT_TRUE(cache()->StoreBrEdrBond(kAddrBrEdr, kBrEdrKey)); + + EXPECT_FALSE(peer()->temporary()); + EXPECT_TRUE(peer()->bonded()); + EXPECT_TRUE(peer()->bredr()->bonded()); + EXPECT_TRUE(peer()->bredr()->link_key()); + EXPECT_EQ(kBrEdrKey, *peer()->bredr()->link_key()); +} + +TEST_F(GAP_PeerCacheTest_BondingTest, StoreBondsForBothTech) { + ASSERT_TRUE(NewPeer(kAddrBrEdr, true)); + ASSERT_EQ(peer(), cache()->FindByAddress(kAddrBrEdr)); + ASSERT_TRUE(peer()->temporary()); + ASSERT_FALSE(peer()->bonded()); + + peer()->MutLe().SetAdvertisingData(kTestRSSI, kAdvData); + ASSERT_EQ(TechnologyType::kDualMode, peer()->technology()); + + // Without Secure Connections cross-transport key generation, bonding on one + // technology does not bond on the other. + ASSERT_FALSE(kBrEdrKey.security().secure_connections()); + EXPECT_TRUE(cache()->StoreBrEdrBond(kAddrBrEdr, kBrEdrKey)); + EXPECT_TRUE(peer()->bonded()); + EXPECT_FALSE(peer()->le()->bonded()); + + sm::PairingData data; + data.ltk = kLTK; + EXPECT_TRUE(cache()->StoreLowEnergyBond(peer()->identifier(), data)); + + EXPECT_FALSE(peer()->temporary()); + EXPECT_TRUE(peer()->bonded()); + EXPECT_TRUE(peer()->bredr()->bonded()); + EXPECT_TRUE(peer()->le()->bonded()); +} + +TEST_F(GAP_PeerCacheTest_BondingTest, ForgetUnknownPeer) { + const DeviceId id(0x9999); + ASSERT_FALSE(cache()->FindById(id)); + EXPECT_FALSE(cache()->ForgetPeer(id)); + EXPECT_EQ(0, updated_callback_count()); +} + +TEST_F(GAP_PeerCacheTest_BondingTest, ForgetBrEdrPeer) { + ASSERT_TRUE(NewPeer(kAddrBrEdr, true)); + ASSERT_TRUE(cache()->StoreBrEdrBond(kAddrBrEdr, kBrEdrKey)); + ASSERT_TRUE(peer()->bonded()); + ASSERT_FALSE(peer()->temporary()); + ASSERT_EQ(3, updated_callback_count()); + + const DeviceId id = peer()->identifier(); + EXPECT_TRUE(cache()->ForgetPeer(id)); + ASSERT_TRUE(cache()->FindById(id)); + EXPECT_FALSE(peer()->bonded()); + EXPECT_TRUE(peer()->temporary()); + EXPECT_EQ(4, updated_callback_count()); +} + +TEST_F(GAP_PeerCacheTest_BondingTest, ForgetLowEnergyPeerWithPublicAddress) { + sm::PairingData data; + data.ltk = kLTK; + ASSERT_TRUE(cache()->StoreLowEnergyBond(peer()->identifier(), data)); + ASSERT_EQ(DeviceAddress::Type::kLEPublic, peer()->address().type()); + ASSERT_TRUE(peer()->bonded()); + ASSERT_FALSE(peer()->temporary()); + ASSERT_EQ(2, updated_callback_count()); + + const DeviceId id = peer()->identifier(); + EXPECT_TRUE(cache()->ForgetPeer(id)); + ASSERT_TRUE(cache()->FindById(id)); + EXPECT_FALSE(peer()->bonded()); + EXPECT_TRUE(peer()->temporary()); + EXPECT_EQ(3, updated_callback_count()); +} + +TEST_F(GAP_PeerCacheTest_BondingTest, ForgetLowEnergyPeerWithIrk) { + ASSERT_TRUE(NewPeer(kAddrLeRandom, true)); + + sm::PairingData data; + data.ltk = kLTK; + data.identity_address = kAddrLeAlias; + data.irk = sm::Key(sm::SecurityProperties(), common::RandomUInt128()); + DeviceAddress rpa = sm::util::GenerateRpa(data.irk->value()); + + ASSERT_TRUE(cache()->StoreLowEnergyBond(peer()->identifier(), data)); + ASSERT_TRUE(peer()->bonded()); + ASSERT_FALSE(peer()->temporary()); + ASSERT_TRUE(peer()->identity_known()); + ASSERT_EQ(peer(), cache()->FindByAddress(rpa)); + ASSERT_EQ(kAddrLeAlias, peer()->address()); + EXPECT_EQ(3, updated_callback_count()); + + const DeviceId id = peer()->identifier(); + EXPECT_TRUE(cache()->ForgetPeer(id)); + ASSERT_TRUE(cache()->FindById(id)); + EXPECT_FALSE(peer()->bonded()); + EXPECT_TRUE(peer()->temporary()); + EXPECT_FALSE(peer()->identity_known()); + EXPECT_FALSE(cache()->FindByAddress(rpa)); + + // Don't expect the original random address to be restored. + EXPECT_EQ(kAddrLeAlias, peer()->address()); + EXPECT_EQ(4, updated_callback_count()); + + RunLoopFor(kCacheTimeout); + EXPECT_FALSE(cache()->FindById(id)); +} + +// Test that a forgotten LE peer using address privacy eventually expires out +// of the cache. +TEST_F(GAP_PeerCacheTest_BondingTest, + RemoveForgetedLePrivacyPeerAfterDisconnectionThenExpiry) { + ASSERT_TRUE(NewPeer(kAddrLeRandom, true)); + + sm::PairingData data; + data.ltk = kLTK; + data.identity_address = kAddrLeAlias; + data.irk = sm::Key(sm::SecurityProperties(), common::RandomUInt128()); + + ASSERT_TRUE(cache()->StoreLowEnergyBond(peer()->identifier(), data)); + peer()->MutLe().SetConnectionState(Peer::ConnectionState::kConnected); + ASSERT_TRUE(peer()->bonded()); + ASSERT_FALSE(peer()->temporary()); + + const DeviceId id = peer()->identifier(); + EXPECT_TRUE(cache()->ForgetPeer(id)); + ASSERT_TRUE(cache()->FindById(id)); + EXPECT_TRUE(peer()->temporary()); + + RunLoopFor(kCacheTimeout); + ASSERT_TRUE(cache()->FindById(id)); + + peer()->MutLe().SetConnectionState(Peer::ConnectionState::kNotConnected); + ASSERT_TRUE(cache()->FindById(id)); + EXPECT_TRUE(peer()->temporary()); + + RunLoopFor(kCacheTimeout); + EXPECT_FALSE(cache()->FindById(id)); +} + +// Fixture parameterized by peer address +class DualModeBondingTest + : public GAP_PeerCacheTest_BondingTest, + public ::testing::WithParamInterface<DeviceAddress> {}; + +TEST_P(DualModeBondingTest, AddBondedPeerSuccess) { + DeviceId kId(5); + sm::PairingData data; + data.ltk = kLTK; + + const DeviceAddress& address = GetParam(); + EXPECT_TRUE(cache()->AddBondedPeer(kId, address, data, kBrEdrKey)); + auto* peer = cache()->FindById(kId); + ASSERT_TRUE(peer); + EXPECT_EQ(peer, cache()->FindByAddress(kAddrLeAlias)); + EXPECT_EQ(peer, cache()->FindByAddress(kAddrBrEdr)); + EXPECT_EQ(kId, peer->identifier()); + EXPECT_EQ(address, peer->address()); + EXPECT_TRUE(peer->identity_known()); + EXPECT_TRUE(peer->bonded()); + ASSERT_TRUE(peer->le()); + EXPECT_TRUE(peer->le()->bonded()); + ASSERT_TRUE(peer->le()->bond_data()); + EXPECT_EQ(data, *peer->le()->bond_data()); + ASSERT_TRUE(peer->bredr()); + EXPECT_TRUE(peer->bredr()->bonded()); + ASSERT_TRUE(peer->bredr()->link_key()); + EXPECT_EQ(kBrEdrKey, *peer->bredr()->link_key()); + EXPECT_EQ(TechnologyType::kDualMode, peer->technology()); + + // The "new bond" callback should not be called when restoring a previously + // bonded peer. + EXPECT_FALSE(bonded_callback_called()); +} + +TEST_P(DualModeBondingTest, ForgetPeer) { + DeviceId kId(5); + sm::PairingData data; + data.ltk = kLTK; + + const DeviceAddress& address = GetParam(); + EXPECT_TRUE(cache()->AddBondedPeer(kId, address, data, kBrEdrKey)); + auto* peer = cache()->FindById(kId); + ASSERT_TRUE(peer); + ASSERT_TRUE(peer->bonded()); + EXPECT_EQ(5, updated_callback_count()); + + // Forgetting a dual-mode peer should only invoke the update callback once. + EXPECT_TRUE(cache()->ForgetPeer(kId)); + EXPECT_FALSE(peer->bonded()); + EXPECT_EQ(6, updated_callback_count()); +} + +// Test dual-mode character of peer using the same address of both types. +INSTANTIATE_TEST_SUITE_P(GAP_PeerCacheTest, DualModeBondingTest, + ::testing::Values(kAddrBrEdr, kAddrLeAlias)); + +template <const DeviceAddress* DevAddr> +class GAP_PeerCacheTest_UpdateCallbackTest : public GAP_PeerCacheTest { + public: + void SetUp() { + was_called_ = false; + ASSERT_TRUE(NewPeer(*DevAddr, true)); + cache()->set_peer_updated_callback( + [this](const auto&) { was_called_ = true; }); + ir_.bd_addr = peer()->address().value(); + irr_.bd_addr = peer()->address().value(); + eirep_.bd_addr = peer()->address().value(); + eir_data().SetToZeros(); + EXPECT_FALSE(was_called_); + } + + protected: + hci::InquiryResult& ir() { return ir_; } + hci::InquiryResultRSSI& irr() { return irr_; } + hci::ExtendedInquiryResultEventParams& eirep() { return eirep_; } + + MutableBufferView eir_data() { + return MutableBufferView(&eirep_.extended_inquiry_response, + sizeof(eirep_.extended_inquiry_response)); + } + bool was_called() const { return was_called_; } + void ClearWasCalled() { was_called_ = false; } + + private: + bool was_called_; + hci::InquiryResult ir_; + hci::InquiryResultRSSI irr_; + hci::ExtendedInquiryResultEventParams eirep_; +}; + +using GAP_PeerCacheTest_BrEdrUpdateCallbackTest = + GAP_PeerCacheTest_UpdateCallbackTest<&kAddrBrEdr>; +using GAP_PeerCacheTest_LowEnergyUpdateCallbackTest = + GAP_PeerCacheTest_UpdateCallbackTest<&kAddrLeAlias>; + +TEST_F(GAP_PeerCacheTest_LowEnergyUpdateCallbackTest, + ChangingLEConnectionStateTriggersUpdateCallback) { + peer()->MutLe().SetConnectionState(Peer::ConnectionState::kConnected); + EXPECT_TRUE(was_called()); +} + +TEST_F(GAP_PeerCacheTest_LowEnergyUpdateCallbackTest, + SetAdvertisingDataTriggersUpdateCallbackOnNameSet) { + peer()->MutLe().SetAdvertisingData(kTestRSSI, kAdvData); + EXPECT_TRUE(was_called()); + ASSERT_TRUE(peer()->name()); + EXPECT_EQ("Test", *peer()->name()); +} + +TEST_F(GAP_PeerCacheTest_LowEnergyUpdateCallbackTest, + SetLowEnergyAdvertisingDataUpdateCallbackProvidesUpdatedPeer) { + ASSERT_NE(peer()->rssi(), kTestRSSI); + cache()->set_peer_updated_callback([&](const auto& updated_peer) { + ASSERT_TRUE(updated_peer.le()); + EXPECT_TRUE(common::ContainersEqual(kAdvData, + updated_peer.le()->advertising_data())); + EXPECT_EQ(updated_peer.rssi(), kTestRSSI); + }); + peer()->MutLe().SetAdvertisingData(kTestRSSI, kAdvData); +} + +TEST_F(GAP_PeerCacheTest_LowEnergyUpdateCallbackTest, + SetAdvertisingDataDoesNotTriggerUpdateCallbackOnSameName) { + peer()->MutLe().SetAdvertisingData(kTestRSSI, kAdvData); + ASSERT_TRUE(was_called()); + + ClearWasCalled(); + peer()->MutLe().SetAdvertisingData(kTestRSSI, kAdvData); + EXPECT_FALSE(was_called()); +} + +TEST_F(GAP_PeerCacheTest_LowEnergyUpdateCallbackTest, + SetLowEnergyConnectionParamsDoesNotTriggerUpdateCallback) { + peer()->MutLe().SetConnectionParameters({}); + EXPECT_FALSE(was_called()); +} + +TEST_F(GAP_PeerCacheTest_LowEnergyUpdateCallbackTest, + SetLowEnergyPreferredConnectionParamsDoesNotTriggerUpdateCallback) { + peer()->MutLe().SetPreferredConnectionParameters({}); + EXPECT_FALSE(was_called()); +} + +TEST_F(GAP_PeerCacheTest_LowEnergyUpdateCallbackTest, + BecomingDualModeTriggersUpdateCallBack) { + EXPECT_EQ(TechnologyType::kLowEnergy, peer()->technology()); + + size_t call_count = 0; + cache()->set_peer_updated_callback([&](const auto&) { ++call_count; }); + peer()->MutBrEdr(); + EXPECT_EQ(TechnologyType::kDualMode, peer()->technology()); + EXPECT_EQ(call_count, 1U); + + // Calling MutBrEdr again on doesn't trigger additional callbacks. + peer()->MutBrEdr(); + EXPECT_EQ(call_count, 1U); + peer()->MutBrEdr().SetInquiryData(eirep()); + EXPECT_EQ(call_count, 2U); +} + +TEST_F(GAP_PeerCacheTest_BrEdrUpdateCallbackTest, + ChangingBrEdrConnectionStateTriggersUpdateCallback) { + peer()->MutBrEdr().SetConnectionState(Peer::ConnectionState::kConnected); + EXPECT_TRUE(was_called()); +} + +TEST_F( + GAP_PeerCacheTest_BrEdrUpdateCallbackTest, + SetBrEdrInquiryDataFromInquiryResultTriggersUpdateCallbackOnPeerClassSet) { + ir().class_of_device = kTestDeviceClass; + peer()->MutBrEdr().SetInquiryData(ir()); + EXPECT_TRUE(was_called()); +} + +TEST_F(GAP_PeerCacheTest_BrEdrUpdateCallbackTest, + SetBrEdrInquiryDataFromInquiryResultUpdateCallbackProvidesUpdatedPeer) { + ir().class_of_device = kTestDeviceClass; + cache()->set_peer_updated_callback([](const auto& updated_peer) { + ASSERT_TRUE(updated_peer.bredr()); + ASSERT_TRUE(updated_peer.bredr()->device_class()); + EXPECT_EQ(common::DeviceClass::MajorClass(0x02), + updated_peer.bredr()->device_class()->major_class()); + }); + peer()->MutBrEdr().SetInquiryData(ir()); +} + +TEST_F( + GAP_PeerCacheTest_BrEdrUpdateCallbackTest, + SetBrEdrInquiryDataFromInquiryResultDoesNotTriggerUpdateCallbackOnSameDeviceClass) { + ir().class_of_device = kTestDeviceClass; + peer()->MutBrEdr().SetInquiryData(ir()); + ASSERT_TRUE(was_called()); + + ClearWasCalled(); + peer()->MutBrEdr().SetInquiryData(ir()); + EXPECT_FALSE(was_called()); +} + +TEST_F( + GAP_PeerCacheTest_BrEdrUpdateCallbackTest, + SetBrEdrInquiryDataFromInquiryResultRSSITriggersUpdateCallbackOnDeviceClassSet) { + irr().class_of_device = kTestDeviceClass; + peer()->MutBrEdr().SetInquiryData(irr()); + EXPECT_TRUE(was_called()); +} + +TEST_F( + GAP_PeerCacheTest_BrEdrUpdateCallbackTest, + SetBrEdrInquiryDataFromInquiryResultRSSIUpdateCallbackProvidesUpdatedPeer) { + irr().class_of_device = kTestDeviceClass; + cache()->set_peer_updated_callback([](const auto& updated_peer) { + ASSERT_TRUE(updated_peer.bredr()->device_class()); + EXPECT_EQ(common::DeviceClass::MajorClass(0x02), + updated_peer.bredr()->device_class()->major_class()); + }); + peer()->MutBrEdr().SetInquiryData(irr()); +} + +TEST_F( + GAP_PeerCacheTest_BrEdrUpdateCallbackTest, + SetBrEdrInquiryDataFromInquiryResultRSSIDoesNotTriggerUpdateCallbackOnSameDeviceClass) { + irr().class_of_device = kTestDeviceClass; + peer()->MutBrEdr().SetInquiryData(irr()); + ASSERT_TRUE(was_called()); + + ClearWasCalled(); + peer()->MutBrEdr().SetInquiryData(irr()); + EXPECT_FALSE(was_called()); +} + +TEST_F( + GAP_PeerCacheTest_BrEdrUpdateCallbackTest, + SetBrEdrInquiryDataFromInquiryResultRSSIDoesNotTriggerUpdateCallbackOnRSSI) { + irr().rssi = 1; + peer()->MutBrEdr().SetInquiryData(irr()); + ASSERT_TRUE(was_called()); // Callback due to |class_of_device|. + + ClearWasCalled(); + irr().rssi = 20; + peer()->MutBrEdr().SetInquiryData(irr()); + EXPECT_FALSE(was_called()); +} + +TEST_F( + GAP_PeerCacheTest_BrEdrUpdateCallbackTest, + SetBrEdrInquiryDataFromExtendedInquiryResultEventParamsTriggersUpdateCallbackOnDeviceClassSet) { + eirep().class_of_device = kTestDeviceClass; + peer()->MutBrEdr().SetInquiryData(eirep()); + EXPECT_TRUE(was_called()); +} + +TEST_F( + GAP_PeerCacheTest_BrEdrUpdateCallbackTest, + SetBrEdrInquiryDataFromExtendedInquiryResultEventParamsTriggersUpdateCallbackOnNameSet) { + peer()->MutBrEdr().SetInquiryData(eirep()); + ASSERT_TRUE(was_called()); // Callback due to |class_of_device|. + + ClearWasCalled(); + eir_data().Write(kEirData); + peer()->MutBrEdr().SetInquiryData(eirep()); + EXPECT_TRUE(was_called()); +} + +TEST_F( + GAP_PeerCacheTest_BrEdrUpdateCallbackTest, + SetBrEdrInquiryDataFromExtendedInquiryResultEventParamsUpdateCallbackProvidesUpdatedPeer) { + eirep().clock_offset = htole16(1); + eirep().page_scan_repetition_mode = hci::PageScanRepetitionMode::kR1; + eirep().rssi = kTestRSSI; + eirep().class_of_device = kTestDeviceClass; + eir_data().Write(kEirData); + ASSERT_FALSE(peer()->name().has_value()); + ASSERT_EQ(peer()->rssi(), hci::kRSSIInvalid); + cache()->set_peer_updated_callback([](const auto& updated_peer) { + const auto& data = updated_peer.bredr(); + ASSERT_TRUE(data); + ASSERT_TRUE(data->clock_offset().has_value()); + ASSERT_TRUE(data->page_scan_repetition_mode().has_value()); + ASSERT_TRUE(data->device_class().has_value()); + ASSERT_TRUE(updated_peer.name().has_value()); + + EXPECT_EQ(*data->clock_offset(), 0x8001); + EXPECT_EQ(*data->page_scan_repetition_mode(), + hci::PageScanRepetitionMode::kR1); + EXPECT_EQ(common::DeviceClass::MajorClass(0x02), + updated_peer.bredr()->device_class()->major_class()); + EXPECT_EQ(updated_peer.rssi(), kTestRSSI); + EXPECT_EQ(*updated_peer.name(), "Test"); + }); + peer()->MutBrEdr().SetInquiryData(eirep()); +} + +TEST_F( + GAP_PeerCacheTest_BrEdrUpdateCallbackTest, + SetBrEdrInquiryDataFromExtendedInquiryResultEventParamsGeneratesExactlyOneUpdateCallbackRegardlessOfNumberOfFieldsChanged) { + eirep().clock_offset = htole16(1); + eirep().page_scan_repetition_mode = hci::PageScanRepetitionMode::kR1; + eirep().rssi = kTestRSSI; + eirep().class_of_device = kTestDeviceClass; + eir_data().Write(kEirData); + + size_t call_count = 0; + cache()->set_peer_updated_callback([&](const auto&) { ++call_count; }); + peer()->MutBrEdr().SetInquiryData(eirep()); + EXPECT_EQ(call_count, 1U); +} + +TEST_F( + GAP_PeerCacheTest_BrEdrUpdateCallbackTest, + SetBrEdrInquiryDataFromExtendedInquiryResultEventParamsDoesNotTriggerUpdateCallbackOnSamePeerClass) { + eirep().class_of_device = kTestDeviceClass; + peer()->MutBrEdr().SetInquiryData(eirep()); + ASSERT_TRUE(was_called()); + + ClearWasCalled(); + peer()->MutBrEdr().SetInquiryData(eirep()); + EXPECT_FALSE(was_called()); +} + +TEST_F( + GAP_PeerCacheTest_BrEdrUpdateCallbackTest, + SetBrEdrInquiryDataFromExtendedInquiryResultEventParamsDoesNotTriggerUpdateCallbackOnSameName) { + eir_data().Write(kEirData); + peer()->MutBrEdr().SetInquiryData(eirep()); + ASSERT_TRUE(was_called()); + + ClearWasCalled(); + peer()->MutBrEdr().SetInquiryData(eirep()); + EXPECT_FALSE(was_called()); +} + +TEST_F( + GAP_PeerCacheTest_BrEdrUpdateCallbackTest, + SetBrEdrInquiryDataFromExtendedInquiryResultEventParamsDoesNotTriggerUpdateCallbackOnRSSI) { + eirep().rssi = 1; + peer()->MutBrEdr().SetInquiryData(eirep()); + ASSERT_TRUE(was_called()); // Callback due to |class_of_device|. + + ClearWasCalled(); + eirep().rssi = 20; + peer()->MutBrEdr().SetInquiryData(eirep()); + EXPECT_FALSE(was_called()); +} + +TEST_F(GAP_PeerCacheTest_BrEdrUpdateCallbackTest, + SetNameTriggersUpdateCallback) { + peer()->SetName("nombre"); + EXPECT_TRUE(was_called()); +} + +TEST_F(GAP_PeerCacheTest_BrEdrUpdateCallbackTest, + SetNameDoesNotTriggerUpdateCallbackOnSameName) { + peer()->SetName("nombre"); + ASSERT_TRUE(was_called()); + + bool was_called_again = false; + cache()->set_peer_updated_callback( + [&](const auto&) { was_called_again = true; }); + peer()->SetName("nombre"); + EXPECT_FALSE(was_called_again); +} + +TEST_F(GAP_PeerCacheTest_BrEdrUpdateCallbackTest, + BecomingDualModeTriggersUpdateCallBack) { + EXPECT_EQ(TechnologyType::kClassic, peer()->technology()); + + size_t call_count = 0; + cache()->set_peer_updated_callback([&](const auto&) { ++call_count; }); + peer()->MutLe(); + EXPECT_EQ(TechnologyType::kDualMode, peer()->technology()); + EXPECT_EQ(call_count, 1U); + + // Calling MutLe again doesn't trigger additional callbacks. + peer()->MutLe(); + EXPECT_EQ(call_count, 1U); + peer()->MutLe().SetAdvertisingData(kTestRSSI, kAdvData); + EXPECT_EQ(call_count, 2U); +} + +class GAP_PeerCacheExpirationTest : public ::gtest::TestLoopFixture { + public: + void SetUp() { + TestLoopFixture::SetUp(); + cache_.set_peer_removed_callback([this](DeviceId) { peers_removed_++; }); + auto* peer = cache_.NewPeer(kAddrLeAlias, true /*connectable*/); + ASSERT_TRUE(peer); + ASSERT_TRUE(peer->temporary()); + peer_addr_ = peer->address(); + peer_addr_alias_ = kAddrBrEdr; + peer_id_ = peer->identifier(); + peers_removed_ = 0; + } + + void TearDown() { + cache_.set_peer_removed_callback(nullptr); + RunLoopUntilIdle(); + TestLoopFixture::TearDown(); + } + + Peer* GetDefaultPeer() { return cache_.FindById(peer_id_); } + Peer* GetPeerById(DeviceId id) { return cache_.FindById(id); } + bool IsDefaultPeerAddressInCache() const { + return cache_.FindByAddress(peer_addr_); + } + bool IsOtherTransportAddressInCache() const { + return cache_.FindByAddress(peer_addr_alias_); + } + bool IsDefaultPeerPresent() { return GetDefaultPeer(); } + Peer* NewPeer(const common::DeviceAddress& address, bool connectable) { + return cache_.NewPeer(address, connectable); + } + int peers_removed() const { return peers_removed_; } + + private: + PeerCache cache_; + common::DeviceAddress peer_addr_; + common::DeviceAddress peer_addr_alias_; + DeviceId peer_id_; + int peers_removed_; +}; + +TEST_F(GAP_PeerCacheExpirationTest, TemporaryDiesSixtySecondsAfterBirth) { + RunLoopFor(kCacheTimeout); + EXPECT_FALSE(IsDefaultPeerPresent()); + EXPECT_EQ(1, peers_removed()); +} + +TEST_F(GAP_PeerCacheExpirationTest, TemporaryLivesForSixtySecondsAfterBirth) { + RunLoopFor(kCacheTimeout - zx::msec(1)); + EXPECT_TRUE(IsDefaultPeerPresent()); + EXPECT_EQ(0, peers_removed()); +} + +TEST_F(GAP_PeerCacheExpirationTest, + TemporaryLivesForSixtySecondsSinceLastSeen) { + RunLoopFor(kCacheTimeout - zx::msec(1)); + ASSERT_TRUE(IsDefaultPeerPresent()); + + // Tickle peer, and verify it sticks around for another cache timeout. + GetDefaultPeer()->SetName("nombre"); + RunLoopFor(kCacheTimeout - zx::msec(1)); + EXPECT_TRUE(IsDefaultPeerPresent()); +} + +TEST_F(GAP_PeerCacheExpirationTest, TemporaryDiesSixtySecondsAfterLastSeen) { + RunLoopFor(kCacheTimeout - zx::msec(1)); + ASSERT_TRUE(IsDefaultPeerPresent()); + + // Tickle peer, and verify it expires after cache timeout. + GetDefaultPeer()->SetName("nombre"); + RunLoopFor(kCacheTimeout); + EXPECT_FALSE(IsDefaultPeerPresent()); +} + +TEST_F(GAP_PeerCacheExpirationTest, CanMakeNonTemporaryJustBeforeSixtySeconds) { + // At last possible moment, make peer non-temporary, + RunLoopFor(kCacheTimeout - zx::msec(1)); + ASSERT_TRUE(IsDefaultPeerPresent()); + GetDefaultPeer()->MutLe().SetConnectionState( + Peer::ConnectionState::kConnected); + ASSERT_FALSE(GetDefaultPeer()->temporary()); + + // Verify that the peer survives. + RunLoopFor(kCacheTimeout * 10); + EXPECT_TRUE(IsDefaultPeerPresent()); +} + +TEST_F(GAP_PeerCacheExpirationTest, + LEConnectedPeerLivesMuchMoreThanSixtySeconds) { + ASSERT_TRUE(IsDefaultPeerPresent()); + GetDefaultPeer()->MutLe().SetConnectionState( + Peer::ConnectionState::kConnected); + RunLoopFor(kCacheTimeout * 10); + ASSERT_TRUE(IsDefaultPeerPresent()); + EXPECT_FALSE(GetDefaultPeer()->temporary()); +} + +TEST_F(GAP_PeerCacheExpirationTest, + BREDRConnectedPeerLivesMuchMoreThanSixtySeconds) { + ASSERT_TRUE(IsDefaultPeerPresent()); + GetDefaultPeer()->MutBrEdr().SetConnectionState( + Peer::ConnectionState::kConnected); + RunLoopFor(kCacheTimeout * 10); + ASSERT_TRUE(IsDefaultPeerPresent()); + EXPECT_FALSE(GetDefaultPeer()->temporary()); +} + +TEST_F(GAP_PeerCacheExpirationTest, LePeerBecomesNonTemporaryWhenConnecting) { + ASSERT_TRUE(IsDefaultPeerPresent()); + ASSERT_EQ(kAddrLeAlias, GetDefaultPeer()->address()); + ASSERT_TRUE(GetDefaultPeer()->temporary()); + + GetDefaultPeer()->MutLe().SetConnectionState( + Peer::ConnectionState::kInitializing); + EXPECT_FALSE(GetDefaultPeer()->temporary()); + + RunLoopFor(kCacheTimeout); + ASSERT_TRUE(IsDefaultPeerPresent()); +} + +TEST_F(GAP_PeerCacheExpirationTest, + LEPublicPeerRemainsNonTemporaryOnDisconnect) { + ASSERT_TRUE(IsDefaultPeerPresent()); + ASSERT_EQ(kAddrLeAlias, GetDefaultPeer()->address()); + GetDefaultPeer()->MutLe().SetConnectionState( + Peer::ConnectionState::kConnected); + ASSERT_FALSE(GetDefaultPeer()->temporary()); + + RunLoopFor(zx::sec(61)); + ASSERT_TRUE(IsDefaultPeerPresent()); + ASSERT_TRUE(GetDefaultPeer()->identity_known()); + + GetDefaultPeer()->MutLe().SetConnectionState( + Peer::ConnectionState::kNotConnected); + EXPECT_FALSE(GetDefaultPeer()->temporary()); + + RunLoopFor(kCacheTimeout); + EXPECT_TRUE(IsDefaultPeerPresent()); +} + +TEST_F(GAP_PeerCacheExpirationTest, LERandomPeerBecomesTemporaryOnDisconnect) { + // Create our Peer, and get it into the kConnected state. + DeviceId custom_peer_id; + { + auto* custom_peer = NewPeer(kAddrLeRandom, true); + ASSERT_TRUE(custom_peer); + ASSERT_TRUE(custom_peer->temporary()); + ASSERT_FALSE(custom_peer->identity_known()); + custom_peer_id = custom_peer->identifier(); + + custom_peer->MutLe().SetConnectionState(Peer::ConnectionState::kConnected); + ASSERT_FALSE(custom_peer->temporary()); + ASSERT_FALSE(custom_peer->identity_known()); + } + + // Verify that the connected peer does not expire out of the cache. + // Then disconnect the peer, in preparation for the next stage of our test. + { + EXPECT_EQ(0, peers_removed()); + RunLoopFor(zx::sec(61)); + EXPECT_EQ(1, peers_removed()); // Default peer timed out. + auto* custom_peer = GetPeerById(custom_peer_id); + ASSERT_TRUE(custom_peer); + ASSERT_FALSE(custom_peer->identity_known()); + + custom_peer->MutLe().SetConnectionState( + Peer::ConnectionState::kNotConnected); + EXPECT_TRUE(custom_peer->temporary()); + EXPECT_FALSE(custom_peer->identity_known()); + } + + // Verify that the disconnected peer expires out of the cache. + RunLoopFor(zx::sec(61)); + EXPECT_FALSE(GetPeerById(custom_peer_id)); + EXPECT_EQ(2, peers_removed()); +} + +TEST_F(GAP_PeerCacheExpirationTest, BrEdrPeerRemainsNonTemporaryOnDisconnect) { + // Create our Peer, and get it into the kConnected state. + DeviceId custom_peer_id; + { + auto* custom_peer = NewPeer(kAddrLePublic, true); + ASSERT_TRUE(custom_peer); + custom_peer->MutLe().SetConnectionState(Peer::ConnectionState::kConnected); + custom_peer_id = custom_peer->identifier(); + } + + // Verify that the connected peer does not expire out of the cache. + // Then disconnect the peer, in preparation for the next stage of our test. + { + EXPECT_EQ(0, peers_removed()); + RunLoopFor(kCacheTimeout * 10); + EXPECT_EQ(1, peers_removed()); // Default peer timed out. + auto* custom_peer = GetPeerById(custom_peer_id); + ASSERT_TRUE(custom_peer); + ASSERT_TRUE(custom_peer->identity_known()); + EXPECT_FALSE(custom_peer->temporary()); + + custom_peer->MutLe().SetConnectionState( + Peer::ConnectionState::kNotConnected); + ASSERT_TRUE(GetPeerById(custom_peer_id)); + EXPECT_FALSE(custom_peer->temporary()); + } + + // Verify that the disconnected peer does _not_ expire out of the cache. + // We expect the peer to remain, because BrEdr peers are non-temporary + // even when disconnected. + RunLoopFor(kCacheTimeout); + EXPECT_TRUE(GetPeerById(custom_peer_id)); + EXPECT_EQ(1, peers_removed()); +} + +TEST_F(GAP_PeerCacheExpirationTest, ExpirationUpdatesAddressMap) { + ASSERT_TRUE(IsDefaultPeerAddressInCache()); + ASSERT_TRUE(IsOtherTransportAddressInCache()); + RunLoopFor(kCacheTimeout); + EXPECT_FALSE(IsDefaultPeerAddressInCache()); + EXPECT_FALSE(IsOtherTransportAddressInCache()); +} + +TEST_F(GAP_PeerCacheExpirationTest, SetAdvertisingDataUpdatesExpiration) { + RunLoopFor(kCacheTimeout - zx::msec(1)); + ASSERT_TRUE(IsDefaultPeerPresent()); + GetDefaultPeer()->MutLe().SetAdvertisingData(kTestRSSI, + StaticByteBuffer<1>{}); + RunLoopFor(zx::msec(1)); + EXPECT_TRUE(IsDefaultPeerPresent()); +} + +TEST_F(GAP_PeerCacheExpirationTest, + SetBrEdrInquiryDataFromInquiryResultUpdatesExpiration) { + hci::InquiryResult ir; + ASSERT_TRUE(IsDefaultPeerPresent()); + ir.bd_addr = GetDefaultPeer()->address().value(); + + RunLoopFor(kCacheTimeout - zx::msec(1)); + ASSERT_TRUE(IsDefaultPeerPresent()); + GetDefaultPeer()->MutBrEdr().SetInquiryData(ir); + + RunLoopFor(zx::msec(1)); + EXPECT_TRUE(IsDefaultPeerPresent()); +} + +TEST_F(GAP_PeerCacheExpirationTest, + SetBrEdrInquiryDataFromInquiryResultRSSIUpdatesExpiration) { + hci::InquiryResultRSSI irr; + ASSERT_TRUE(IsDefaultPeerPresent()); + irr.bd_addr = GetDefaultPeer()->address().value(); + + RunLoopFor(kCacheTimeout - zx::msec(1)); + ASSERT_TRUE(IsDefaultPeerPresent()); + GetDefaultPeer()->MutBrEdr().SetInquiryData(irr); + + RunLoopFor(zx::msec(1)); + EXPECT_TRUE(IsDefaultPeerPresent()); +} + +TEST_F( + GAP_PeerCacheExpirationTest, + SetBrEdrInquiryDataFromExtendedInquiryResultEventParamsUpdatesExpiration) { + hci::ExtendedInquiryResultEventParams eirep; + ASSERT_TRUE(IsDefaultPeerPresent()); + eirep.bd_addr = GetDefaultPeer()->address().value(); + + RunLoopFor(kCacheTimeout - zx::msec(1)); + ASSERT_TRUE(IsDefaultPeerPresent()); + GetDefaultPeer()->MutBrEdr().SetInquiryData(eirep); + + RunLoopFor(zx::msec(1)); + EXPECT_TRUE(IsDefaultPeerPresent()); +} + +TEST_F(GAP_PeerCacheExpirationTest, SetNameUpdatesExpiration) { + RunLoopFor(kCacheTimeout - zx::msec(1)); + ASSERT_TRUE(IsDefaultPeerPresent()); + GetDefaultPeer()->SetName({}); + RunLoopFor(zx::msec(1)); + EXPECT_TRUE(IsDefaultPeerPresent()); +} + +} // namespace +} // namespace gap +} // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/gap/remote_device_cache.h b/src/connectivity/bluetooth/core/bt-host/gap/remote_device_cache.h deleted file mode 100644 index a88eb9cdcf93ecf93b6e696b1420566067ee642e..0000000000000000000000000000000000000000 --- a/src/connectivity/bluetooth/core/bt-host/gap/remote_device_cache.h +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright 2017 The Fuchsia Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_GAP_REMOTE_DEVICE_CACHE_H_ -#define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_GAP_REMOTE_DEVICE_CACHE_H_ - -#include <fbl/function.h> -#include <fbl/macros.h> -#include <lib/async/cpp/task.h> - -#include <unordered_map> - -#include "src/connectivity/bluetooth/core/bt-host/common/device_address.h" -#include "src/connectivity/bluetooth/core/bt-host/gap/identity_resolving_list.h" -#include "src/connectivity/bluetooth/core/bt-host/gap/remote_device.h" -#include "src/connectivity/bluetooth/core/bt-host/hci/connection.h" -#include "src/connectivity/bluetooth/core/bt-host/sm/types.h" -#include "src/lib/fxl/synchronization/thread_checker.h" - -namespace bt { - -namespace common { -class ByteBuffer; -} // namespace common - -namespace hci { -struct LowEnergyScanResult; -} // namespace hci - -namespace gap { - -// A RemoteDeviceCache provides access to remote Bluetooth devices that are -// known to the system. -class RemoteDeviceCache final { - public: - using DeviceCallback = fit::function<void(const RemoteDevice& device)>; - using DeviceIdCallback = fit::function<void(DeviceId identifier)>; - - RemoteDeviceCache() = default; - - // Creates a new device entry using the given parameters, and returns a - // (non-owning) pointer to that device. The caller must not retain the pointer - // beyond the current dispatcher task, as the underlying RemoteDevice is owned - // by |this| RemoteDeviceCache, and may be invalidated spontaneously. - // - // Returns nullptr if an entry matching |address| already exists in the cache, - // including as a public identity of a device with a different technology. - RemoteDevice* NewDevice(const common::DeviceAddress& address, - bool connectable); - - // Iterates over all current devices in the map, running |f| on each entry - // synchronously. This is intended for IPC methods that request a list of - // devices. - // - // Clients should use the FindDeviceBy*() methods below to interact with - // RemoteDevice objects. - void ForEach(DeviceCallback f); - - // Creates a new non-temporary device entry using the given |identifier| and - // identity |address|. This is intended to initialize this RemoteDeviceCache - // with previously bonded devices while bootstrapping a bt-host device. The - // "device bonded" callback will not be invoked. - // - // This method is not intended for updating the bonding data of a device that - // already exists the cache and returns false if a mapping for |identifier| or - // |address| is already present. Use Store*Bond() methods to update pairing - // information of an existing device. - // - // If a device already exists that has the same public identity address with a - // different technology, this method will return false. The existing device - // should be instead updated with new bond information to create a dual-mode - // device. - // - bool AddBondedDevice(DeviceId identifier, - const common::DeviceAddress& address, - const sm::PairingData& bond_data, - const std::optional<sm::LTK>& link_key); - - // Update the device with the given identifier with new LE bonding - // information. The device will be considered "bonded" and the bonded callback - // will be notified. If the device is already bonded then bonding data will be - // updated. - // - // If |bond_data| contains an |identity_address|, the device cache will be - // updated with a new mapping from that address to this device identifier. If - // the identity address already maps to an existing device, this method will - // return false. TODO(armansito): Merge the devices instead of failing? What - // happens if we obtain a LE identity address from a dual-mode device that - // matches the BD_ADDR previously obtained from it over BR/EDR? - bool StoreLowEnergyBond(DeviceId identifier, - const sm::PairingData& bond_data); - - // Update a device identified by BD_ADDR |address| with a new BR/EDR link key. - // The device will be considered "bonded" and the bonded callback notified. If - // the device is already bonded then the link key will be updated. Returns - // false if the address does not match that of a known device. - bool StoreBrEdrBond(const common::DeviceAddress& address, - const sm::LTK& link_key); - - // Resets a peer |peer_id| to an unbonded state by removing secrets for its - // transports. The peer will become temporary and may expire. This does not - // otherwise disconnect the peer or remove its ID or address from the cache. - // Returns true if bonds were deleted from a known peer. - // - // TODO(BT-824): Delete the peer immediately after disconnecting. Will return - // true if a known peer was deleted or marked for deletion. - bool ForgetPeer(DeviceId peer_id); - - // Returns the remote device with identifier |identifier|. Returns nullptr if - // |identifier| is not recognized. - RemoteDevice* FindDeviceById(DeviceId identifier) const; - - // Finds and returns a RemoteDevice with address |address| if it exists, - // returns nullptr otherwise. Tries to resolve |address| if it is resolvable. - // If |address| is of type kBREDR or kLEPublic, then this searches for devices - // that have either type of address. - RemoteDevice* FindDeviceByAddress(const common::DeviceAddress& address) const; - - // When set, |callback| will be invoked whenever a device is added or updated. - void set_device_updated_callback(DeviceCallback callback) { - ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); - device_updated_callback_ = std::move(callback); - } - - // When set, |callback| will be invoked whenever a device is removed. - void set_device_removed_callback(DeviceIdCallback callback) { - ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); - device_removed_callback_ = std::move(callback); - } - - // When this callback is set, |callback| will be invoked whenever the bonding - // data of a device is updated and should be persisted. The caller must ensure - // that |callback| outlives |this|. - void set_device_bonded_callback(DeviceCallback callback) { - ZX_DEBUG_ASSERT(thread_checker_.IsCreationThreadCurrent()); - device_bonded_callback_ = std::move(callback); - } - - // Returns the number of devices that are currently in the device cache. - size_t count() const { return devices_.size(); } - - private: - class RemoteDeviceRecord final { - public: - RemoteDeviceRecord(std::unique_ptr<RemoteDevice> device, - fbl::Closure remove_device_callback) - : device_(std::move(device)), - removal_task_(std::move(remove_device_callback)) {} - - // The copy and move ctors cannot be implicitly defined, since - // async::TaskClosure does not support those operations. Nor is any - // meaningful explicit definition possible. - RemoteDeviceRecord(const RemoteDeviceRecord&) = delete; - RemoteDeviceRecord(RemoteDeviceRecord&&) = delete; - - RemoteDevice* device() const { return device_.get(); } - - // Returns a pointer to removal_task_, which can be used to (re-)schedule or - // cancel |remove_device_callback|. - async::TaskClosure* removal_task() { return &removal_task_; } - - private: - std::unique_ptr<RemoteDevice> device_; - async::TaskClosure removal_task_; - }; - - // Create and track a record of a remote device with a given |identifier|, - // |address|, and connectability (|connectable|). Returns a pointer to the - // inserted device or nullptr if |identifier| or |address| already exists in - // the cache. - RemoteDevice* InsertDeviceRecord(DeviceId identifier, - const common::DeviceAddress& address, - bool connectable); - - // Notifies interested parties that |device| has bonded - // |device| must already exist in the cache. - void NotifyDeviceBonded(const RemoteDevice& device); - - // Notifies interested parties that |device| has seen a significant change. - // |device| must already exist in the cache. - void NotifyDeviceUpdated(const RemoteDevice& device); - - // Updates the expiration time for |device|, if a temporary. Cancels expiry, - // if a non-temporary. Pre-conditions: - // - |device| must already exist in the cache - // - can only be called from the thread that created |device| - void UpdateExpiry(const RemoteDevice& device); - - // Updates the cache when an existing device is found to be dual-mode. Also - // notifies listeners of the "device updated" callback. - // |device| must already exist in the cache. - void MakeDualMode(const RemoteDevice& device); - - // Removes |device| from this cache, and notifies listeners of the removal. - void RemoveDevice(RemoteDevice* device); - - // Search for an unique device ID by its device address |address|, by both - // technologies if it is a public address. |address| should be already - // resolved, if it is resolvable. If found, returns a valid device ID; - // otherwise returns std::nullopt. - std::optional<DeviceId> FindIdByAddress( - const common::DeviceAddress& address) const; - - // Mapping from unique device IDs to RemoteDeviceRecords. - // Owns the corresponding RemoteDevices. - std::unordered_map<DeviceId, RemoteDeviceRecord> devices_; - - // Mapping from device addresses to unique device identifiers for all known - // devices. This is used to look-up and update existing cached data for a - // particular scan result so as to avoid creating duplicate entries for the - // same device. - // - // Dual-mode devices shall have identity addresses of both technologies - // mapped to the same ID, if the addresses have the same value. - std::unordered_map<common::DeviceAddress, DeviceId> address_map_; - - // The LE identity resolving list used to resolve RPAs. - IdentityResolvingList le_resolving_list_; - - DeviceCallback device_updated_callback_; - DeviceIdCallback device_removed_callback_; - DeviceCallback device_bonded_callback_; - - fxl::ThreadChecker thread_checker_; - - DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(RemoteDeviceCache); -}; - -} // namespace gap -} // namespace bt - -#endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_GAP_REMOTE_DEVICE_CACHE_H_ diff --git a/src/connectivity/bluetooth/core/bt-host/gap/remote_device_cache_unittest.cc b/src/connectivity/bluetooth/core/bt-host/gap/remote_device_cache_unittest.cc deleted file mode 100644 index d6577de5d38e8148dca07421c83791c98e455a31..0000000000000000000000000000000000000000 --- a/src/connectivity/bluetooth/core/bt-host/gap/remote_device_cache_unittest.cc +++ /dev/null @@ -1,1471 +0,0 @@ -// Copyright 2017 The Fuchsia Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "src/connectivity/bluetooth/core/bt-host/gap/remote_device_cache.h" - -#include "gtest/gtest.h" -#include "lib/gtest/test_loop_fixture.h" - -#include "src/connectivity/bluetooth/core/bt-host/common/device_class.h" -#include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" -#include "src/connectivity/bluetooth/core/bt-host/common/uint128.h" -#include "src/connectivity/bluetooth/core/bt-host/gap/remote_device.h" -#include "src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.h" -#include "src/connectivity/bluetooth/core/bt-host/sm/types.h" -#include "src/connectivity/bluetooth/core/bt-host/sm/util.h" - -namespace bt { -namespace gap { -namespace { - -using common::CreateStaticByteBuffer; -using common::DeviceAddress; -using common::MutableBufferView; -using common::StaticByteBuffer; - -// All fields are initialized to zero as they are unused in these tests. -const hci::LEConnectionParameters kTestParams; - -// Arbitrary ID value used by the bonding tests below. The actual value of this -// constant does not effect the test logic. -constexpr DeviceId kId(100); -constexpr int8_t kTestRSSI = 10; - -const DeviceAddress kAddrBrEdr(DeviceAddress::Type::kBREDR, - "AA:BB:CC:DD:EE:FF"); -const DeviceAddress kAddrLePublic(DeviceAddress::Type::kLEPublic, - "01:02:03:04:05:06"); -// LE Public Device Address that has the same value as a BR/EDR BD_ADDR, e.g. on -// a dual-mode device. -const DeviceAddress kAddrLeAlias(DeviceAddress::Type::kLEPublic, - "AA:BB:CC:DD:EE:FF"); - -// TODO(armansito): Make these adhere to privacy specification. -const DeviceAddress kAddrLeRandom(DeviceAddress::Type::kLERandom, - "06:05:04:03:02:01"); -const DeviceAddress kAddrLeRandom2(DeviceAddress::Type::kLERandom, - "FF:EE:DD:CC:BB:AA"); -const DeviceAddress kAddrLeAnon(DeviceAddress::Type::kLEAnonymous, - "06:05:04:03:02:01"); - -const auto kAdvData = - CreateStaticByteBuffer(0x05, // Length - 0x09, // AD type: Complete Local Name - 'T', 'e', 's', 't'); -const auto kEirData = kAdvData; - -const bt::sm::LTK kLTK; -const bt::sm::Key kKey{}; - -const bt::sm::LTK kBrEdrKey; - -// Phone (Networking) -const common::DeviceClass kTestDeviceClass({0x06, 0x02, 0x02}); - -class GAP_RemoteDeviceCacheTest : public ::gtest::TestLoopFixture { - public: - void SetUp() override { TestLoopFixture::SetUp(); } - - void TearDown() override { - RunLoopUntilIdle(); - TestLoopFixture::TearDown(); - } - - protected: - // Creates a new RemoteDevice, and caches a pointer to that device. - __WARN_UNUSED_RESULT bool NewDevice(const DeviceAddress& addr, - bool connectable) { - auto* dev = cache_.NewDevice(addr, connectable); - if (!dev) { - return false; - } - device_ = dev; - return true; - } - - RemoteDeviceCache* cache() { return &cache_; } - // Returns the cached pointer to the device created in the most recent call to - // NewDevice(). The caller must ensure that the device has not expired out of - // the cache. (Tests of cache expiration should generally subclass the - // GAP_RemoteDeviceCacheExpirationTest fixture.) - RemoteDevice* device() { return device_; } - - private: - RemoteDeviceCache cache_; - RemoteDevice* device_; -}; - -TEST_F(GAP_RemoteDeviceCacheTest, LookUp) { - auto kAdvData0 = CreateStaticByteBuffer(0x05, 0x09, 'T', 'e', 's', 't'); - auto kAdvData1 = CreateStaticByteBuffer(0x0C, 0x09, 'T', 'e', 's', 't', ' ', - 'D', 'e', 'v', 'i', 'c', 'e'); - - // These should return false regardless of the input while the cache is empty. - EXPECT_FALSE(cache()->FindDeviceByAddress(kAddrLePublic)); - EXPECT_FALSE(cache()->FindDeviceById(kId)); - - auto device = cache()->NewDevice(kAddrLePublic, true); - ASSERT_TRUE(device); - ASSERT_TRUE(device->le()); - EXPECT_EQ(TechnologyType::kLowEnergy, device->technology()); - EXPECT_TRUE(device->connectable()); - EXPECT_TRUE(device->temporary()); - EXPECT_EQ(kAddrLePublic, device->address()); - EXPECT_EQ(0u, device->le()->advertising_data().size()); - EXPECT_EQ(hci::kRSSIInvalid, device->rssi()); - - // A look up should return the same instance. - EXPECT_EQ(device, cache()->FindDeviceById(device->identifier())); - EXPECT_EQ(device, cache()->FindDeviceByAddress(device->address())); - - // Adding a device with the same address should return nullptr. - EXPECT_FALSE(cache()->NewDevice(kAddrLePublic, true)); - - device->MutLe().SetAdvertisingData(kTestRSSI, kAdvData1); - EXPECT_TRUE( - common::ContainersEqual(kAdvData1, device->le()->advertising_data())); - EXPECT_EQ(kTestRSSI, device->rssi()); - - device->MutLe().SetAdvertisingData(kTestRSSI, kAdvData0); - EXPECT_TRUE( - common::ContainersEqual(kAdvData0, device->le()->advertising_data())); - EXPECT_EQ(kTestRSSI, device->rssi()); -} - -TEST_F(GAP_RemoteDeviceCacheTest, LookUpBrEdrDeviceByLePublicAlias) { - ASSERT_FALSE(cache()->FindDeviceByAddress(kAddrLeAlias)); - ASSERT_TRUE(NewDevice(kAddrBrEdr, true)); - auto* dev = cache()->FindDeviceByAddress(kAddrBrEdr); - ASSERT_TRUE(dev); - EXPECT_EQ(device(), dev); - - dev = cache()->FindDeviceByAddress(kAddrLeAlias); - ASSERT_TRUE(dev); - EXPECT_EQ(device(), dev); - EXPECT_EQ(DeviceAddress::Type::kBREDR, dev->address().type()); -} - -TEST_F(GAP_RemoteDeviceCacheTest, LookUpLeDeviceByBrEdrAlias) { - EXPECT_FALSE(cache()->FindDeviceByAddress(kAddrBrEdr)); - ASSERT_TRUE(NewDevice(kAddrLeAlias, true)); - auto* dev = cache()->FindDeviceByAddress(kAddrLeAlias); - ASSERT_TRUE(dev); - EXPECT_EQ(device(), dev); - - dev = cache()->FindDeviceByAddress(kAddrBrEdr); - ASSERT_TRUE(dev); - EXPECT_EQ(device(), dev); - EXPECT_EQ(DeviceAddress::Type::kLEPublic, dev->address().type()); -} - -TEST_F(GAP_RemoteDeviceCacheTest, - NewDeviceDoesNotCrashWhenNoCallbackIsRegistered) { - RemoteDeviceCache().NewDevice(kAddrLePublic, true); -} - -TEST_F(GAP_RemoteDeviceCacheTest, ForEachEmpty) { - bool found = false; - cache()->ForEach([&](const auto&) { found = true; }); - EXPECT_FALSE(found); -} - -TEST_F(GAP_RemoteDeviceCacheTest, ForEach) { - int count = 0; - ASSERT_TRUE(NewDevice(kAddrLePublic, true)); - cache()->ForEach([&](const auto& dev) { - count++; - EXPECT_EQ(device()->identifier(), dev.identifier()); - EXPECT_EQ(device()->address(), dev.address()); - }); - EXPECT_EQ(1, count); -} - -TEST_F(GAP_RemoteDeviceCacheTest, - NewDeviceInvokesCallbackWhenDeviceIsFirstRegistered) { - bool was_called = false; - cache()->set_device_updated_callback( - [&was_called](const auto&) { was_called = true; }); - cache()->NewDevice(kAddrLePublic, true); - EXPECT_TRUE(was_called); -} - -TEST_F(GAP_RemoteDeviceCacheTest, - NewDeviceDoesNotInvokeCallbackWhenDeviceIsReRegistered) { - int call_count = 0; - cache()->set_device_updated_callback( - [&call_count](const auto&) { ++call_count; }); - cache()->NewDevice(kAddrLePublic, true); - cache()->NewDevice(kAddrLePublic, true); - EXPECT_EQ(1, call_count); -} - -TEST_F(GAP_RemoteDeviceCacheTest, NewDeviceIdentityKnown) { - EXPECT_TRUE(cache()->NewDevice(kAddrBrEdr, true)->identity_known()); - EXPECT_TRUE(cache()->NewDevice(kAddrLePublic, true)->identity_known()); - EXPECT_FALSE(cache()->NewDevice(kAddrLeRandom, true)->identity_known()); - EXPECT_FALSE(cache()->NewDevice(kAddrLeAnon, false)->identity_known()); -} - -TEST_F(GAP_RemoteDeviceCacheTest, NewDeviceInitialTechnologyIsClassic) { - ASSERT_TRUE(NewDevice(kAddrBrEdr, true)); - - // A device initialized with a BR/EDR address should start out as a - // classic-only. - ASSERT_TRUE(device()); - EXPECT_TRUE(device()->bredr()); - EXPECT_FALSE(device()->le()); - EXPECT_TRUE(device()->identity_known()); - EXPECT_EQ(TechnologyType::kClassic, device()->technology()); -} - -TEST_F(GAP_RemoteDeviceCacheTest, NewDeviceInitialTechnologyLowEnergy) { - // LE address types should initialize the device as LE-only. - auto* le_publ_dev = cache()->NewDevice(kAddrLePublic, true /*connectable*/); - auto* le_rand_dev = cache()->NewDevice(kAddrLeRandom, true /*connectable*/); - auto* le_anon_dev = cache()->NewDevice(kAddrLeAnon, false /*connectable*/); - ASSERT_TRUE(le_publ_dev); - ASSERT_TRUE(le_rand_dev); - ASSERT_TRUE(le_anon_dev); - EXPECT_TRUE(le_publ_dev->le()); - EXPECT_TRUE(le_rand_dev->le()); - EXPECT_TRUE(le_anon_dev->le()); - EXPECT_FALSE(le_publ_dev->bredr()); - EXPECT_FALSE(le_rand_dev->bredr()); - EXPECT_FALSE(le_anon_dev->bredr()); - EXPECT_EQ(TechnologyType::kLowEnergy, le_publ_dev->technology()); - EXPECT_EQ(TechnologyType::kLowEnergy, le_rand_dev->technology()); - EXPECT_EQ(TechnologyType::kLowEnergy, le_anon_dev->technology()); - EXPECT_TRUE(le_publ_dev->identity_known()); - EXPECT_FALSE(le_rand_dev->identity_known()); - EXPECT_FALSE(le_anon_dev->identity_known()); -} - -TEST_F(GAP_RemoteDeviceCacheTest, - DisallowNewLowEnergyDeviceIfBrEdrDeviceExists) { - ASSERT_TRUE(NewDevice(kAddrBrEdr, true)); - - // Try to add new LE device with a public identity address containing the same - // value as the existing BR/EDR device's BD_ADDR. - auto* le_alias_dev = cache()->NewDevice(kAddrLeAlias, true); - EXPECT_FALSE(le_alias_dev); -} - -TEST_F(GAP_RemoteDeviceCacheTest, - DisallowNewBrEdrDeviceIfLowEnergyDeviceExists) { - ASSERT_TRUE(NewDevice(kAddrLeAlias, true)); - - // Try to add new BR/EDR device with BD_ADDR containing the same value as the - // existing LE device's public identity address. - auto* bredr_alias_dev = cache()->NewDevice(kAddrBrEdr, true); - ASSERT_FALSE(bredr_alias_dev); -} - -TEST_F(GAP_RemoteDeviceCacheTest, - BrEdrDeviceBecomesDualModeWithAdvertisingData) { - ASSERT_TRUE(NewDevice(kAddrBrEdr, true)); - ASSERT_TRUE(device()->bredr()); - ASSERT_FALSE(device()->le()); - - device()->MutLe().SetAdvertisingData(kTestRSSI, kAdvData); - EXPECT_TRUE(device()->le()); - EXPECT_EQ(TechnologyType::kDualMode, device()->technology()); - - // Searching by LE address should turn up this device, which should retain its - // original address type. - auto* const le_device = cache()->FindDeviceByAddress(kAddrLeAlias); - ASSERT_EQ(device(), le_device); - EXPECT_EQ(DeviceAddress::Type::kBREDR, device()->address().type()); -} - -TEST_F(GAP_RemoteDeviceCacheTest, - BrEdrDeviceBecomesDualModeWhenConnectedOverLowEnergy) { - ASSERT_TRUE(NewDevice(kAddrBrEdr, true)); - ASSERT_TRUE(device()->bredr()); - ASSERT_FALSE(device()->le()); - - device()->MutLe().SetConnectionState( - RemoteDevice::ConnectionState::kConnected); - EXPECT_TRUE(device()->le()); - EXPECT_EQ(TechnologyType::kDualMode, device()->technology()); - - auto* const le_device = cache()->FindDeviceByAddress(kAddrLeAlias); - ASSERT_EQ(device(), le_device); - EXPECT_EQ(DeviceAddress::Type::kBREDR, device()->address().type()); -} - -TEST_F(GAP_RemoteDeviceCacheTest, - BrEdrDeviceBecomesDualModeWithLowEnergyConnParams) { - ASSERT_TRUE(NewDevice(kAddrBrEdr, true)); - ASSERT_TRUE(device()->bredr()); - ASSERT_FALSE(device()->le()); - - device()->MutLe().SetConnectionParameters({}); - EXPECT_TRUE(device()->le()); - EXPECT_EQ(TechnologyType::kDualMode, device()->technology()); - - auto* const le_device = cache()->FindDeviceByAddress(kAddrLeAlias); - ASSERT_EQ(device(), le_device); - EXPECT_EQ(DeviceAddress::Type::kBREDR, device()->address().type()); -} - -TEST_F(GAP_RemoteDeviceCacheTest, - BrEdrDeviceBecomesDualModeWithLowEnergyPreferredConnParams) { - ASSERT_TRUE(NewDevice(kAddrBrEdr, true)); - ASSERT_TRUE(device()->bredr()); - ASSERT_FALSE(device()->le()); - - device()->MutLe().SetPreferredConnectionParameters({}); - EXPECT_TRUE(device()->le()); - EXPECT_EQ(TechnologyType::kDualMode, device()->technology()); - - auto* const le_device = cache()->FindDeviceByAddress(kAddrLeAlias); - ASSERT_EQ(device(), le_device); - EXPECT_EQ(DeviceAddress::Type::kBREDR, device()->address().type()); -} - -TEST_F(GAP_RemoteDeviceCacheTest, - LowEnergyDeviceBecomesDualModeWithInquiryData) { - ASSERT_TRUE(NewDevice(kAddrLeAlias, true)); - ASSERT_TRUE(device()->le()); - ASSERT_FALSE(device()->bredr()); - - hci::InquiryResult ir; - ir.bd_addr = kAddrLeAlias.value(); - device()->MutBrEdr().SetInquiryData(ir); - EXPECT_TRUE(device()->bredr()); - EXPECT_EQ(TechnologyType::kDualMode, device()->technology()); - - // Searching by only BR/EDR technology should turn up this device, which - // should still retain its original address type. - auto* const bredr_device = cache()->FindDeviceByAddress(kAddrBrEdr); - ASSERT_EQ(device(), bredr_device); - EXPECT_EQ(DeviceAddress::Type::kLEPublic, device()->address().type()); - EXPECT_EQ(kAddrBrEdr, device()->bredr()->address()); -} - -TEST_F(GAP_RemoteDeviceCacheTest, - LowEnergyDeviceBecomesDualModeWhenConnectedOverClassic) { - ASSERT_TRUE(NewDevice(kAddrLeAlias, true)); - ASSERT_TRUE(device()->le()); - ASSERT_FALSE(device()->bredr()); - - device()->MutBrEdr().SetConnectionState( - RemoteDevice::ConnectionState::kConnected); - EXPECT_TRUE(device()->bredr()); - EXPECT_EQ(TechnologyType::kDualMode, device()->technology()); - - auto* const bredr_device = cache()->FindDeviceByAddress(kAddrBrEdr); - ASSERT_EQ(device(), bredr_device); - EXPECT_EQ(DeviceAddress::Type::kLEPublic, device()->address().type()); - EXPECT_EQ(kAddrBrEdr, device()->bredr()->address()); -} - -class GAP_RemoteDeviceCacheTest_BondingTest : public GAP_RemoteDeviceCacheTest { - public: - void SetUp() override { - GAP_RemoteDeviceCacheTest::SetUp(); - ASSERT_TRUE(NewDevice(kAddrLePublic, true)); - bonded_callback_called_ = false; - cache()->set_device_bonded_callback( - [this](const auto&) { bonded_callback_called_ = true; }); - updated_callback_count_ = 0; - cache()->set_device_updated_callback( - [this](auto&) { updated_callback_count_++; }); - } - - void TearDown() override { - cache()->set_device_updated_callback(nullptr); - updated_callback_count_ = 0; - cache()->set_device_bonded_callback(nullptr); - bonded_callback_called_ = false; - GAP_RemoteDeviceCacheTest::TearDown(); - } - - protected: - bool bonded_callback_called() const { return bonded_callback_called_; } - - // Returns 0 at the beginning of each test case. - int updated_callback_count() const { return updated_callback_count_; } - - private: - bool bonded_callback_called_; - int updated_callback_count_; -}; - -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, - AddBondedDeviceFailsWithExistingId) { - sm::PairingData data; - data.ltk = kLTK; - EXPECT_FALSE(cache()->AddBondedDevice(device()->identifier(), kAddrLeRandom, - data, {})); - EXPECT_FALSE(bonded_callback_called()); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, - AddBondedDeviceFailsWithExistingAddress) { - sm::PairingData data; - data.ltk = kLTK; - EXPECT_FALSE(cache()->AddBondedDevice(kId, device()->address(), data, {})); - EXPECT_FALSE(bonded_callback_called()); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, - AddBondedLowEnergyDeviceFailsWithExistingBrEdrAliasAddress) { - EXPECT_TRUE(NewDevice(kAddrBrEdr, true)); - sm::PairingData data; - data.ltk = kLTK; - EXPECT_FALSE(cache()->AddBondedDevice(kId, kAddrLeAlias, data, {})); - EXPECT_FALSE(bonded_callback_called()); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, - AddBondedBrEdrDeviceFailsWithExistingLowEnergyAliasAddress) { - EXPECT_TRUE(NewDevice(kAddrLeAlias, true)); - EXPECT_FALSE(cache()->AddBondedDevice(kId, kAddrBrEdr, {}, kBrEdrKey)); - EXPECT_FALSE(bonded_callback_called()); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, - AddBondedDeviceFailsWithoutMandatoryKeys) { - sm::PairingData data; - EXPECT_FALSE(cache()->AddBondedDevice(kId, kAddrLeAlias, data, kBrEdrKey)); - data.ltk = kLTK; - EXPECT_FALSE(cache()->AddBondedDevice(kId, kAddrBrEdr, data, {})); - EXPECT_FALSE(bonded_callback_called()); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, AddLowEnergyBondedDeviceSuccess) { - sm::PairingData data; - data.ltk = kLTK; - - EXPECT_TRUE(cache()->AddBondedDevice(kId, kAddrLeRandom, data, {})); - auto* dev = cache()->FindDeviceById(kId); - ASSERT_TRUE(dev); - EXPECT_EQ(dev, cache()->FindDeviceByAddress(kAddrLeRandom)); - EXPECT_EQ(kId, dev->identifier()); - EXPECT_EQ(kAddrLeRandom, dev->address()); - EXPECT_TRUE(dev->identity_known()); - ASSERT_TRUE(dev->le()); - EXPECT_TRUE(dev->le()->bonded()); - ASSERT_TRUE(dev->le()->bond_data()); - EXPECT_EQ(data, *dev->le()->bond_data()); - EXPECT_FALSE(dev->bredr()); - EXPECT_EQ(TechnologyType::kLowEnergy, dev->technology()); - - // The "new bond" callback should not be called when restoring a previously - // bonded device. - EXPECT_FALSE(bonded_callback_called()); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, AddBrEdrBondedDeviceSuccess) { - DeviceId kId(5); - sm::PairingData data; - - EXPECT_TRUE(cache()->AddBondedDevice(kId, kAddrBrEdr, data, kBrEdrKey)); - auto* dev = cache()->FindDeviceById(kId); - ASSERT_TRUE(dev); - EXPECT_EQ(dev, cache()->FindDeviceByAddress(kAddrBrEdr)); - EXPECT_EQ(kId, dev->identifier()); - EXPECT_EQ(kAddrBrEdr, dev->address()); - EXPECT_TRUE(dev->identity_known()); - ASSERT_TRUE(dev->bredr()); - EXPECT_TRUE(dev->bredr()->bonded()); - ASSERT_TRUE(dev->bredr()->link_key()); - EXPECT_EQ(kBrEdrKey, *dev->bredr()->link_key()); - EXPECT_FALSE(dev->le()); - EXPECT_EQ(TechnologyType::kClassic, dev->technology()); - - // The "new bond" callback should not be called when restoring a previously - // bonded device. - EXPECT_FALSE(bonded_callback_called()); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, - AddBondedDeviceWithIrkIsAddedToResolvingList) { - sm::PairingData data; - data.ltk = kLTK; - data.irk = sm::Key(sm::SecurityProperties(), common::RandomUInt128()); - - EXPECT_TRUE(cache()->AddBondedDevice(kId, kAddrLeRandom, data, {})); - auto* dev = cache()->FindDeviceByAddress(kAddrLeRandom); - ASSERT_TRUE(dev); - EXPECT_EQ(kAddrLeRandom, dev->address()); - - // Looking up the device by RPA generated using the IRK should return the same - // device. - DeviceAddress rpa = sm::util::GenerateRpa(data.irk->value()); - EXPECT_EQ(dev, cache()->FindDeviceByAddress(rpa)); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, - StoreLowEnergyBondFailsWithNoKeys) { - sm::PairingData data; - EXPECT_FALSE(cache()->StoreLowEnergyBond(device()->identifier(), data)); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, StoreLowEnergyBondDeviceUnknown) { - sm::PairingData data; - data.ltk = kLTK; - EXPECT_FALSE(cache()->StoreLowEnergyBond(kId, data)); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, StoreLowEnergyBondWithLtk) { - ASSERT_TRUE(device()->temporary()); - ASSERT_TRUE(device()->le()); - ASSERT_FALSE(device()->le()->bonded()); - - sm::PairingData data; - data.ltk = kLTK; - EXPECT_TRUE(cache()->StoreLowEnergyBond(device()->identifier(), data)); - - EXPECT_TRUE(bonded_callback_called()); - EXPECT_FALSE(device()->temporary()); - EXPECT_TRUE(device()->le()->bonded()); - EXPECT_TRUE(device()->le()->bond_data()); - EXPECT_EQ(data, *device()->le()->bond_data()); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, StoreLowEnergyBondWithCsrk) { - ASSERT_TRUE(device()->temporary()); - ASSERT_TRUE(device()->le()); - ASSERT_FALSE(device()->le()->bonded()); - - sm::PairingData data; - data.csrk = kKey; - EXPECT_TRUE(cache()->StoreLowEnergyBond(device()->identifier(), data)); - - EXPECT_TRUE(bonded_callback_called()); - EXPECT_FALSE(device()->temporary()); - EXPECT_TRUE(device()->le()->bonded()); - EXPECT_TRUE(device()->le()->bond_data()); - EXPECT_EQ(data, *device()->le()->bond_data()); -} - -// StoreLowEnergyBond fails if it contains the address of a different, -// previously known device. -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, - StoreLowEnergyBondWithExistingDifferentIdentity) { - auto* dev = cache()->NewDevice(kAddrLeRandom, true); - - // Assign the other device's address as identity. - sm::PairingData data; - data.ltk = kLTK; - data.identity_address = device()->address(); - EXPECT_FALSE(cache()->StoreLowEnergyBond(dev->identifier(), data)); - EXPECT_FALSE(dev->le()->bonded()); - EXPECT_TRUE(dev->temporary()); -} - -// StoreLowEnergyBond fails if the new identity is the address of a "different" -// (another device record with a distinct ID) BR/EDR device. -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, - StoreLowEnergyBondWithNewIdentityMatchingExistingBrEdrDevice) { - ASSERT_TRUE(NewDevice(kAddrBrEdr, true)); - ASSERT_TRUE(NewDevice(kAddrLeRandom, true)); - ASSERT_FALSE(device()->identity_known()); - - sm::PairingData data; - data.ltk = kLTK; - // new identity address is same as another device's BR/EDR identity - data.identity_address = kAddrLeAlias; - const auto old_address = device()->address(); - ASSERT_EQ(device(), cache()->FindDeviceByAddress(old_address)); - ASSERT_NE(device(), cache()->FindDeviceByAddress(*data.identity_address)); - EXPECT_FALSE(cache()->StoreLowEnergyBond(device()->identifier(), data)); - EXPECT_FALSE(device()->identity_known()); -} - -// StoreLowEnergyBond succeeds if it contains an identity address that already -// matches the target device. -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, - StoreLowEnergyBondWithExistingMatchingIdentity) { - sm::PairingData data; - data.ltk = kLTK; - data.identity_address = device()->address(); - EXPECT_TRUE(cache()->StoreLowEnergyBond(device()->identifier(), data)); - EXPECT_TRUE(device()->le()->bonded()); - EXPECT_EQ(device(), cache()->FindDeviceByAddress(*data.identity_address)); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, - StoreLowEnergyBondWithNewIdentity) { - ASSERT_TRUE(NewDevice(kAddrLeRandom, true)); - ASSERT_FALSE(device()->identity_known()); - - sm::PairingData data; - data.ltk = kLTK; - data.identity_address = kAddrLeRandom2; // assign a new identity address - const auto old_address = device()->address(); - ASSERT_EQ(device(), cache()->FindDeviceByAddress(old_address)); - ASSERT_EQ(nullptr, cache()->FindDeviceByAddress(*data.identity_address)); - - EXPECT_TRUE(cache()->StoreLowEnergyBond(device()->identifier(), data)); - EXPECT_TRUE(device()->le()->bonded()); - - // Address should have been updated. - ASSERT_NE(*data.identity_address, old_address); - EXPECT_EQ(*data.identity_address, device()->address()); - EXPECT_TRUE(device()->identity_known()); - EXPECT_EQ(device(), cache()->FindDeviceByAddress(*data.identity_address)); - - // The old address should still map to |dev|. - ASSERT_EQ(device(), cache()->FindDeviceByAddress(old_address)); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, - StoreLowEnergyBondWithIrkIsAddedToResolvingList) { - ASSERT_TRUE(NewDevice(kAddrLeRandom, true)); - ASSERT_FALSE(device()->identity_known()); - - sm::PairingData data; - data.ltk = kLTK; - data.identity_address = kAddrLeRandom; - data.irk = sm::Key(sm::SecurityProperties(), common::RandomUInt128()); - - EXPECT_TRUE(cache()->StoreLowEnergyBond(device()->identifier(), data)); - ASSERT_TRUE(device()->le()->bonded()); - ASSERT_TRUE(device()->identity_known()); - - // Looking up the device by RPA generated using the IRK should return the same - // device. - DeviceAddress rpa = sm::util::GenerateRpa(data.irk->value()); - EXPECT_EQ(device(), cache()->FindDeviceByAddress(rpa)); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, - StoreBrEdrBondWithUnknownAddress) { - ASSERT_EQ(nullptr, cache()->FindDeviceByAddress(kAddrBrEdr)); - EXPECT_FALSE(cache()->StoreBrEdrBond(kAddrBrEdr, kBrEdrKey)); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, StoreBrEdrBond) { - ASSERT_TRUE(NewDevice(kAddrBrEdr, true)); - ASSERT_EQ(device(), cache()->FindDeviceByAddress(kAddrBrEdr)); - ASSERT_TRUE(device()->temporary()); - ASSERT_FALSE(device()->bonded()); - ASSERT_TRUE(device()->bredr()); - ASSERT_FALSE(device()->bredr()->bonded()); - - EXPECT_TRUE(cache()->StoreBrEdrBond(kAddrBrEdr, kBrEdrKey)); - - EXPECT_FALSE(device()->temporary()); - EXPECT_TRUE(device()->bonded()); - EXPECT_TRUE(device()->bredr()->bonded()); - EXPECT_TRUE(device()->bredr()->link_key()); - EXPECT_EQ(kBrEdrKey, *device()->bredr()->link_key()); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, StoreBondsForBothTech) { - ASSERT_TRUE(NewDevice(kAddrBrEdr, true)); - ASSERT_EQ(device(), cache()->FindDeviceByAddress(kAddrBrEdr)); - ASSERT_TRUE(device()->temporary()); - ASSERT_FALSE(device()->bonded()); - - device()->MutLe().SetAdvertisingData(kTestRSSI, kAdvData); - ASSERT_EQ(TechnologyType::kDualMode, device()->technology()); - - // Without Secure Connections cross-transport key generation, bonding on one - // technology does not bond on the other. - ASSERT_FALSE(kBrEdrKey.security().secure_connections()); - EXPECT_TRUE(cache()->StoreBrEdrBond(kAddrBrEdr, kBrEdrKey)); - EXPECT_TRUE(device()->bonded()); - EXPECT_FALSE(device()->le()->bonded()); - - sm::PairingData data; - data.ltk = kLTK; - EXPECT_TRUE(cache()->StoreLowEnergyBond(device()->identifier(), data)); - - EXPECT_FALSE(device()->temporary()); - EXPECT_TRUE(device()->bonded()); - EXPECT_TRUE(device()->bredr()->bonded()); - EXPECT_TRUE(device()->le()->bonded()); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, ForgetUnknownPeer) { - const DeviceId id(0x9999); - ASSERT_FALSE(cache()->FindDeviceById(id)); - EXPECT_FALSE(cache()->ForgetPeer(id)); - EXPECT_EQ(0, updated_callback_count()); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, ForgetBrEdrDevice) { - ASSERT_TRUE(NewDevice(kAddrBrEdr, true)); - ASSERT_TRUE(cache()->StoreBrEdrBond(kAddrBrEdr, kBrEdrKey)); - ASSERT_TRUE(device()->bonded()); - ASSERT_FALSE(device()->temporary()); - ASSERT_EQ(3, updated_callback_count()); - - const DeviceId id = device()->identifier(); - EXPECT_TRUE(cache()->ForgetPeer(id)); - ASSERT_TRUE(cache()->FindDeviceById(id)); - EXPECT_FALSE(device()->bonded()); - EXPECT_TRUE(device()->temporary()); - EXPECT_EQ(4, updated_callback_count()); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, - ForgetLowEnergyPeerWithPublicAddress) { - sm::PairingData data; - data.ltk = kLTK; - ASSERT_TRUE(cache()->StoreLowEnergyBond(device()->identifier(), data)); - ASSERT_EQ(DeviceAddress::Type::kLEPublic, device()->address().type()); - ASSERT_TRUE(device()->bonded()); - ASSERT_FALSE(device()->temporary()); - ASSERT_EQ(2, updated_callback_count()); - - const DeviceId id = device()->identifier(); - EXPECT_TRUE(cache()->ForgetPeer(id)); - ASSERT_TRUE(cache()->FindDeviceById(id)); - EXPECT_FALSE(device()->bonded()); - EXPECT_TRUE(device()->temporary()); - EXPECT_EQ(3, updated_callback_count()); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, ForgetLowEnergyPeerWithIrk) { - ASSERT_TRUE(NewDevice(kAddrLeRandom, true)); - - sm::PairingData data; - data.ltk = kLTK; - data.identity_address = kAddrLeAlias; - data.irk = sm::Key(sm::SecurityProperties(), common::RandomUInt128()); - DeviceAddress rpa = sm::util::GenerateRpa(data.irk->value()); - - ASSERT_TRUE(cache()->StoreLowEnergyBond(device()->identifier(), data)); - ASSERT_TRUE(device()->bonded()); - ASSERT_FALSE(device()->temporary()); - ASSERT_TRUE(device()->identity_known()); - ASSERT_EQ(device(), cache()->FindDeviceByAddress(rpa)); - ASSERT_EQ(kAddrLeAlias, device()->address()); - EXPECT_EQ(3, updated_callback_count()); - - const DeviceId id = device()->identifier(); - EXPECT_TRUE(cache()->ForgetPeer(id)); - ASSERT_TRUE(cache()->FindDeviceById(id)); - EXPECT_FALSE(device()->bonded()); - EXPECT_TRUE(device()->temporary()); - EXPECT_FALSE(device()->identity_known()); - EXPECT_FALSE(cache()->FindDeviceByAddress(rpa)); - - // Don't expect the original random address to be restored. - EXPECT_EQ(kAddrLeAlias, device()->address()); - EXPECT_EQ(4, updated_callback_count()); - - RunLoopFor(kCacheTimeout); - EXPECT_FALSE(cache()->FindDeviceById(id)); -} - -// Test that a forgotten LE device using address privacy eventually expires out -// of the cache. -TEST_F(GAP_RemoteDeviceCacheTest_BondingTest, - RemoveForgetedLePrivacyPeerAfterDisconnectionThenExpiry) { - ASSERT_TRUE(NewDevice(kAddrLeRandom, true)); - - sm::PairingData data; - data.ltk = kLTK; - data.identity_address = kAddrLeAlias; - data.irk = sm::Key(sm::SecurityProperties(), common::RandomUInt128()); - - ASSERT_TRUE(cache()->StoreLowEnergyBond(device()->identifier(), data)); - device()->MutLe().SetConnectionState( - RemoteDevice::ConnectionState::kConnected); - ASSERT_TRUE(device()->bonded()); - ASSERT_FALSE(device()->temporary()); - - const DeviceId id = device()->identifier(); - EXPECT_TRUE(cache()->ForgetPeer(id)); - ASSERT_TRUE(cache()->FindDeviceById(id)); - EXPECT_TRUE(device()->temporary()); - - RunLoopFor(kCacheTimeout); - ASSERT_TRUE(cache()->FindDeviceById(id)); - - device()->MutLe().SetConnectionState( - RemoteDevice::ConnectionState::kNotConnected); - ASSERT_TRUE(cache()->FindDeviceById(id)); - EXPECT_TRUE(device()->temporary()); - - RunLoopFor(kCacheTimeout); - EXPECT_FALSE(cache()->FindDeviceById(id)); -} - -// Fixture parameterized by device address -class DualModeBondingTest - : public GAP_RemoteDeviceCacheTest_BondingTest, - public ::testing::WithParamInterface<DeviceAddress> {}; - -TEST_P(DualModeBondingTest, AddBondedDeviceSuccess) { - DeviceId kId(5); - sm::PairingData data; - data.ltk = kLTK; - - const DeviceAddress& address = GetParam(); - EXPECT_TRUE(cache()->AddBondedDevice(kId, address, data, kBrEdrKey)); - auto* dev = cache()->FindDeviceById(kId); - ASSERT_TRUE(dev); - EXPECT_EQ(dev, cache()->FindDeviceByAddress(kAddrLeAlias)); - EXPECT_EQ(dev, cache()->FindDeviceByAddress(kAddrBrEdr)); - EXPECT_EQ(kId, dev->identifier()); - EXPECT_EQ(address, dev->address()); - EXPECT_TRUE(dev->identity_known()); - EXPECT_TRUE(dev->bonded()); - ASSERT_TRUE(dev->le()); - EXPECT_TRUE(dev->le()->bonded()); - ASSERT_TRUE(dev->le()->bond_data()); - EXPECT_EQ(data, *dev->le()->bond_data()); - ASSERT_TRUE(dev->bredr()); - EXPECT_TRUE(dev->bredr()->bonded()); - ASSERT_TRUE(dev->bredr()->link_key()); - EXPECT_EQ(kBrEdrKey, *dev->bredr()->link_key()); - EXPECT_EQ(TechnologyType::kDualMode, dev->technology()); - - // The "new bond" callback should not be called when restoring a previously - // bonded device. - EXPECT_FALSE(bonded_callback_called()); -} - -TEST_P(DualModeBondingTest, ForgetPeer) { - DeviceId kId(5); - sm::PairingData data; - data.ltk = kLTK; - - const DeviceAddress& address = GetParam(); - EXPECT_TRUE(cache()->AddBondedDevice(kId, address, data, kBrEdrKey)); - auto* dev = cache()->FindDeviceById(kId); - ASSERT_TRUE(dev); - ASSERT_TRUE(dev->bonded()); - EXPECT_EQ(5, updated_callback_count()); - - // Forgetting a dual-mode peer should only invoke the update callback once. - EXPECT_TRUE(cache()->ForgetPeer(kId)); - EXPECT_FALSE(dev->bonded()); - EXPECT_EQ(6, updated_callback_count()); -} - -// Test dual-mode character of device using the same address of both types. -INSTANTIATE_TEST_SUITE_P(GAP_RemoteDeviceCacheTest, DualModeBondingTest, - ::testing::Values(kAddrBrEdr, kAddrLeAlias)); - -template <const DeviceAddress* DevAddr> -class GAP_RemoteDeviceCacheTest_UpdateCallbackTest - : public GAP_RemoteDeviceCacheTest { - public: - void SetUp() { - was_called_ = false; - ASSERT_TRUE(NewDevice(*DevAddr, true)); - cache()->set_device_updated_callback( - [this](const auto&) { was_called_ = true; }); - ir_.bd_addr = device()->address().value(); - irr_.bd_addr = device()->address().value(); - eirep_.bd_addr = device()->address().value(); - eir_data().SetToZeros(); - EXPECT_FALSE(was_called_); - } - - protected: - hci::InquiryResult& ir() { return ir_; } - hci::InquiryResultRSSI& irr() { return irr_; } - hci::ExtendedInquiryResultEventParams& eirep() { return eirep_; } - - MutableBufferView eir_data() { - return MutableBufferView(&eirep_.extended_inquiry_response, - sizeof(eirep_.extended_inquiry_response)); - } - bool was_called() const { return was_called_; } - void ClearWasCalled() { was_called_ = false; } - - private: - bool was_called_; - hci::InquiryResult ir_; - hci::InquiryResultRSSI irr_; - hci::ExtendedInquiryResultEventParams eirep_; -}; - -using GAP_RemoteDeviceCacheTest_BrEdrUpdateCallbackTest = - GAP_RemoteDeviceCacheTest_UpdateCallbackTest<&kAddrBrEdr>; -using GAP_RemoteDeviceCacheTest_LowEnergyUpdateCallbackTest = - GAP_RemoteDeviceCacheTest_UpdateCallbackTest<&kAddrLeAlias>; - -TEST_F(GAP_RemoteDeviceCacheTest_LowEnergyUpdateCallbackTest, - ChangingLEConnectionStateTriggersUpdateCallback) { - device()->MutLe().SetConnectionState( - RemoteDevice::ConnectionState::kConnected); - EXPECT_TRUE(was_called()); -} - -TEST_F(GAP_RemoteDeviceCacheTest_LowEnergyUpdateCallbackTest, - SetAdvertisingDataTriggersUpdateCallbackOnNameSet) { - device()->MutLe().SetAdvertisingData(kTestRSSI, kAdvData); - EXPECT_TRUE(was_called()); - ASSERT_TRUE(device()->name()); - EXPECT_EQ("Test", *device()->name()); -} - -TEST_F(GAP_RemoteDeviceCacheTest_LowEnergyUpdateCallbackTest, - SetLowEnergyAdvertisingDataUpdateCallbackProvidesUpdatedDevice) { - ASSERT_NE(device()->rssi(), kTestRSSI); - cache()->set_device_updated_callback([&](const auto& updated_dev) { - ASSERT_TRUE(updated_dev.le()); - EXPECT_TRUE(common::ContainersEqual(kAdvData, - updated_dev.le()->advertising_data())); - EXPECT_EQ(updated_dev.rssi(), kTestRSSI); - }); - device()->MutLe().SetAdvertisingData(kTestRSSI, kAdvData); -} - -TEST_F(GAP_RemoteDeviceCacheTest_LowEnergyUpdateCallbackTest, - SetAdvertisingDataDoesNotTriggerUpdateCallbackOnSameName) { - device()->MutLe().SetAdvertisingData(kTestRSSI, kAdvData); - ASSERT_TRUE(was_called()); - - ClearWasCalled(); - device()->MutLe().SetAdvertisingData(kTestRSSI, kAdvData); - EXPECT_FALSE(was_called()); -} - -TEST_F(GAP_RemoteDeviceCacheTest_LowEnergyUpdateCallbackTest, - SetLowEnergyConnectionParamsDoesNotTriggerUpdateCallback) { - device()->MutLe().SetConnectionParameters({}); - EXPECT_FALSE(was_called()); -} - -TEST_F(GAP_RemoteDeviceCacheTest_LowEnergyUpdateCallbackTest, - SetLowEnergyPreferredConnectionParamsDoesNotTriggerUpdateCallback) { - device()->MutLe().SetPreferredConnectionParameters({}); - EXPECT_FALSE(was_called()); -} - -TEST_F(GAP_RemoteDeviceCacheTest_LowEnergyUpdateCallbackTest, - BecomingDualModeTriggersUpdateCallBack) { - EXPECT_EQ(TechnologyType::kLowEnergy, device()->technology()); - - size_t call_count = 0; - cache()->set_device_updated_callback([&](const auto&) { ++call_count; }); - device()->MutBrEdr(); - EXPECT_EQ(TechnologyType::kDualMode, device()->technology()); - EXPECT_EQ(call_count, 1U); - - // Calling MutBrEdr again on doesn't trigger additional callbacks. - device()->MutBrEdr(); - EXPECT_EQ(call_count, 1U); - device()->MutBrEdr().SetInquiryData(eirep()); - EXPECT_EQ(call_count, 2U); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BrEdrUpdateCallbackTest, - ChangingBrEdrConnectionStateTriggersUpdateCallback) { - device()->MutBrEdr().SetConnectionState( - RemoteDevice::ConnectionState::kConnected); - EXPECT_TRUE(was_called()); -} - -TEST_F( - GAP_RemoteDeviceCacheTest_BrEdrUpdateCallbackTest, - SetBrEdrInquiryDataFromInquiryResultTriggersUpdateCallbackOnDeviceClassSet) { - ir().class_of_device = kTestDeviceClass; - device()->MutBrEdr().SetInquiryData(ir()); - EXPECT_TRUE(was_called()); -} - -TEST_F( - GAP_RemoteDeviceCacheTest_BrEdrUpdateCallbackTest, - SetBrEdrInquiryDataFromInquiryResultUpdateCallbackProvidesUpdatedDevice) { - ir().class_of_device = kTestDeviceClass; - cache()->set_device_updated_callback([](const auto& updated_dev) { - ASSERT_TRUE(updated_dev.bredr()); - ASSERT_TRUE(updated_dev.bredr()->device_class()); - EXPECT_EQ(common::DeviceClass::MajorClass(0x02), - updated_dev.bredr()->device_class()->major_class()); - }); - device()->MutBrEdr().SetInquiryData(ir()); -} - -TEST_F( - GAP_RemoteDeviceCacheTest_BrEdrUpdateCallbackTest, - SetBrEdrInquiryDataFromInquiryResultDoesNotTriggerUpdateCallbackOnSameDeviceClass) { - ir().class_of_device = kTestDeviceClass; - device()->MutBrEdr().SetInquiryData(ir()); - ASSERT_TRUE(was_called()); - - ClearWasCalled(); - device()->MutBrEdr().SetInquiryData(ir()); - EXPECT_FALSE(was_called()); -} - -TEST_F( - GAP_RemoteDeviceCacheTest_BrEdrUpdateCallbackTest, - SetBrEdrInquiryDataFromInquiryResultRSSITriggersUpdateCallbackOnDeviceClassSet) { - irr().class_of_device = kTestDeviceClass; - device()->MutBrEdr().SetInquiryData(irr()); - EXPECT_TRUE(was_called()); -} - -TEST_F( - GAP_RemoteDeviceCacheTest_BrEdrUpdateCallbackTest, - SetBrEdrInquiryDataFromInquiryResultRSSIUpdateCallbackProvidesUpdatedDevice) { - irr().class_of_device = kTestDeviceClass; - cache()->set_device_updated_callback([](const auto& updated_dev) { - ASSERT_TRUE(updated_dev.bredr()->device_class()); - EXPECT_EQ(common::DeviceClass::MajorClass(0x02), - updated_dev.bredr()->device_class()->major_class()); - }); - device()->MutBrEdr().SetInquiryData(irr()); -} - -TEST_F( - GAP_RemoteDeviceCacheTest_BrEdrUpdateCallbackTest, - SetBrEdrInquiryDataFromInquiryResultRSSIDoesNotTriggerUpdateCallbackOnSameDeviceClass) { - irr().class_of_device = kTestDeviceClass; - device()->MutBrEdr().SetInquiryData(irr()); - ASSERT_TRUE(was_called()); - - ClearWasCalled(); - device()->MutBrEdr().SetInquiryData(irr()); - EXPECT_FALSE(was_called()); -} - -TEST_F( - GAP_RemoteDeviceCacheTest_BrEdrUpdateCallbackTest, - SetBrEdrInquiryDataFromInquiryResultRSSIDoesNotTriggerUpdateCallbackOnRSSI) { - irr().rssi = 1; - device()->MutBrEdr().SetInquiryData(irr()); - ASSERT_TRUE(was_called()); // Callback due to |class_of_device|. - - ClearWasCalled(); - irr().rssi = 20; - device()->MutBrEdr().SetInquiryData(irr()); - EXPECT_FALSE(was_called()); -} - -TEST_F( - GAP_RemoteDeviceCacheTest_BrEdrUpdateCallbackTest, - SetBrEdrInquiryDataFromExtendedInquiryResultEventParamsTriggersUpdateCallbackOnDeviceClassSet) { - eirep().class_of_device = kTestDeviceClass; - device()->MutBrEdr().SetInquiryData(eirep()); - EXPECT_TRUE(was_called()); -} - -TEST_F( - GAP_RemoteDeviceCacheTest_BrEdrUpdateCallbackTest, - SetBrEdrInquiryDataFromExtendedInquiryResultEventParamsTriggersUpdateCallbackOnNameSet) { - device()->MutBrEdr().SetInquiryData(eirep()); - ASSERT_TRUE(was_called()); // Callback due to |class_of_device|. - - ClearWasCalled(); - eir_data().Write(kEirData); - device()->MutBrEdr().SetInquiryData(eirep()); - EXPECT_TRUE(was_called()); -} - -TEST_F( - GAP_RemoteDeviceCacheTest_BrEdrUpdateCallbackTest, - SetBrEdrInquiryDataFromExtendedInquiryResultEventParamsUpdateCallbackProvidesUpdatedDevice) { - eirep().clock_offset = htole16(1); - eirep().page_scan_repetition_mode = hci::PageScanRepetitionMode::kR1; - eirep().rssi = kTestRSSI; - eirep().class_of_device = kTestDeviceClass; - eir_data().Write(kEirData); - ASSERT_FALSE(device()->name().has_value()); - ASSERT_EQ(device()->rssi(), hci::kRSSIInvalid); - cache()->set_device_updated_callback([](const auto& updated_dev) { - const auto& data = updated_dev.bredr(); - ASSERT_TRUE(data); - ASSERT_TRUE(data->clock_offset().has_value()); - ASSERT_TRUE(data->page_scan_repetition_mode().has_value()); - ASSERT_TRUE(data->device_class().has_value()); - ASSERT_TRUE(updated_dev.name().has_value()); - - EXPECT_EQ(*data->clock_offset(), 0x8001); - EXPECT_EQ(*data->page_scan_repetition_mode(), - hci::PageScanRepetitionMode::kR1); - EXPECT_EQ(common::DeviceClass::MajorClass(0x02), - updated_dev.bredr()->device_class()->major_class()); - EXPECT_EQ(updated_dev.rssi(), kTestRSSI); - EXPECT_EQ(*updated_dev.name(), "Test"); - }); - device()->MutBrEdr().SetInquiryData(eirep()); -} - -TEST_F( - GAP_RemoteDeviceCacheTest_BrEdrUpdateCallbackTest, - SetBrEdrInquiryDataFromExtendedInquiryResultEventParamsGeneratesExactlyOneUpdateCallbackRegardlessOfNumberOfFieldsChanged) { - eirep().clock_offset = htole16(1); - eirep().page_scan_repetition_mode = hci::PageScanRepetitionMode::kR1; - eirep().rssi = kTestRSSI; - eirep().class_of_device = kTestDeviceClass; - eir_data().Write(kEirData); - - size_t call_count = 0; - cache()->set_device_updated_callback([&](const auto&) { ++call_count; }); - device()->MutBrEdr().SetInquiryData(eirep()); - EXPECT_EQ(call_count, 1U); -} - -TEST_F( - GAP_RemoteDeviceCacheTest_BrEdrUpdateCallbackTest, - SetBrEdrInquiryDataFromExtendedInquiryResultEventParamsDoesNotTriggerUpdateCallbackOnSameDeviceClass) { - eirep().class_of_device = kTestDeviceClass; - device()->MutBrEdr().SetInquiryData(eirep()); - ASSERT_TRUE(was_called()); - - ClearWasCalled(); - device()->MutBrEdr().SetInquiryData(eirep()); - EXPECT_FALSE(was_called()); -} - -TEST_F( - GAP_RemoteDeviceCacheTest_BrEdrUpdateCallbackTest, - SetBrEdrInquiryDataFromExtendedInquiryResultEventParamsDoesNotTriggerUpdateCallbackOnSameName) { - eir_data().Write(kEirData); - device()->MutBrEdr().SetInquiryData(eirep()); - ASSERT_TRUE(was_called()); - - ClearWasCalled(); - device()->MutBrEdr().SetInquiryData(eirep()); - EXPECT_FALSE(was_called()); -} - -TEST_F( - GAP_RemoteDeviceCacheTest_BrEdrUpdateCallbackTest, - SetBrEdrInquiryDataFromExtendedInquiryResultEventParamsDoesNotTriggerUpdateCallbackOnRSSI) { - eirep().rssi = 1; - device()->MutBrEdr().SetInquiryData(eirep()); - ASSERT_TRUE(was_called()); // Callback due to |class_of_device|. - - ClearWasCalled(); - eirep().rssi = 20; - device()->MutBrEdr().SetInquiryData(eirep()); - EXPECT_FALSE(was_called()); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BrEdrUpdateCallbackTest, - SetNameTriggersUpdateCallback) { - device()->SetName("nombre"); - EXPECT_TRUE(was_called()); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BrEdrUpdateCallbackTest, - SetNameDoesNotTriggerUpdateCallbackOnSameName) { - device()->SetName("nombre"); - ASSERT_TRUE(was_called()); - - bool was_called_again = false; - cache()->set_device_updated_callback( - [&](const auto&) { was_called_again = true; }); - device()->SetName("nombre"); - EXPECT_FALSE(was_called_again); -} - -TEST_F(GAP_RemoteDeviceCacheTest_BrEdrUpdateCallbackTest, - BecomingDualModeTriggersUpdateCallBack) { - EXPECT_EQ(TechnologyType::kClassic, device()->technology()); - - size_t call_count = 0; - cache()->set_device_updated_callback([&](const auto&) { ++call_count; }); - device()->MutLe(); - EXPECT_EQ(TechnologyType::kDualMode, device()->technology()); - EXPECT_EQ(call_count, 1U); - - // Calling MutLe again doesn't trigger additional callbacks. - device()->MutLe(); - EXPECT_EQ(call_count, 1U); - device()->MutLe().SetAdvertisingData(kTestRSSI, kAdvData); - EXPECT_EQ(call_count, 2U); -} - -class GAP_RemoteDeviceCacheExpirationTest : public ::gtest::TestLoopFixture { - public: - void SetUp() { - TestLoopFixture::SetUp(); - cache_.set_device_removed_callback( - [this](DeviceId) { devices_removed_++; }); - auto* dev = cache_.NewDevice(kAddrLeAlias, true /*connectable*/); - ASSERT_TRUE(dev); - ASSERT_TRUE(dev->temporary()); - device_addr_ = dev->address(); - device_addr_alias_ = kAddrBrEdr; - device_id_ = dev->identifier(); - devices_removed_ = 0; - } - - void TearDown() { - cache_.set_device_removed_callback(nullptr); - RunLoopUntilIdle(); - TestLoopFixture::TearDown(); - } - - RemoteDevice* GetDefaultDevice() { return cache_.FindDeviceById(device_id_); } - RemoteDevice* GetDeviceById(DeviceId id) { return cache_.FindDeviceById(id); } - bool IsDefaultDeviceAddressInCache() const { - return cache_.FindDeviceByAddress(device_addr_); - } - bool IsOtherTransportAddressInCache() const { - return cache_.FindDeviceByAddress(device_addr_alias_); - } - bool IsDefaultDevicePresent() { return GetDefaultDevice(); } - RemoteDevice* NewDevice(const common::DeviceAddress& address, - bool connectable) { - return cache_.NewDevice(address, connectable); - } - int devices_removed() const { return devices_removed_; } - - private: - RemoteDeviceCache cache_; - common::DeviceAddress device_addr_; - common::DeviceAddress device_addr_alias_; - DeviceId device_id_; - int devices_removed_; -}; - -TEST_F(GAP_RemoteDeviceCacheExpirationTest, - TemporaryDiesSixtySecondsAfterBirth) { - RunLoopFor(kCacheTimeout); - EXPECT_FALSE(IsDefaultDevicePresent()); - EXPECT_EQ(1, devices_removed()); -} - -TEST_F(GAP_RemoteDeviceCacheExpirationTest, - TemporaryLivesForSixtySecondsAfterBirth) { - RunLoopFor(kCacheTimeout - zx::msec(1)); - EXPECT_TRUE(IsDefaultDevicePresent()); - EXPECT_EQ(0, devices_removed()); -} - -TEST_F(GAP_RemoteDeviceCacheExpirationTest, - TemporaryLivesForSixtySecondsSinceLastSeen) { - RunLoopFor(kCacheTimeout - zx::msec(1)); - ASSERT_TRUE(IsDefaultDevicePresent()); - - // Tickle device, and verify it sticks around for another cache timeout. - GetDefaultDevice()->SetName("nombre"); - RunLoopFor(kCacheTimeout - zx::msec(1)); - EXPECT_TRUE(IsDefaultDevicePresent()); -} - -TEST_F(GAP_RemoteDeviceCacheExpirationTest, - TemporaryDiesSixtySecondsAfterLastSeen) { - RunLoopFor(kCacheTimeout - zx::msec(1)); - ASSERT_TRUE(IsDefaultDevicePresent()); - - // Tickle device, and verify it expires after cache timeout. - GetDefaultDevice()->SetName("nombre"); - RunLoopFor(kCacheTimeout); - EXPECT_FALSE(IsDefaultDevicePresent()); -} - -TEST_F(GAP_RemoteDeviceCacheExpirationTest, - CanMakeNonTemporaryJustBeforeSixtySeconds) { - // At last possible moment, make device non-temporary, - RunLoopFor(kCacheTimeout - zx::msec(1)); - ASSERT_TRUE(IsDefaultDevicePresent()); - GetDefaultDevice()->MutLe().SetConnectionState( - RemoteDevice::ConnectionState::kConnected); - ASSERT_FALSE(GetDefaultDevice()->temporary()); - - // Verify that the device survives. - RunLoopFor(kCacheTimeout * 10); - EXPECT_TRUE(IsDefaultDevicePresent()); -} - -TEST_F(GAP_RemoteDeviceCacheExpirationTest, - LEConnectedDeviceLivesMuchMoreThanSixtySeconds) { - ASSERT_TRUE(IsDefaultDevicePresent()); - GetDefaultDevice()->MutLe().SetConnectionState( - RemoteDevice::ConnectionState::kConnected); - RunLoopFor(kCacheTimeout * 10); - ASSERT_TRUE(IsDefaultDevicePresent()); - EXPECT_FALSE(GetDefaultDevice()->temporary()); -} - -TEST_F(GAP_RemoteDeviceCacheExpirationTest, - BREDRConnectedDeviceLivesMuchMoreThanSixtySeconds) { - ASSERT_TRUE(IsDefaultDevicePresent()); - GetDefaultDevice()->MutBrEdr().SetConnectionState( - RemoteDevice::ConnectionState::kConnected); - RunLoopFor(kCacheTimeout * 10); - ASSERT_TRUE(IsDefaultDevicePresent()); - EXPECT_FALSE(GetDefaultDevice()->temporary()); -} - -TEST_F(GAP_RemoteDeviceCacheExpirationTest, - LeDeviceBecomesNonTemporaryWhenConnecting) { - ASSERT_TRUE(IsDefaultDevicePresent()); - ASSERT_EQ(kAddrLeAlias, GetDefaultDevice()->address()); - ASSERT_TRUE(GetDefaultDevice()->temporary()); - - GetDefaultDevice()->MutLe().SetConnectionState( - RemoteDevice::ConnectionState::kInitializing); - EXPECT_FALSE(GetDefaultDevice()->temporary()); - - RunLoopFor(kCacheTimeout); - ASSERT_TRUE(IsDefaultDevicePresent()); -} - -TEST_F(GAP_RemoteDeviceCacheExpirationTest, - LEPublicDeviceRemainsNonTemporaryOnDisconnect) { - ASSERT_TRUE(IsDefaultDevicePresent()); - ASSERT_EQ(kAddrLeAlias, GetDefaultDevice()->address()); - GetDefaultDevice()->MutLe().SetConnectionState( - RemoteDevice::ConnectionState::kConnected); - ASSERT_FALSE(GetDefaultDevice()->temporary()); - - RunLoopFor(zx::sec(61)); - ASSERT_TRUE(IsDefaultDevicePresent()); - ASSERT_TRUE(GetDefaultDevice()->identity_known()); - - GetDefaultDevice()->MutLe().SetConnectionState( - RemoteDevice::ConnectionState::kNotConnected); - EXPECT_FALSE(GetDefaultDevice()->temporary()); - - RunLoopFor(kCacheTimeout); - EXPECT_TRUE(IsDefaultDevicePresent()); -} - -TEST_F(GAP_RemoteDeviceCacheExpirationTest, - LERandomDeviceBecomesTemporaryOnDisconnect) { - // Create our RemoteDevice, and get it into the kConnected state. - DeviceId custom_device_id; - { - auto* custom_device = NewDevice(kAddrLeRandom, true); - ASSERT_TRUE(custom_device); - ASSERT_TRUE(custom_device->temporary()); - ASSERT_FALSE(custom_device->identity_known()); - custom_device_id = custom_device->identifier(); - - custom_device->MutLe().SetConnectionState( - RemoteDevice::ConnectionState::kConnected); - ASSERT_FALSE(custom_device->temporary()); - ASSERT_FALSE(custom_device->identity_known()); - } - - // Verify that the connected device does not expire out of the cache. - // Then disconnect the device, in preparation for the next stage of our test. - { - EXPECT_EQ(0, devices_removed()); - RunLoopFor(zx::sec(61)); - EXPECT_EQ(1, devices_removed()); // Default device timed out. - auto* custom_device = GetDeviceById(custom_device_id); - ASSERT_TRUE(custom_device); - ASSERT_FALSE(custom_device->identity_known()); - - custom_device->MutLe().SetConnectionState( - RemoteDevice::ConnectionState::kNotConnected); - EXPECT_TRUE(custom_device->temporary()); - EXPECT_FALSE(custom_device->identity_known()); - } - - // Verify that the disconnected device expires out of the cache. - RunLoopFor(zx::sec(61)); - EXPECT_FALSE(GetDeviceById(custom_device_id)); - EXPECT_EQ(2, devices_removed()); -} - -TEST_F(GAP_RemoteDeviceCacheExpirationTest, - BrEdrDeviceRemainsNonTemporaryOnDisconnect) { - // Create our RemoteDevice, and get it into the kConnected state. - DeviceId custom_device_id; - { - auto* custom_device = NewDevice(kAddrLePublic, true); - ASSERT_TRUE(custom_device); - custom_device->MutLe().SetConnectionState( - RemoteDevice::ConnectionState::kConnected); - custom_device_id = custom_device->identifier(); - } - - // Verify that the connected device does not expire out of the cache. - // Then disconnect the device, in preparation for the next stage of our test. - { - EXPECT_EQ(0, devices_removed()); - RunLoopFor(kCacheTimeout * 10); - EXPECT_EQ(1, devices_removed()); // Default device timed out. - auto* custom_device = GetDeviceById(custom_device_id); - ASSERT_TRUE(custom_device); - ASSERT_TRUE(custom_device->identity_known()); - EXPECT_FALSE(custom_device->temporary()); - - custom_device->MutLe().SetConnectionState( - RemoteDevice::ConnectionState::kNotConnected); - ASSERT_TRUE(GetDeviceById(custom_device_id)); - EXPECT_FALSE(custom_device->temporary()); - } - - // Verify that the disconnected device does _not_ expire out of the cache. - // We expect the device to remain, because BrEdr devices are non-temporary - // even when disconnected. - RunLoopFor(kCacheTimeout); - EXPECT_TRUE(GetDeviceById(custom_device_id)); - EXPECT_EQ(1, devices_removed()); -} - -TEST_F(GAP_RemoteDeviceCacheExpirationTest, ExpirationUpdatesAddressMap) { - ASSERT_TRUE(IsDefaultDeviceAddressInCache()); - ASSERT_TRUE(IsOtherTransportAddressInCache()); - RunLoopFor(kCacheTimeout); - EXPECT_FALSE(IsDefaultDeviceAddressInCache()); - EXPECT_FALSE(IsOtherTransportAddressInCache()); -} - -TEST_F(GAP_RemoteDeviceCacheExpirationTest, - SetAdvertisingDataUpdatesExpiration) { - RunLoopFor(kCacheTimeout - zx::msec(1)); - ASSERT_TRUE(IsDefaultDevicePresent()); - GetDefaultDevice()->MutLe().SetAdvertisingData(kTestRSSI, - StaticByteBuffer<1>{}); - RunLoopFor(zx::msec(1)); - EXPECT_TRUE(IsDefaultDevicePresent()); -} - -TEST_F(GAP_RemoteDeviceCacheExpirationTest, - SetBrEdrInquiryDataFromInquiryResultUpdatesExpiration) { - hci::InquiryResult ir; - ASSERT_TRUE(IsDefaultDevicePresent()); - ir.bd_addr = GetDefaultDevice()->address().value(); - - RunLoopFor(kCacheTimeout - zx::msec(1)); - ASSERT_TRUE(IsDefaultDevicePresent()); - GetDefaultDevice()->MutBrEdr().SetInquiryData(ir); - - RunLoopFor(zx::msec(1)); - EXPECT_TRUE(IsDefaultDevicePresent()); -} - -TEST_F(GAP_RemoteDeviceCacheExpirationTest, - SetBrEdrInquiryDataFromInquiryResultRSSIUpdatesExpiration) { - hci::InquiryResultRSSI irr; - ASSERT_TRUE(IsDefaultDevicePresent()); - irr.bd_addr = GetDefaultDevice()->address().value(); - - RunLoopFor(kCacheTimeout - zx::msec(1)); - ASSERT_TRUE(IsDefaultDevicePresent()); - GetDefaultDevice()->MutBrEdr().SetInquiryData(irr); - - RunLoopFor(zx::msec(1)); - EXPECT_TRUE(IsDefaultDevicePresent()); -} - -TEST_F( - GAP_RemoteDeviceCacheExpirationTest, - SetBrEdrInquiryDataFromExtendedInquiryResultEventParamsUpdatesExpiration) { - hci::ExtendedInquiryResultEventParams eirep; - ASSERT_TRUE(IsDefaultDevicePresent()); - eirep.bd_addr = GetDefaultDevice()->address().value(); - - RunLoopFor(kCacheTimeout - zx::msec(1)); - ASSERT_TRUE(IsDefaultDevicePresent()); - GetDefaultDevice()->MutBrEdr().SetInquiryData(eirep); - - RunLoopFor(zx::msec(1)); - EXPECT_TRUE(IsDefaultDevicePresent()); -} - -TEST_F(GAP_RemoteDeviceCacheExpirationTest, SetNameUpdatesExpiration) { - RunLoopFor(kCacheTimeout - zx::msec(1)); - ASSERT_TRUE(IsDefaultDevicePresent()); - GetDefaultDevice()->SetName({}); - RunLoopFor(zx::msec(1)); - EXPECT_TRUE(IsDefaultDevicePresent()); -} - -} // namespace -} // namespace gap -} // namespace bt diff --git a/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner.cc b/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner.cc index ab75529f2144c9baadafaa540b22f81c5b852b66..a8b1637c7cb378c6e5fef5404f7cb120d7d19010 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner.cc @@ -225,8 +225,8 @@ void LegacyLowEnergyScanner::StopScanInternal(bool stopped) { if (!stopped) { for (auto& result : pending_results_) { auto& pending = result.second; - NotifyDeviceFound(pending.result, - pending.data.view(0, pending.adv_data_len)); + NotifyPeerFound(pending.result, + pending.data.view(0, pending.adv_data_len)); } } @@ -315,7 +315,7 @@ void LegacyLowEnergyScanner::OnAdvertisingReportEvent( } if (!needs_scan_rsp) { - NotifyDeviceFound(result, BufferView(report->data, report->length_data)); + NotifyPeerFound(result, BufferView(report->data, report->length_data)); continue; } @@ -323,7 +323,7 @@ void LegacyLowEnergyScanner::OnAdvertisingReportEvent( auto& pending = iter->second; // We overwrite the pending result entry with the most recent report, even - // if one from this device was already pending. + // if one from this peer was already pending. pending.result = result; pending.adv_data_len = report->length_data; pending.data.Write(report->data, report->length_data); @@ -357,15 +357,14 @@ void LegacyLowEnergyScanner::HandleScanResponse( // Append the scan response to the pending advertising data. pending.data.Write(report.data, report.length_data, pending.adv_data_len); - NotifyDeviceFound( - pending.result, - pending.data.view(0, pending.adv_data_len + report.length_data)); + NotifyPeerFound(pending.result, pending.data.view(0, pending.adv_data_len + + report.length_data)); pending_results_.erase(iter); } -void LegacyLowEnergyScanner::NotifyDeviceFound( - const LowEnergyScanResult& result, const common::ByteBuffer& data) { - delegate()->OnDeviceFound(result, data); +void LegacyLowEnergyScanner::NotifyPeerFound(const LowEnergyScanResult& result, + const common::ByteBuffer& data) { + delegate()->OnPeerFound(result, data); } void LegacyLowEnergyScanner::OnScanPeriodComplete() { diff --git a/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner.h b/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner.h index cdf2025ff0ee721d645f727e4656d2de97caa7d1..7c23a5c28ec158835ac58ffadda62030345cd882 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner.h +++ b/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner.h @@ -24,7 +24,7 @@ class LocalAddressDelegate; // LegacyLowEnergyScanner implements the LowEnergyScanner interface for // controllers that do not support the 5.0 Extended Advertising feature. This -// uses the legacy HCI LE device scan commands and events: +// uses the legacy HCI LE scan commands and events: // - HCI_LE_Set_Scan_Parameters // - HCI_LE_Set_Scan_Enable // - HCI_LE_Advertising_Report event @@ -54,7 +54,7 @@ class LegacyLowEnergyScanner : public LowEnergyScanner { common::StaticByteBuffer<kMaxLEAdvertisingDataLength * 2> data; }; - // Called by StartScan() after the local device address has been obtained. + // Called by StartScan() after the local peer address has been obtained. void StartScanInternal(const common::DeviceAddress& local_address, bool active, uint16_t scan_interval, uint16_t scan_window, bool filter_duplicates, @@ -70,14 +70,14 @@ class LegacyLowEnergyScanner : public LowEnergyScanner { // Called when a Scan Response is received during an active scan. void HandleScanResponse(const LEAdvertisingReportData& report, int8_t rssi); - // Notifies observers of a device that was found. - void NotifyDeviceFound(const LowEnergyScanResult& result, - const common::ByteBuffer& data); + // Notifies observers of a peer that was found. + void NotifyPeerFound(const LowEnergyScanResult& result, + const common::ByteBuffer& data); // Called when the scan timeout task executes. void OnScanPeriodComplete(); - // Used to obtain the local device address type to use during scanning. + // Used to obtain the local peer address type to use during scanning. LocalAddressDelegate* local_addr_delegate_; // weak // Callback passed in to the most recently accepted call to StartScan(); diff --git a/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner_unittest.cc b/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner_unittest.cc index a5fe09126d725761c655cca2d522491f48dc3eb1..3398e1f6b5f6fb5e76bf95207e1c043f078002a5 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner_unittest.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/legacy_low_energy_scanner_unittest.cc @@ -71,10 +71,10 @@ class LegacyLowEnergyScannerTest : public TestingBase, TestingBase::TearDown(); } - using DeviceFoundCallback = fit::function<void(const LowEnergyScanResult&, - const common::ByteBuffer&)>; - void set_device_found_callback(DeviceFoundCallback cb) { - device_found_cb_ = std::move(cb); + using PeerFoundCallback = fit::function<void(const LowEnergyScanResult&, + const common::ByteBuffer&)>; + void set_peer_found_callback(PeerFoundCallback cb) { + peer_found_cb_ = std::move(cb); } using DirectedAdvCallback = fit::function<void(const LowEnergyScanResult&)>; @@ -91,10 +91,10 @@ class LegacyLowEnergyScannerTest : public TestingBase, } // LowEnergyScanner::Observer override: - void OnDeviceFound(const LowEnergyScanResult& result, - const common::ByteBuffer& data) override { - if (device_found_cb_) { - device_found_cb_(result, data); + void OnPeerFound(const LowEnergyScanResult& result, + const common::ByteBuffer& data) override { + if (peer_found_cb_) { + peer_found_cb_(result, data); } } @@ -105,7 +105,7 @@ class LegacyLowEnergyScannerTest : public TestingBase, } } - // Adds 6 fake devices using kAddress[0-5] above. + // Adds 6 fake peers using kAddress[0-5] above. void AddFakePeers() { // We use malformed data for testing purposes, as we don't care about // integrity here. @@ -114,8 +114,7 @@ class LegacyLowEnergyScannerTest : public TestingBase, auto empty_data = common::DynamicByteBuffer(); // Generates ADV_IND, scan response is reported in a single HCI event. - auto fake_peer = - std::make_unique<FakePeer>(kPublicAddress1, true, true); + auto fake_peer = std::make_unique<FakePeer>(kPublicAddress1, true, true); fake_peer->SetAdvertisingData(adv_data); fake_peer->SetScanResponse(true, scan_rsp); test_device()->AddPeer(std::move(fake_peer)); @@ -162,7 +161,7 @@ class LegacyLowEnergyScannerTest : public TestingBase, } private: - DeviceFoundCallback device_found_cb_; + PeerFoundCallback peer_found_cb_; DirectedAdvCallback directed_adv_cb_; FakeLocalAddressDelegate fake_address_delegate_; std::unique_ptr<LegacyLowEnergyScanner> scanner_; @@ -307,14 +306,14 @@ TEST_F(HCI_LegacyLowEnergyScannerTest, StopScanWhileInitiating) { } TEST_F(HCI_LegacyLowEnergyScannerTest, ActiveScanResults) { - // One of the 6 fake devices is scannable but never sends scan response - // packets. That device doesn't get reported until the end of the scan period. + // One of the 6 fake peers is scannable but never sends scan response + // packets. That peer doesn't get reported until the end of the scan period. constexpr size_t kExpectedResultCount = 5u; AddFakePeers(); std::map<DeviceAddress, std::pair<LowEnergyScanResult, std::string>> results; - set_device_found_callback([&, this](const auto& result, const auto& data) { + set_peer_found_callback([&, this](const auto& result, const auto& data) { results[result.address] = std::make_pair(result, data.ToString()); }); @@ -326,16 +325,16 @@ TEST_F(HCI_LegacyLowEnergyScannerTest, ActiveScanResults) { ASSERT_EQ(kExpectedResultCount, results.size()); - // Ending the scan period should notify Fake Device #4. + // Ending the scan period should notify Fake Peer #4. scanner()->StopScanPeriodForTesting(); RunLoopUntilIdle(); EXPECT_EQ(LowEnergyScanner::ScanStatus::kComplete, last_scan_status()); ASSERT_EQ(kExpectedResultCount + 1, results.size()); - // Verify the 6 results against the fake devices that were set up by + // Verify the 6 results against the fake peers that were set up by // AddFakePeers(). Since the scan period ended naturally, LowEnergyScanner - // should generate a device found event for all pending reports even if a scan - // response was not received for a scannable device (see Fake Device 4, i.e. + // should generate a peer found event for all pending reports even if a scan + // response was not received for a scannable peer (see Fake Peer 4, i.e. // kRandomAddress3). // Result 0 @@ -417,7 +416,7 @@ TEST_F(HCI_LegacyLowEnergyScannerTest, StopDuringActiveScan) { AddFakePeers(); std::map<DeviceAddress, std::pair<LowEnergyScanResult, std::string>> results; - set_device_found_callback( + set_peer_found_callback( [&results, this](const auto& result, const auto& data) { results[result.address] = std::make_pair(result, data.ToString()); }); @@ -429,8 +428,8 @@ TEST_F(HCI_LegacyLowEnergyScannerTest, StopDuringActiveScan) { RunLoopUntilIdle(); EXPECT_EQ(LowEnergyScanner::State::kActiveScanning, scanner()->state()); - // Run the loop until we've seen an event for the last device that we - // added. Fake Device 4 (i.e. kRandomAddress3) is scannable but it never sends + // Run the loop until we've seen an event for the last peer that we + // added. Fake Peer 4 (i.e. kRandomAddress3) is scannable but it never sends // a scan response so we expect that remain in the scanner's pending reports // list. RunLoopUntilIdle(); @@ -438,7 +437,7 @@ TEST_F(HCI_LegacyLowEnergyScannerTest, StopDuringActiveScan) { EXPECT_EQ(results.find(kRandomAddress3), results.end()); // Stop the scan. Since we are terminating the scan period early, - // LowEnergyScanner should not send a report for the pending device. + // LowEnergyScanner should not send a report for the pending peer. EXPECT_TRUE(scanner()->StopScan()); RunLoopUntilIdle(); EXPECT_TRUE(scanner()->IsIdle()); @@ -452,7 +451,7 @@ TEST_F(HCI_LegacyLowEnergyScannerTest, PassiveScanResults) { AddFakePeers(); std::map<DeviceAddress, std::pair<LowEnergyScanResult, std::string>> results; - set_device_found_callback([&, this](const auto& result, const auto& data) { + set_peer_found_callback([&, this](const auto& result, const auto& data) { results[result.address] = std::make_pair(result, data.ToString()); }); @@ -466,7 +465,7 @@ TEST_F(HCI_LegacyLowEnergyScannerTest, PassiveScanResults) { EXPECT_EQ(LowEnergyScanner::ScanStatus::kPassive, last_scan_status()); ASSERT_EQ(kExpectedResultCount, results.size()); - // Verify the 6 results against the fake devices that were set up by + // Verify the 6 results against the fake peers that were set up by // AddFakePeers(). All Scan Response PDUs should have been ignored. // Result 0 diff --git a/src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.cc b/src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.cc index 111114ece58d8438748febab4318b056855f9916..3b34f95a4ce9a864b9ed2d01bbc72b2db21e022e 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.cc @@ -14,8 +14,8 @@ namespace hci { // Default implementations do nothing. -void LowEnergyScanner::Delegate::OnDeviceFound( - const LowEnergyScanResult& result, const common::ByteBuffer& data) {} +void LowEnergyScanner::Delegate::OnPeerFound(const LowEnergyScanResult& result, + const common::ByteBuffer& data) {} void LowEnergyScanner::Delegate::OnDirectedAdvertisement( const LowEnergyScanResult& result) {} diff --git a/src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.h b/src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.h index bc68686cca03039123d7afedf4def9d37d3fb016..81f18a32585433252ca47c9f5bc605a4a489f22a 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.h +++ b/src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.h @@ -22,30 +22,30 @@ namespace hci { class Transport; -// Represents a discovered Bluetooth Low Energy device. +// Represents a discovered Bluetooth Low Energy peer. struct LowEnergyScanResult { LowEnergyScanResult(); LowEnergyScanResult(const common::DeviceAddress& address, bool resolved, bool connectable, int8_t rssi); - // The device address of the remote device. + // The device address of the remote peer. common::DeviceAddress address; // True if |address| is a static or random identity address resolved by the // controller. bool resolved; - // True if this device accepts connections. This is the case if this device + // True if this peer accepts connections. This is the case if this peer // sent a connectable advertising PDU. bool connectable; // The received signal strength of the advertisement packet corresponding to - // this device. + // this peer. int8_t rssi; }; -// LowEnergyScanner manages Low Energy device scan procedures that are used -// during general and limited device discovery and connection establishment +// LowEnergyScanner manages Low Energy scan procedures that are used +// during general and limited discovery and connection establishment // procedures. This is an abstract class that provides a common interface // over 5.0 Extended Advertising and Legacy Advertising features. // @@ -74,17 +74,17 @@ class LowEnergyScanner : public LocalAddressClient { kPassiveScanning, }; - // Interface for receiving events related to Low Energy device scan. + // Interface for receiving events related to Low Energy scan. class Delegate { public: virtual ~Delegate() = default; - // Called when a device is found. |data| contains the advertising data, as + // Called when a peer is found. |data| contains the advertising data, as // well as any scan response data that was received during an active scan. - virtual void OnDeviceFound(const LowEnergyScanResult& result, - const common::ByteBuffer& data); + virtual void OnPeerFound(const LowEnergyScanResult& result, + const common::ByteBuffer& data); - // Called when a directed advertising report is received from the device + // Called when a directed advertising report is received from the peer // with the given address. virtual void OnDirectedAdvertisement(const LowEnergyScanResult& result); }; @@ -108,7 +108,7 @@ class LowEnergyScanner : public LocalAddressClient { // True if no scan procedure is currently enabled. bool IsIdle() const { return state() == State::kIdle; } - // Initiates a device scan. This is an asynchronous operation that abides by + // Initiates a scan. This is an asynchronous operation that abides by // the following rules: // // - This method synchronously returns false if the procedure could not be @@ -136,10 +136,10 @@ class LowEnergyScanner : public LocalAddressClient { // the scan period if a finite value for |period| was provided. // // If an active scan is being performed, then scannable advertising reports - // will NOT generate an OnDeviceFound event until a scan response is received + // will NOT generate an OnPeerFound event until a scan response is received // from the corresponding broadcaster. If a scan response from a scannable - // device is never received during a scan period, then an OnDeviceFound event - // (excluding scan response data) will be generated for that device at the end + // peer is never received during a scan period, then an OnPeerFound event + // (excluding scan response data) will be generated for that peer at the end // of the scan period, UNLESS the scan was explicitly stopped via StopScan(). enum class ScanStatus { // Reported when the scan could not be started. @@ -164,7 +164,7 @@ class LowEnergyScanner : public LocalAddressClient { LEScanFilterPolicy filter_policy, zx::duration period, ScanStatusCallback callback) = 0; - // Stops a previously started device scan. Returns false if a scan is not in + // Stops a previously started scan. Returns false if a scan is not in // progress. Otherwise, cancels any in progress scan procedure and returns // true. virtual bool StopScan() = 0; diff --git a/src/connectivity/bluetooth/core/bt-host/hci/util.cc b/src/connectivity/bluetooth/core/bt-host/hci/util.cc index 0ac3d507296d4bf5bdd51a4fbbfdc1b89f1cb7b5..77a730f420746d3aecaaf3efb32632c60117bd75 100644 --- a/src/connectivity/bluetooth/core/bt-host/hci/util.cc +++ b/src/connectivity/bluetooth/core/bt-host/hci/util.cc @@ -66,7 +66,7 @@ std::string StatusCodeToString(StatusCode code) { case kInvalidHCICommandParameters: return "invalid HCI command parameters"; case kRemoteUserTerminatedConnection: return "remote user terminated connection"; case kRemoteDeviceTerminatedConnectionLowResources: return "remote device terminated connection: low resources"; - case kRemoteDeviceTerminatedConnectionPowerOff: return "remote device rerminated connection: power off"; + case kRemoteDeviceTerminatedConnectionPowerOff: return "remote device terminated connection: power off"; case kConnectionTerminatedByLocalHost: return "connection terminated by local host"; case kRepeatedAttempts: return "repeated attempts"; case kPairingNotAllowed: return "pairing not allowed"; diff --git a/src/connectivity/bluetooth/core/bt-host/testing/fake_controller.cc b/src/connectivity/bluetooth/core/bt-host/testing/fake_controller.cc index 4092dd7b685b883afe67da1d820b23d32f3a30fc..903d0ef69f96329b72b426b7087bd798d06255b5 100644 --- a/src/connectivity/bluetooth/core/bt-host/testing/fake_controller.cc +++ b/src/connectivity/bluetooth/core/bt-host/testing/fake_controller.cc @@ -240,8 +240,7 @@ void FakeController::SetLEConnectionParametersCallback( le_conn_params_cb_dispatcher_ = dispatcher; } -FakePeer* FakeController::FindDeviceByAddress( - const common::DeviceAddress& addr) { +FakePeer* FakeController::FindByAddress(const common::DeviceAddress& addr) { for (auto& dev : peers_) { if (dev->address() == addr) return dev.get(); @@ -249,8 +248,7 @@ FakePeer* FakeController::FindDeviceByAddress( return nullptr; } -FakePeer* FakeController::FindDeviceByConnHandle( - hci::ConnectionHandle handle) { +FakePeer* FakeController::FindByConnHandle(hci::ConnectionHandle handle) { for (auto& dev : peers_) { if (dev->HasLink(handle)) return dev.get(); @@ -387,17 +385,17 @@ void FakeController::SendNumberOfCompletedPacketsEvent( void FakeController::ConnectLowEnergy(const common::DeviceAddress& addr, hci::ConnectionRole role) { async::PostTask(dispatcher(), [addr, role, this] { - FakePeer* dev = FindDeviceByAddress(addr); + FakePeer* dev = FindByAddress(addr); if (!dev) { - bt_log(WARN, "fake-hci", "no device found with address: %s", + bt_log(WARN, "fake-hci", "no peer found with address: %s", addr.ToString().c_str()); return; } - // TODO(armansito): Don't worry about managing multiple links per device + // TODO(armansito): Don't worry about managing multiple links per peer // until this supports Bluetooth classic. if (dev->connected()) { - bt_log(WARN, "fake-hci", "device already connected"); + bt_log(WARN, "fake-hci", "peer already connected"); return; } @@ -436,15 +434,15 @@ void FakeController::L2CAPConnectionParameterUpdate( const common::DeviceAddress& addr, const hci::LEPreferredConnectionParameters& params) { async::PostTask(dispatcher(), [addr, params, this] { - FakePeer* dev = FindDeviceByAddress(addr); + FakePeer* dev = FindByAddress(addr); if (!dev) { - bt_log(WARN, "fake-hci", "no device found with address: %s", + bt_log(WARN, "fake-hci", "no peer found with address: %s", addr.ToString().c_str()); return; } if (!dev->connected()) { - bt_log(WARN, "fake-hci", "device not connected"); + bt_log(WARN, "fake-hci", "peer not connected"); return; } @@ -467,9 +465,9 @@ void FakeController::L2CAPConnectionParameterUpdate( void FakeController::Disconnect(const common::DeviceAddress& addr) { async::PostTask(dispatcher(), [addr, this] { - FakePeer* dev = FindDeviceByAddress(addr); + FakePeer* dev = FindByAddress(addr); if (!dev || !dev->connected()) { - bt_log(WARN, "fake-hci", "no connected device found with address: %s", + bt_log(WARN, "fake-hci", "no connected peer found with address: %s", addr.ToString().c_str()); return; } @@ -508,12 +506,12 @@ bool FakeController::MaybeRespondWithDefaultStatus(hci::OpCode opcode) { void FakeController::SendInquiryResponses() { // TODO(jamuraa): combine some of these into a single response event - for (const auto& device : peers_) { - if (!device->has_inquiry_response()) { + for (const auto& peer : peers_) { + if (!peer->has_inquiry_response()) { continue; } - SendCommandChannelPacket(device->CreateInquiryResponseEvent(inquiry_mode_)); + SendCommandChannelPacket(peer->CreateInquiryResponseEvent(inquiry_mode_)); inquiry_num_responses_left_--; if (inquiry_num_responses_left_ == 0) { break; @@ -525,26 +523,26 @@ void FakeController::SendAdvertisingReports() { if (!le_scan_state_.enabled || peers_.empty()) return; - for (const auto& device : peers_) { - if (!device->has_advertising_reports()) { + for (const auto& peer : peers_) { + if (!peer->has_advertising_reports()) { continue; } // We want to send scan response packets only during an active scan and if - // the device is scannable. + // the peer is scannable. bool need_scan_rsp = (le_scan_state().scan_type == hci::LEScanType::kActive) && - device->scannable(); - SendCommandChannelPacket(device->CreateAdvertisingReportEvent( - need_scan_rsp && device->should_batch_reports())); + peer->scannable(); + SendCommandChannelPacket(peer->CreateAdvertisingReportEvent( + need_scan_rsp && peer->should_batch_reports())); // If the original report did not include a scan response then we send it as // a separate event. - if (need_scan_rsp && !device->should_batch_reports()) { - SendCommandChannelPacket(device->CreateScanResponseReportEvent()); + if (need_scan_rsp && !peer->should_batch_reports()) { + SendCommandChannelPacket(peer->CreateScanResponseReportEvent()); } } - // We'll send new reports for the same devices if duplicate filtering is + // We'll send new reports for the same peers if duplicate filtering is // disabled. if (!le_scan_state_.filter_duplicates) { async::PostTask(dispatcher(), [this] { SendAdvertisingReports(); }); @@ -597,13 +595,13 @@ void FakeController::OnCreateConnectionCommandReceived( const DeviceAddress peer_address(DeviceAddress::Type::kBREDR, params.bd_addr); hci::StatusCode status = hci::StatusCode::kSuccess; - // Find the device that matches the requested address. - FakePeer* device = FindDeviceByAddress(peer_address); - if (device) { - if (device->connected()) + // Find the peer that matches the requested address. + FakePeer* peer = FindByAddress(peer_address); + if (peer) { + if (peer->connected()) status = hci::StatusCode::kConnectionAlreadyExists; else - status = device->connect_status(); + status = peer->connect_status(); } // First send the Command Status response. @@ -616,11 +614,11 @@ void FakeController::OnCreateConnectionCommandReceived( bredr_connect_pending_ = true; pending_bredr_connect_addr_ = peer_address; - // The procedure was initiated successfully but the device cannot be connected + // The procedure was initiated successfully but the peer cannot be connected // because it either doesn't exist or isn't connectable. - if (!device || !device->connectable()) { + if (!peer || !peer->connectable()) { bt_log(INFO, "fake-hci", - "requested device %s cannot be connected; request will time out", + "requested peer %s cannot be connected; request will time out", peer_address.ToString().c_str()); pending_bredr_connect_rsp_.Reset([this, peer_address] { @@ -648,7 +646,7 @@ void FakeController::OnCreateConnectionCommandReceived( // Ran out of handles status = hci::StatusCode::kConnectionLimitExceeded; } else { - status = device->connect_response(); + status = peer->connect_response(); } hci::ConnectionCompleteEventParams response = {}; @@ -666,17 +664,17 @@ void FakeController::OnCreateConnectionCommandReceived( // Don't send a connection event if we were asked to force the request to // remain pending. This is used by test cases that operate during the pending // state. - if (device->force_pending_connect()) + if (peer->force_pending_connect()) return; - pending_bredr_connect_rsp_.Reset([response, device, this] { + pending_bredr_connect_rsp_.Reset([response, peer, this] { bredr_connect_pending_ = false; if (response.status == hci::StatusCode::kSuccess) { - bool notify = !device->connected(); - device->AddLink(le16toh(response.connection_handle)); - if (notify && device->connected()) - NotifyConnectionState(device->address(), true); + bool notify = !peer->connected(); + peer->AddLink(le16toh(response.connection_handle)); + if (notify && peer->connected()) + NotifyConnectionState(peer->address(), true); } SendEvent(hci::kConnectionCompleteEventCode, @@ -702,13 +700,13 @@ void FakeController::OnLECreateConnectionCommandReceived( const common::DeviceAddress peer_address(addr_type, params.peer_address); hci::StatusCode status = hci::StatusCode::kSuccess; - // Find the device that matches the requested address. - FakePeer* device = FindDeviceByAddress(peer_address); - if (device) { - if (device->connected()) + // Find the peer that matches the requested address. + FakePeer* peer = FindByAddress(peer_address); + if (peer) { + if (peer->connected()) status = hci::StatusCode::kConnectionAlreadyExists; else - status = device->connect_status(); + status = peer->connect_status(); } // First send the Command Status response. @@ -726,11 +724,11 @@ void FakeController::OnLECreateConnectionCommandReceived( le_connect_params_->own_address_type = params.own_address_type; le_connect_params_->peer_address = peer_address; - // The procedure was initiated successfully but the device cannot be connected + // The procedure was initiated successfully but the peer cannot be connected // because it either doesn't exist or isn't connectable. - if (!device || !device->connectable()) { + if (!peer || !peer->connectable()) { bt_log(INFO, "fake-hci", - "requested fake device cannot be connected; request will time out"); + "requested fake peer cannot be connected; request will time out"); return; } @@ -738,7 +736,7 @@ void FakeController::OnLECreateConnectionCommandReceived( // Ran out of handles status = hci::StatusCode::kConnectionLimitExceeded; } else { - status = device->connect_response(); + status = peer->connect_response(); } hci::LEConnectionCompleteSubeventParams response; @@ -756,7 +754,7 @@ void FakeController::OnLECreateConnectionCommandReceived( hci::LEConnectionParameters conn_params( interval, le16toh(params.conn_latency), le16toh(params.supervision_timeout)); - device->set_le_params(conn_params); + peer->set_le_params(conn_params); response.conn_latency = params.conn_latency; response.conn_interval = le16toh(interval); @@ -771,17 +769,17 @@ void FakeController::OnLECreateConnectionCommandReceived( // Don't send a connection event if we were asked to force the request to // remain pending. This is used by test cases that operate during the pending // state. - if (device->force_pending_connect()) + if (peer->force_pending_connect()) return; - pending_le_connect_rsp_.Reset([response, device, this] { + pending_le_connect_rsp_.Reset([response, peer, this] { le_connect_pending_ = false; if (response.status == hci::StatusCode::kSuccess) { - bool notify = !device->connected(); - device->AddLink(le16toh(response.connection_handle)); - if (notify && device->connected()) - NotifyConnectionState(device->address(), true); + bool notify = !peer->connected(); + peer->AddLink(le16toh(response.connection_handle)); + if (notify && peer->connected()) + NotifyConnectionState(peer->address(), true); } SendLEMetaEvent(hci::kLEConnectionCompleteSubeventCode, @@ -795,14 +793,14 @@ void FakeController::OnLECreateConnectionCommandReceived( void FakeController::OnLEConnectionUpdateCommandReceived( const hci::LEConnectionUpdateCommandParams& params) { hci::ConnectionHandle handle = le16toh(params.connection_handle); - FakePeer* device = FindDeviceByConnHandle(handle); - if (!device) { + FakePeer* peer = FindByConnHandle(handle); + if (!peer) { RespondWithCommandStatus(hci::kLEConnectionUpdate, hci::StatusCode::kUnknownConnectionId); return; } - ZX_DEBUG_ASSERT(device->connected()); + ZX_DEBUG_ASSERT(peer->connected()); uint16_t min_interval = le16toh(params.conn_interval_min); uint16_t max_interval = le16toh(params.conn_interval_max); @@ -820,7 +818,7 @@ void FakeController::OnLEConnectionUpdateCommandReceived( hci::LEConnectionParameters conn_params( min_interval + ((max_interval - min_interval) / 2), max_latency, supv_timeout); - device->set_le_params(conn_params); + peer->set_le_params(conn_params); hci::LEConnectionUpdateCompleteSubeventParams reply; reply.status = hci::StatusCode::kSuccess; @@ -832,29 +830,29 @@ void FakeController::OnLEConnectionUpdateCommandReceived( SendLEMetaEvent(hci::kLEConnectionUpdateCompleteSubeventCode, BufferView(&reply, sizeof(reply))); - NotifyLEConnectionParameters(device->address(), conn_params); + NotifyLEConnectionParameters(peer->address(), conn_params); } void FakeController::OnDisconnectCommandReceived( const hci::DisconnectCommandParams& params) { hci::ConnectionHandle handle = le16toh(params.connection_handle); - // Find the device that matches the disconnected handle. - FakePeer* device = FindDeviceByConnHandle(handle); - if (!device) { + // Find the peer that matches the disconnected handle. + FakePeer* peer = FindByConnHandle(handle); + if (!peer) { RespondWithCommandStatus(hci::kDisconnect, hci::StatusCode::kUnknownConnectionId); return; } - ZX_DEBUG_ASSERT(device->connected()); + ZX_DEBUG_ASSERT(peer->connected()); RespondWithCommandStatus(hci::kDisconnect, hci::StatusCode::kSuccess); - bool notify = device->connected(); - device->RemoveLink(handle); - if (notify && !device->connected()) - NotifyConnectionState(device->address(), false); + bool notify = peer->connected(); + peer->RemoveLink(handle); + if (notify && !peer->connected()) + NotifyConnectionState(peer->address(), false); hci::DisconnectionCompleteEventParams reply; reply.status = hci::StatusCode::kSuccess; @@ -1389,14 +1387,14 @@ void FakeController::OnACLDataPacketReceived( const auto& header = acl_data_packet.As<hci::ACLDataHeader>(); hci::ConnectionHandle handle = le16toh(header.handle_and_flags) & 0x0FFFF; - FakePeer* dev = FindDeviceByConnHandle(handle); - if (!dev) { + FakePeer* peer = FindByConnHandle(handle); + if (!peer) { bt_log(WARN, "fake-hci", "ACL data received for unknown handle!"); return; } SendNumberOfCompletedPacketsEvent(handle, 1); - dev->OnRxL2CAP(handle, acl_data_packet.view(sizeof(hci::ACLDataHeader))); + peer->OnRxL2CAP(handle, acl_data_packet.view(sizeof(hci::ACLDataHeader))); } } // namespace testing diff --git a/src/connectivity/bluetooth/core/bt-host/testing/fake_controller.h b/src/connectivity/bluetooth/core/bt-host/testing/fake_controller.h index 540ff15559f47d26c90c7ecbfc78cd882ef1cf43..1f4d134f3c39a6e67ba43069e76ca349691ab56b 100644 --- a/src/connectivity/bluetooth/core/bt-host/testing/fake_controller.h +++ b/src/connectivity/bluetooth/core/bt-host/testing/fake_controller.h @@ -228,8 +228,8 @@ class FakeController : public FakeControllerBase, // Finds and returns the FakePeer with the given parameters or nullptr if no // such device exists. - FakePeer* FindDeviceByAddress(const common::DeviceAddress& addr); - FakePeer* FindDeviceByConnHandle(hci::ConnectionHandle handle); + FakePeer* FindByAddress(const common::DeviceAddress& addr); + FakePeer* FindByConnHandle(hci::ConnectionHandle handle); // Returns the next available L2CAP signaling channel command ID. uint8_t NextL2CAPCommandId();