Migrate to AnyInvocable in platform code

PiperOrigin-RevId: 504104740
This commit is contained in:
Janusz Sobczak
2023-01-23 16:04:21 -08:00
committed by Copybara-Service
parent 7f34968b78
commit f4d85f9b90
100 changed files with 449 additions and 494 deletions
@@ -44,10 +44,9 @@ class EncryptionRunner {
std::unique_ptr<securegcm::UKey2Handshake> ukey2,
const std::string& auth_token,
const ByteArray& raw_auth_token)>
on_success_cb =
DefaultCallback<const std::string&,
std::unique_ptr<securegcm::UKey2Handshake>,
const std::string&, const ByteArray&>();
on_success_cb = [](const std::string&,
std::unique_ptr<securegcm::UKey2Handshake>,
const std::string&, const ByteArray&) {};
// Encryption has failed. The remote_endpoint_id and channel are given so
// that any pending state can be cleaned up.
@@ -60,7 +59,7 @@ class EncryptionRunner {
// @EncryptionRunnerThread
std::function<void(const std::string& endpoint_id,
EndpointChannel* channel)>
on_failure_cb = DefaultCallback<const std::string&, EndpointChannel*>();
on_failure_cb = [](const std::string&, EndpointChannel*) {};
};
// @AnyThread
+2 -2
View File
@@ -21,9 +21,9 @@
#include "absl/strings/escaping.h"
#include "connections/implementation/mediums/ble_v2/ble_advertisement.h"
#include "connections/implementation/mediums/utils.h"
#include "internal/platform/prng.h"
#include "internal/platform/logging.h"
#include "internal/platform/mutex_lock.h"
#include "internal/platform/prng.h"
namespace nearby {
namespace connections {
@@ -273,7 +273,7 @@ bool Ble::StartAcceptingConnections(const std::string& service_id,
return false;
}
if (!medium_.StartAcceptingConnections(service_id, callback)) {
if (!medium_.StartAcceptingConnections(service_id, std::move(callback))) {
NEARBY_LOGS(INFO) << "Failed to accept connections callback for "
<< service_id << " .";
return false;
+1 -1
View File
@@ -51,7 +51,7 @@ class BleV2 final {
// Callback that is invoked when a new connection is accepted.
struct AcceptedConnectionCallback {
std::function<void(BleV2Socket socket, const std::string& service_id)>
absl::AnyInvocable<void(BleV2Socket socket, const std::string& service_id)>
accepted_cb = DefaultCallback<BleV2Socket, const std::string&>();
};
@@ -32,13 +32,12 @@ struct DiscoveredPeripheralCallback {
const ByteArray& advertisement_bytes,
bool fast_advertisement)>
peripheral_discovered_cb =
DefaultCallback<BleV2Peripheral, const std::string&, const ByteArray&,
bool>();
[](BleV2Peripheral, const std::string&, const ByteArray&, bool) {};
std::function<void(BleV2Peripheral peripheral, const std::string& service_id,
const ByteArray& advertisement_bytes,
bool fast_advertisement)>
peripheral_lost_cb = DefaultCallback<BleV2Peripheral, const std::string&,
const ByteArray&, bool>();
peripheral_lost_cb =
[](BleV2Peripheral, const std::string&, const ByteArray&, bool) {};
};
} // namespace mediums
@@ -52,10 +52,9 @@ class DiscoveredPeripheralTracker {
BleV2Peripheral peripheral, int num_slots, int psm,
const std::vector<std::string>& interesting_service_ids,
mediums::AdvertisementReadResult& advertisement_read_result)>
fetch_advertisements =
DefaultCallback<BleV2Peripheral, int, int,
const std::vector<std::string>&,
mediums::AdvertisementReadResult&>();
fetch_advertisements = [](BleV2Peripheral, int, int,
const std::vector<std::string>&,
mediums::AdvertisementReadResult&) {};
};
explicit DiscoveredPeripheralTracker(
@@ -76,8 +75,7 @@ class DiscoveredPeripheralTracker {
void StartTracking(
const std::string& service_id,
const DiscoveredPeripheralCallback& discovered_peripheral_callback,
const Uuid& fast_advertisement_service_uuid)
ABSL_LOCKS_EXCLUDED(mutex_);
const Uuid& fast_advertisement_service_uuid) ABSL_LOCKS_EXCLUDED(mutex_);
// Stops tracking discoveries for a particular service Id.
void StopTracking(const std::string& service_id) ABSL_LOCKS_EXCLUDED(mutex_);
@@ -203,7 +203,7 @@ bool BluetoothClassic::StartDiscovery(DiscoveredDeviceCallback callback) {
return false;
}
if (!medium_.StartDiscovery(callback)) {
if (!medium_.StartDiscovery(std::move(callback))) {
NEARBY_LOGS(INFO) << "Failed to start discovery of BT devices.";
return false;
}
@@ -22,10 +22,10 @@
#include "absl/container/flat_hash_map.h"
#include "connections/implementation/mediums/bluetooth_radio.h"
#include "connections/listeners.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/cancellation_flag.h"
#include "internal/platform/bluetooth_adapter.h"
#include "internal/platform/bluetooth_classic.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/cancellation_flag.h"
#include "internal/platform/multi_thread_executor.h"
#include "internal/platform/mutex.h"
@@ -40,7 +40,7 @@ class BluetoothClassic {
// Callback that is invoked when a new connection is accepted.
struct AcceptedConnectionCallback {
std::function<void(const std::string& service_id, BluetoothSocket socket)>
accepted_cb = DefaultCallback<const std::string&, BluetoothSocket>();
accepted_cb = [](const std::string&, BluetoothSocket) {};
};
explicit BluetoothClassic(BluetoothRadio& bluetooth_radio);
+1 -2
View File
@@ -28,7 +28,6 @@
#include "internal/platform/cancelable_alarm.h"
#include "internal/platform/cancellation_flag.h"
#include "internal/platform/future.h"
#include "internal/platform/listeners.h"
#include "internal/platform/mutex.h"
#include "internal/platform/runnable.h"
#include "internal/platform/scheduled_executor.h"
@@ -43,7 +42,7 @@ namespace mediums {
// Callback that is invoked when a new connection is accepted.
struct AcceptedConnectionCallback {
std::function<void(const std::string& service_id, WebRtcSocketWrapper socket)>
accepted_cb = DefaultCallback<const std::string&, WebRtcSocketWrapper>();
accepted_cb = [](const std::string&, WebRtcSocketWrapper) {};
};
// Entry point for connecting a data channel between two devices via WebRtc.
@@ -420,9 +420,10 @@ void ConnectionFlow::CreateSocketFromDataChannel(
// Pass socket wrapper by copy on purpose
data_channel_listener_.data_channel_open_cb(socket_wrapper_);
}},
.socket_closed_cb = [callback =
data_channel_listener_.data_channel_closed_cb](
WebRtcSocket*) { callback(); },
.socket_closed_cb =
[this](WebRtcSocket*) {
data_channel_listener_.data_channel_closed_cb();
},
});
socket_wrapper_ = WebRtcSocketWrapper(std::move(socket));
}
@@ -28,10 +28,10 @@ struct DataChannelListener {
// Called when the data channel is open and the socket wraper is ready to
// read and write.
std::function<void(WebRtcSocketWrapper)> data_channel_open_cb =
DefaultCallback<WebRtcSocketWrapper>();
[](WebRtcSocketWrapper) {};
// Called when the data channel is closed.
std::function<void()> data_channel_closed_cb = DefaultCallback<>();
std::function<void()> data_channel_closed_cb = []() {};
};
} // namespace mediums
@@ -25,7 +25,7 @@ namespace mediums {
// Callbacks from local ice candidate collection.
struct LocalIceCandidateListener {
// Called when a new local ice candidate has been found.
std::function<void(const webrtc::IceCandidateInterface*)>
absl::AnyInvocable<void(const webrtc::IceCandidateInterface*)>
local_ice_candidate_found_cb =
nearby::DefaultCallback<const webrtc::IceCandidateInterface*>();
};
@@ -18,14 +18,14 @@
#include <memory>
#include "connections/listeners.h"
#include "internal/platform/input_stream.h"
#include "internal/platform/output_stream.h"
#include "internal/platform/socket.h"
#include "internal/platform/atomic_boolean.h"
#include "internal/platform/condition_variable.h"
#include "internal/platform/input_stream.h"
#include "internal/platform/mutex.h"
#include "internal/platform/output_stream.h"
#include "internal/platform/pipe.h"
#include "internal/platform/single_thread_executor.h"
#include "internal/platform/socket.h"
#include "webrtc/api/data_channel_interface.h"
namespace nearby {
@@ -61,9 +61,9 @@ class WebRtcSocket : public Socket, public webrtc::DataChannelObserver {
// Listener class the gets called when the socket is ready or closed
struct SocketListener {
std::function<void(WebRtcSocket*)> socket_ready_cb =
absl::AnyInvocable<void(WebRtcSocket*)> socket_ready_cb =
DefaultCallback<WebRtcSocket*>();
std::function<void(WebRtcSocket*)> socket_closed_cb =
absl::AnyInvocable<void(WebRtcSocket*)> socket_closed_cb =
DefaultCallback<WebRtcSocket*>();
};
@@ -20,9 +20,9 @@
#include <memory>
#include <string>
#include "connections/implementation/proto/offline_wire_formats.pb.h"
#include "connections/implementation/mediums/webrtc_peer_id_stub.h"
#include "connections/implementation/mediums/webrtc_socket_stub.h"
#include "connections/implementation/proto/offline_wire_formats.pb.h"
#include "internal/platform/cancellation_flag.h"
#include "internal/platform/listeners.h"
@@ -32,7 +32,7 @@ namespace mediums {
// Callback that is invoked when a new connection is accepted.
struct AcceptedConnectionCallback {
std::function<void(WebRtcSocketWrapper socket)> accepted_cb =
DefaultCallback<WebRtcSocketWrapper>();
[](WebRtcSocketWrapper) {};
};
// Entry point for connecting a data channel between two devices via WebRtc.
class WebRtc {
@@ -31,7 +31,7 @@ class WifiDirect {
// Callback that is invoked when a new connection is accepted.
struct AcceptedConnectionCallback {
std::function<void(const std::string& service_id, WifiDirectSocket socket)>
accepted_cb = DefaultCallback<const std::string&, WifiDirectSocket>();
accepted_cb = [](const std::string&, WifiDirectSocket) {};
};
WifiDirect() : is_go_started_(false), is_connected_to_go_(false) {}
@@ -31,7 +31,7 @@ class WifiHotspot {
// Callback that is invoked when a new connection is accepted.
struct AcceptedConnectionCallback {
std::function<void(const std::string& service_id, WifiHotspotSocket socket)>
accepted_cb = DefaultCallback<const std::string&, WifiHotspotSocket>();
accepted_cb = [](const std::string&, WifiHotspotSocket) {};
};
WifiHotspot() : is_hotspot_started_(false), is_connected_to_hotspot_(false) {}
@@ -42,7 +42,6 @@ class WifiHotspot {
WifiHotspot(WifiHotspot&&) = delete;
WifiHotspot& operator=(WifiHotspot&&) = delete;
// Returns true, if WifiHotspot communications are supported by a platform.
bool IsAPAvailable() const ABSL_LOCKS_EXCLUDED(mutex_);
bool IsClientAvailable() const ABSL_LOCKS_EXCLUDED(mutex_);
@@ -161,7 +161,8 @@ bool WifiLan::StartDiscovery(const std::string& service_id,
}
std::string service_type = GenerateServiceType(service_id);
bool ret = medium_.StartDiscovery(service_id, service_type, callback);
bool ret =
medium_.StartDiscovery(service_id, service_type, std::move(callback));
if (!ret) {
NEARBY_LOGS(INFO) << "Failed to start discovery of WifiLan services.";
return false;
@@ -23,9 +23,9 @@
#include "absl/container/flat_hash_set.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/cancellation_flag.h"
#include "internal/platform/nsd_service_info.h"
#include "internal/platform/multi_thread_executor.h"
#include "internal/platform/mutex.h"
#include "internal/platform/nsd_service_info.h"
#include "internal/platform/wifi_lan.h"
namespace nearby {
@@ -38,7 +38,7 @@ class WifiLan {
// Callback that is invoked when a new connection is accepted.
struct AcceptedConnectionCallback {
std::function<void(const std::string& service_id, WifiLanSocket socket)>
accepted_cb = DefaultCallback<const std::string&, WifiLanSocket>();
accepted_cb = [](const std::string&, WifiLanSocket) {};
};
WifiLan() = default;
@@ -290,80 +290,81 @@ void P2pClusterPcpHandler::BluetoothNameChangedHandler(
BluetoothDevice device) {
RunOnPcpHandlerThread(
"p2p-bt-name-changed",
[this, client, service_id, device]() RUN_ON_PCP_HANDLER_THREAD() {
// Make sure we are still discovering before proceeding.
if (!client->IsDiscovering()) {
NEARBY_LOGS(WARNING)
<< "Ignoring lost BluetoothDevice " << device.GetName()
<< " because Connections is no longer discovering.";
return;
}
[this, client, service_id, device]()
RUN_ON_PCP_HANDLER_THREAD() {
// Make sure we are still discovering before proceeding.
if (!client->IsDiscovering()) {
NEARBY_LOGS(WARNING)
<< "Ignoring lost BluetoothDevice " << device.GetName()
<< " because Connections is no longer discovering.";
return;
}
// Parse the Bluetooth device name.
const std::string device_name_string = device.GetName();
BluetoothDeviceName device_name(device_name_string);
NEARBY_LOGS(INFO) << "BT discovery handler (CHANGED) [client_id="
<< client->GetClientId()
<< ", service_id=" << service_id
<< "]: processing new name " << device_name_string;
// Parse the Bluetooth device name.
const std::string device_name_string = device.GetName();
BluetoothDeviceName device_name(device_name_string);
NEARBY_LOGS(INFO)
<< "BT discovery handler (CHANGED) [client_id="
<< client->GetClientId() << ", service_id=" << service_id
<< "]: processing new name " << device_name_string;
// By this point, the BluetoothDevice passed to us has a different name
// than what we may have discovered before. We need to iterate over the
// found BluetoothEndpoints and compare their addresses to see the
// devices are the same. We are not guaranteed to discover a match,
// since the old name may not have been formatted for Nearby
// Connections.
for (auto endpoint : GetDiscoveredEndpoints(
location::nearby::proto::connections::Medium::BLUETOOTH)) {
BluetoothEndpoint* bluetoothEndpoint =
static_cast<BluetoothEndpoint*>(endpoint);
NEARBY_LOGS(INFO)
<< "BT discovery handler (CHANGED) [client_id="
<< client->GetClientId() << ", service_id=" << service_id
<< "]: comparing MAC addresses with existing endpoint "
<< bluetoothEndpoint->bluetooth_device.GetName()
<< ". They have MAC address "
<< bluetoothEndpoint->bluetooth_device.GetMacAddress()
<< " and the new endpoint has MAC address "
<< device.GetMacAddress();
if (bluetoothEndpoint->bluetooth_device.GetMacAddress() ==
device.GetMacAddress()) {
// Report the BluetoothEndpoint as lost to the client.
NEARBY_LOGS(INFO) << "Reporting lost BluetoothDevice "
<< bluetoothEndpoint->bluetooth_device.GetName()
<< ", due to device name change.";
OnEndpointLost(client, *endpoint);
break;
}
}
// By this point, the BluetoothDevice passed to us has a different
// name than what we may have discovered before. We need to iterate
// over the found BluetoothEndpoints and compare their addresses to
// see the devices are the same. We are not guaranteed to discover a
// match, since the old name may not have been formatted for Nearby
// Connections.
for (auto endpoint : GetDiscoveredEndpoints(
location::nearby::proto::connections::Medium::BLUETOOTH)) {
BluetoothEndpoint* bluetoothEndpoint =
static_cast<BluetoothEndpoint*>(endpoint);
NEARBY_LOGS(INFO)
<< "BT discovery handler (CHANGED) [client_id="
<< client->GetClientId() << ", service_id=" << service_id
<< "]: comparing MAC addresses with existing endpoint "
<< bluetoothEndpoint->bluetooth_device.GetName()
<< ". They have MAC address "
<< bluetoothEndpoint->bluetooth_device.GetMacAddress()
<< " and the new endpoint has MAC address "
<< device.GetMacAddress();
if (bluetoothEndpoint->bluetooth_device.GetMacAddress() ==
device.GetMacAddress()) {
// Report the BluetoothEndpoint as lost to the client.
NEARBY_LOGS(INFO)
<< "Reporting lost BluetoothDevice "
<< bluetoothEndpoint->bluetooth_device.GetName()
<< ", due to device name change.";
OnEndpointLost(client, *endpoint);
break;
}
}
// Make sure the Bluetooth device name points to a valid
// endpoint we're discovering.
if (!IsRecognizedBluetoothEndpoint(device_name_string, service_id,
device_name)) {
NEARBY_LOGS(INFO) << "Found unrecognized BluetoothDeviceName "
<< device_name_string;
return;
}
// Make sure the Bluetooth device name points to a valid
// endpoint we're discovering.
if (!IsRecognizedBluetoothEndpoint(device_name_string, service_id,
device_name)) {
NEARBY_LOGS(INFO) << "Found unrecognized BluetoothDeviceName "
<< device_name_string;
return;
}
// Report the discovered endpoint to the client.
NEARBY_LOGS(INFO) << "Found BluetoothDeviceName " << device_name_string
<< " (with endpoint_id="
<< device_name.GetEndpointId()
<< " and endpoint_info="
<< absl::BytesToHexString(
device_name.GetEndpointInfo().data())
<< ").";
OnEndpointFound(
client,
std::make_shared<BluetoothEndpoint>(BluetoothEndpoint{
{device_name.GetEndpointId(), device_name.GetEndpointInfo(),
service_id,
location::nearby::proto::connections::Medium::BLUETOOTH,
device_name.GetWebRtcState()},
device,
}));
});
// Report the discovered endpoint to the client.
NEARBY_LOGS(INFO)
<< "Found BluetoothDeviceName " << device_name_string
<< " (with endpoint_id=" << device_name.GetEndpointId()
<< " and endpoint_info="
<< absl::BytesToHexString(device_name.GetEndpointInfo().data())
<< ").";
OnEndpointFound(
client,
std::make_shared<BluetoothEndpoint>(BluetoothEndpoint{
{device_name.GetEndpointId(), device_name.GetEndpointInfo(),
service_id,
location::nearby::proto::connections::Medium::BLUETOOTH,
device_name.GetWebRtcState()},
device,
}));
});
}
void P2pClusterPcpHandler::BluetoothDeviceLostHandler(
@@ -1764,19 +1765,19 @@ P2pClusterPcpHandler::StartWifiLanAdvertising(
RunOnPcpHandlerThread(
"p2p-wifi-on-incoming-connection",
[this, client, local_endpoint_id, local_endpoint_info,
service_id, socket = std::move(socket)]()
RUN_ON_PCP_HANDLER_THREAD() mutable {
std::string remote_service_name = local_endpoint_id;
auto channel = std::make_unique<WifiLanEndpointChannel>(
service_id, /*channel_name=*/remote_service_name,
socket);
ByteArray remote_service_name_byte{remote_service_name};
service_id,
socket = std::move(
socket)]() RUN_ON_PCP_HANDLER_THREAD() mutable {
std::string remote_service_name = local_endpoint_id;
auto channel = std::make_unique<WifiLanEndpointChannel>(
service_id, /*channel_name=*/remote_service_name,
socket);
ByteArray remote_service_name_byte{remote_service_name};
OnIncomingConnection(client, remote_service_name_byte,
std::move(channel),
location::nearby::proto::
connections::Medium::WIFI_LAN);
});
OnIncomingConnection(
client, remote_service_name_byte, std::move(channel),
location::nearby::proto::connections::Medium::WIFI_LAN);
});
}})) {
NEARBY_LOGS(WARNING)
<< "In StartWifiLanAdvertising("
+12 -15
View File
@@ -32,7 +32,6 @@
#include "connections/status.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/byte_utils.h"
#include "internal/platform/listeners.h"
namespace nearby {
namespace connections {
@@ -46,7 +45,7 @@ struct ResultCallback {
// Callback to access the status of the operation when available.
// status - result of job execution;
// Status::kSuccess, if successful; anything else indicates failure.
std::function<void(Status)> result_cb = DefaultCallback<Status>();
std::function<void(Status)> result_cb = [](Status) {};
};
struct ConnectionResponseInfo {
@@ -100,8 +99,7 @@ struct ConnectionListener {
// info - Other relevant information about the connection.
std::function<void(const std::string& endpoint_id,
const ConnectionResponseInfo& info)>
initiated_cb =
DefaultCallback<const std::string&, const ConnectionResponseInfo&>();
initiated_cb = [](const std::string&, const ConnectionResponseInfo&) {};
// Called after both sides have accepted the connection.
// Both sides may now send Payloads to each other.
@@ -109,7 +107,7 @@ struct ConnectionListener {
//
// endpoint_id - The identifier for the remote endpoint.
std::function<void(const std::string& endpoint_id)> accepted_cb =
DefaultCallback<const std::string&>();
[](const std::string&) {};
// Called when either side rejected the connection.
// Payloads can not be exchaged. Call Core::DisconnectFromEndpoint()
@@ -117,21 +115,21 @@ struct ConnectionListener {
//
// endpoint_id - The identifier for the remote endpoint.
std::function<void(const std::string& endpoint_id, Status status)>
rejected_cb = DefaultCallback<const std::string&, Status>();
rejected_cb = [](const std::string&, Status) {};
// Called when a remote endpoint is disconnected or has become unreachable.
// At this point service (re-)discovery may start again.
//
// endpoint_id - The identifier for the remote endpoint.
std::function<void(const std::string& endpoint_id)> disconnected_cb =
DefaultCallback<const std::string&>();
[](const std::string&) {};
// Called when the connection's available bandwidth has changed.
//
// endpoint_id - The identifier for the remote endpoint.
// medium - Medium we upgraded to.
std::function<void(const std::string& endpoint_id, Medium medium)>
bandwidth_changed_cb = DefaultCallback<const std::string&, Medium>();
bandwidth_changed_cb = [](const std::string&, Medium) {};
};
struct DiscoveryListener {
@@ -143,8 +141,8 @@ struct DiscoveryListener {
std::function<void(const std::string& endpoint_id,
const ByteArray& endpoint_info,
const std::string& service_id)>
endpoint_found_cb = DefaultCallback<const std::string&, const ByteArray&,
const std::string&>();
endpoint_found_cb =
[](const std::string&, const ByteArray&, const std::string&) {};
// Called when a remote endpoint is no longer discoverable; only called for
// endpoints that previously had been passed to {@link
@@ -152,7 +150,7 @@ struct DiscoveryListener {
//
// endpoint_id - The ID of the remote endpoint that was lost.
std::function<void(const std::string& endpoint_id)> endpoint_lost_cb =
DefaultCallback<const std::string&>();
[](const std::string&) {};
// Called when a remote endpoint is found with an updated distance.
//
@@ -160,8 +158,7 @@ struct DiscoveryListener {
// endpoint_id - The ID of the remote endpoint that was lost.
// info - The distance info, encoded as enum value.
std::function<void(const std::string& endpoint_id, DistanceInfo info)>
endpoint_distance_changed_cb =
DefaultCallback<const std::string&, DistanceInfo>();
endpoint_distance_changed_cb = [](const std::string&, DistanceInfo) {};
};
struct PayloadListener {
@@ -174,7 +171,7 @@ struct PayloadListener {
// payload.
// payload - The Payload object received.
std::function<void(const std::string& endpoint_id, Payload payload)>
payload_cb = DefaultCallback<const std::string&, Payload>();
payload_cb = [](const std::string&, Payload) {};
// Called with progress information about an active Payload transfer, either
// incoming or outgoing.
@@ -186,7 +183,7 @@ struct PayloadListener {
std::function<void(const std::string& endpoint_id,
const PayloadProgressInfo& info)>
payload_progress_cb =
DefaultCallback<const std::string&, const PayloadProgressInfo&>();
[](const std::string&, const PayloadProgressInfo&) {};
};
} // namespace connections
+4 -1
View File
@@ -180,6 +180,7 @@ cc_library(
":logging",
"//proto:connections_enums_cc_proto",
"//proto/errorcode:error_code_enums_cc_proto",
"@com_google_absl//absl/functional:any_invocable",
],
)
@@ -354,12 +355,13 @@ cc_library(
":base",
":logging",
":util",
"//internal/crypto",
"//internal/platform/implementation:platform",
"//internal/platform/implementation:types",
"@com_google_absl//absl/base:core_headers",
"@com_google_absl//absl/container:flat_hash_map",
"@com_google_absl//absl/functional:any_invocable",
"@com_google_absl//absl/log:check",
"@com_google_absl//absl/random",
"@com_google_absl//absl/synchronization",
"@com_google_absl//absl/time",
"@com_google_glog//:glog",
@@ -414,6 +416,7 @@ cc_library(
"//internal/platform/implementation:comm",
"//internal/platform/implementation:platform",
"@com_google_absl//absl/container:flat_hash_map",
"@com_google_absl//absl/functional:any_invocable",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/types:optional",
],
+10 -10
View File
@@ -16,14 +16,14 @@
#define PLATFORM_PUBLIC_BLE_H_
#include "absl/container/flat_hash_map.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/platform.h"
#include "internal/platform/bluetooth_adapter.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/cancellation_flag.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/platform.h"
#include "internal/platform/input_stream.h"
#include "internal/platform/output_stream.h"
#include "internal/platform/bluetooth_adapter.h"
#include "internal/platform/mutex.h"
#include "internal/platform/output_stream.h"
namespace nearby {
@@ -85,14 +85,14 @@ class BleMedium final {
public:
using Platform = api::ImplementationPlatform;
struct DiscoveredPeripheralCallback {
std::function<void(BlePeripheral& peripheral, const std::string& service_id,
const ByteArray& advertisement_bytes,
bool fast_advertisement)>
absl::AnyInvocable<void(
BlePeripheral& peripheral, const std::string& service_id,
const ByteArray& advertisement_bytes, bool fast_advertisement)>
peripheral_discovered_cb =
DefaultCallback<BlePeripheral&, const std::string&,
const ByteArray&, bool>();
std::function<void(BlePeripheral& peripheral,
const std::string& service_id)>
absl::AnyInvocable<void(BlePeripheral& peripheral,
const std::string& service_id)>
peripheral_lost_cb =
DefaultCallback<BlePeripheral&, const std::string&>();
};
@@ -101,7 +101,7 @@ class BleMedium final {
};
struct AcceptedConnectionCallback {
std::function<void(BleSocket& socket, const std::string& service_id)>
absl::AnyInvocable<void(BleSocket& socket, const std::string& service_id)>
accepted_cb = DefaultCallback<BleSocket&, const std::string&>();
};
struct AcceptedConnectionInfo {
+31 -23
View File
@@ -15,11 +15,11 @@
#ifndef PLATFORM_PUBLIC_BLE_V2_H_
#define PLATFORM_PUBLIC_BLE_V2_H_
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include "absl/functional/any_invocable.h"
#include "absl/types/optional.h"
#include "internal/platform/bluetooth_adapter.h"
#include "internal/platform/byte_array.h"
@@ -37,8 +37,9 @@ namespace nearby {
class BleV2Socket final {
public:
BleV2Socket() = default;
explicit BleV2Socket(std::unique_ptr<api::ble_v2::BleSocket> socket)
: impl_(std::move(socket)) {}
explicit BleV2Socket(std::unique_ptr<api::ble_v2::BleSocket> socket) {
state_->socket = std::move(socket);
}
BleV2Socket(const BleV2Socket&) = default;
BleV2Socket& operator=(const BleV2Socket&) = default;
@@ -47,32 +48,32 @@ class BleV2Socket final {
//
// The returned object is not owned by the caller, and can be invalidated once
// the BleSocket object is destroyed.
InputStream& GetInputStream() { return impl_->GetInputStream(); }
InputStream& GetInputStream() { return state_->socket->GetInputStream(); }
// Returns the OutputStream of the BleSocket.
// On error, returned stream will report Exception::kIo on any operation.
//
// The returned object is not owned by the caller, and can be invalidated once
// the BleSocket object is destroyed.
OutputStream& GetOutputStream() { return impl_->GetOutputStream(); }
OutputStream& GetOutputStream() { return state_->socket->GetOutputStream(); }
// Sets the close notifier by client side.
void SetCloseNotifier(std::function<void()> notifier) {
close_notifier_ = std::move(notifier);
void SetCloseNotifier(absl::AnyInvocable<void()> notifier) {
state_->close_notifier = std::move(notifier);
}
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
Exception Close() {
if (close_notifier_) {
auto notifier = std::move(close_notifier_);
if (state_->close_notifier) {
auto notifier = std::move(state_->close_notifier);
notifier();
}
return impl_->Close();
return state_->socket->Close();
}
// Returns BlePeripheral object which wraps a valid BlePeripheral pointer.
BleV2Peripheral GetRemotePeripheral() {
return BleV2Peripheral(impl_->GetRemotePeripheral());
return BleV2Peripheral(state_->socket->GetRemotePeripheral());
}
// Returns true if a socket is usable. If this method returns false,
@@ -84,18 +85,21 @@ class BleV2Socket final {
// an object returned by BleMedium::Connect
// These methods may also return an invalid socket if connection failed for
// any reason.
bool IsValid() const { return impl_ != nullptr; }
bool IsValid() const { return state_->socket != nullptr; }
// Returns reference to platform implementation.
// This is used to communicate with platform code, and for debugging purposes.
// Returned reference will remain valid for while BleSocket object is
// itself valid. Typically BleSocket lifetime matches duration of the
// connection, and is controlled by end user, since they hold the instance.
api::ble_v2::BleSocket& GetImpl() { return *impl_; }
api::ble_v2::BleSocket& GetImpl() { return *state_->socket; }
private:
std::function<void()> close_notifier_;
std::shared_ptr<api::ble_v2::BleSocket> impl_;
struct SharedState {
std::unique_ptr<api::ble_v2::BleSocket> socket;
absl::AnyInvocable<void()> close_notifier;
};
std::shared_ptr<SharedState> state_ = std::make_shared<SharedState>();
};
// Container of operations that can be performed over the BLE GATT server
@@ -176,7 +180,8 @@ class GattServer final {
bool IsValid() const { return impl_ != nullptr; }
// Returns reference to platform implementation.
// This is used to communicate with platform code, and for debugging purposes.
// This is used to communicate with platform code, and for debugging
// purposes.
api::ble_v2::GattServer* GetImpl() { return impl_.get(); }
private:
@@ -213,12 +218,13 @@ class GattClient final {
void Disconnect() { impl_->Disconnect(); }
// Returns true if a client_gatt_connection is usable. If this method returns
// false, it is not safe to call any other method.
// Returns true if a client_gatt_connection is usable. If this method
// returns false, it is not safe to call any other method.
bool IsValid() const { return impl_ != nullptr; }
// Returns reference to platform implementation.
// This is used to communicate with platform code, and for debugging purposes.
// This is used to communicate with platform code, and for debugging
// purposes.
api::ble_v2::GattClient* GetImpl() { return impl_.get(); }
private:
@@ -237,7 +243,7 @@ class BleV2Medium final {
// connection, and is controlled by primitive client, since they hold the
// instance.
struct ScanCallback {
std::function<void(
absl::AnyInvocable<void(
BleV2Peripheral peripheral,
const api::ble_v2::BleAdvertisementData& advertisement_data)>
advertisement_found_cb =
@@ -245,17 +251,19 @@ class BleV2Medium final {
const api::ble_v2::BleAdvertisementData&>();
};
struct ServerGattConnectionCallback {
std::function<void(const api::ble_v2::GattCharacteristic& characteristic)>
absl::AnyInvocable<void(
const api::ble_v2::GattCharacteristic& characteristic)>
characteristic_subscription_cb =
nearby::DefaultCallback<const api::ble_v2::GattCharacteristic&>();
std::function<void(const api::ble_v2::GattCharacteristic& characteristic)>
absl::AnyInvocable<void(
const api::ble_v2::GattCharacteristic& characteristic)>
characteristic_unsubscription_cb =
nearby::DefaultCallback<const api::ble_v2::GattCharacteristic&>();
};
// TODO(b/231318879): Remove this wrapper callback and use impl callback if
// there is only disconnect function here in the end.
struct ClientGattConnectionCallback {
std::function<void()> disconnected_cb = nearby::DefaultCallback<>();
absl::AnyInvocable<void()> disconnected_cb = nearby::DefaultCallback<>();
};
explicit BleV2Medium(BluetoothAdapter& adapter)
+24 -36
View File
@@ -14,7 +14,6 @@
#include "internal/platform/ble_v2.h"
#include <functional>
#include <memory>
#include <string>
#include <utility>
@@ -339,18 +338,15 @@ TEST_F(BleV2MediumTest, StartThenStopAsyncScanning) {
Uuid service_uuid(1234, 5678);
CountDownLatch found_latch_a(1);
std::function<void(api::ble_v2::BlePeripheral&, BleAdvertisementData)>
advertisement_found_cb_a =
[&found_latch_a](api::ble_v2::BlePeripheral& peripheral,
BleAdvertisementData advertisement_data) -> void {
found_latch_a.CountDown();
};
std::unique_ptr<api::ble_v2::BleMedium::ScanningSession> scanning_session_a =
ble_a.StartScanning(
service_uuid, kTxPowerLevel,
api::ble_v2::BleMedium::ScanningCallback{
.advertisement_found_cb = advertisement_found_cb_a,
.advertisement_found_cb =
[&](api::ble_v2::BlePeripheral& peripheral,
BleAdvertisementData advertisement_data) -> void {
found_latch_a.CountDown();
},
});
EXPECT_TRUE(env_.GetBleV2MediumStatus(*ble_a.GetImpl()).value().is_scanning);
@@ -368,31 +364,25 @@ TEST_F(BleV2MediumTest, CanStartMultipleAsyncScanning) {
CountDownLatch found_latch_a(1);
CountDownLatch found_latch_b(1);
std::function<void(api::ble_v2::BlePeripheral&, BleAdvertisementData)>
advertisement_found_cb_a =
[&found_latch_a](api::ble_v2::BlePeripheral& peripheral,
BleAdvertisementData advertisement_data) -> void {
found_latch_a.CountDown();
};
std::function<void(api::ble_v2::BlePeripheral&, BleAdvertisementData)>
advertisement_found_cb_b =
[&found_latch_b](api::ble_v2::BlePeripheral& peripheral,
BleAdvertisementData advertisement_data) -> void {
found_latch_b.CountDown();
};
std::unique_ptr<api::ble_v2::BleMedium::ScanningSession> scanning_session_a =
ble_a.StartScanning(
service_uuid, kTxPowerLevel,
api::ble_v2::BleMedium::ScanningCallback{
.advertisement_found_cb = advertisement_found_cb_a,
.advertisement_found_cb =
[&](api::ble_v2::BlePeripheral& peripheral,
BleAdvertisementData advertisement_data) -> void {
found_latch_a.CountDown();
},
});
std::unique_ptr<api::ble_v2::BleMedium::ScanningSession> scanning_session_b =
ble_b.StartScanning(
service_uuid, kTxPowerLevel,
api::ble_v2::BleMedium::ScanningCallback{
.advertisement_found_cb = advertisement_found_cb_b,
.advertisement_found_cb =
[&](api::ble_v2::BlePeripheral& peripheral,
BleAdvertisementData advertisement_data) -> void {
found_latch_b.CountDown();
},
});
EXPECT_TRUE(env_.GetBleV2MediumStatus(*ble_a.GetImpl()).value().is_scanning);
@@ -417,18 +407,16 @@ TEST_F(BleV2MediumTest, CanStartAsyncScanningAndAdvertising) {
ByteArray advertisement_header_bytes{std::string(kAdvertisementHeaderString)};
CountDownLatch found_latch(1);
std::function<void(api::ble_v2::BlePeripheral&, BleAdvertisementData)>
advertisement_found_cb =
[&found_latch](api::ble_v2::BlePeripheral& peripheral,
BleAdvertisementData advertisement_data) -> void {
found_latch.CountDown();
};
std::unique_ptr<api::ble_v2::BleMedium::ScanningSession> scanning_session =
ble_a.StartScanning(service_uuid, kTxPowerLevel,
api::ble_v2::BleMedium::ScanningCallback{
.advertisement_found_cb = advertisement_found_cb,
});
ble_a.StartScanning(
service_uuid, kTxPowerLevel,
api::ble_v2::BleMedium::ScanningCallback{
.advertisement_found_cb =
[&](api::ble_v2::BlePeripheral& peripheral,
BleAdvertisementData advertisement_data) -> void {
found_latch.CountDown();
},
});
// Succeed to start regular advertisement.
BleAdvertisementData advertising_data;
+7 -7
View File
@@ -19,17 +19,17 @@
#include <string>
#include "absl/container/flat_hash_map.h"
#include "internal/platform/implementation/bluetooth_classic.h"
#include "internal/platform/implementation/platform.h"
#include "internal/platform/bluetooth_adapter.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/cancellation_flag.h"
#include "internal/platform/exception.h"
#include "internal/platform/implementation/bluetooth_classic.h"
#include "internal/platform/implementation/platform.h"
#include "internal/platform/input_stream.h"
#include "internal/platform/listeners.h"
#include "internal/platform/output_stream.h"
#include "internal/platform/bluetooth_adapter.h"
#include "internal/platform/logging.h"
#include "internal/platform/mutex.h"
#include "internal/platform/output_stream.h"
namespace nearby {
@@ -137,11 +137,11 @@ class BluetoothClassicMedium final {
// and at any time afterwards, until device_lost_cb() is called.
// It is not safe to use BluetoothDevice after returning from
// device_lost_cb() callback.
std::function<void(BluetoothDevice& device)> device_discovered_cb =
absl::AnyInvocable<void(BluetoothDevice& device)> device_discovered_cb =
DefaultCallback<BluetoothDevice&>();
std::function<void(BluetoothDevice& device)> device_name_changed_cb =
absl::AnyInvocable<void(BluetoothDevice& device)> device_name_changed_cb =
DefaultCallback<BluetoothDevice&>();
std::function<void(BluetoothDevice& device)> device_lost_cb =
absl::AnyInvocable<void(BluetoothDevice& device)> device_lost_cb =
DefaultCallback<BluetoothDevice&>();
};
struct DeviceDiscoveryInfo {
+2 -3
View File
@@ -15,8 +15,7 @@
#ifndef PLATFORM_BASE_CALLABLE_H_
#define PLATFORM_BASE_CALLABLE_H_
#include <functional>
#include "absl/functional/any_invocable.h"
#include "internal/platform/exception.h"
namespace nearby {
@@ -28,7 +27,7 @@ namespace nearby {
//
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Callable.html
template <typename T>
using Callable = std::function<ExceptionOr<T>()>;
using Callable = absl::AnyInvocable<ExceptionOr<T>()>;
} // namespace nearby
+3 -3
View File
@@ -16,11 +16,11 @@
#define PLATFORM_PUBLIC_CANCELABLE_ALARM_H_
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include "absl/functional/any_invocable.h"
#include "internal/platform/cancelable.h"
#include "internal/platform/mutex.h"
#include "internal/platform/mutex_lock.h"
@@ -36,7 +36,7 @@ namespace nearby {
class CancelableAlarm {
public:
CancelableAlarm() = default;
CancelableAlarm(absl::string_view name, std::function<void()>&& runnable,
CancelableAlarm(absl::string_view name, absl::AnyInvocable<void()>&& runnable,
absl::Duration delay, ScheduledExecutor* scheduled_executor,
bool is_recurring = false)
: name_(name), scheduled_executor_(scheduled_executor), delay_(delay) {
@@ -75,7 +75,7 @@ class CancelableAlarm {
Cancelable cancelable_;
ScheduledExecutor* scheduled_executor_;
absl::Duration delay_;
std::function<void()> runnable_;
absl::AnyInvocable<void()> runnable_;
};
} // namespace nearby
+1 -1
View File
@@ -53,7 +53,7 @@ class CancellationFlag {
// function. It conducts that 2 different pointers might point to the same
// callback function which is unusual and should avoid. Hence we make it as
// private and use `CancellationFlagListener` as a RAII to wrap the function.
// The caller should register listener as lambda or std::function
// The caller should register listener as lambda or absl::AnyInvocable
// via `CancellationFlagListener`.
void RegisterOnCancelListener(CancelListener *listener)
ABSL_LOCKS_EXCLUDED(mutex_);
@@ -14,7 +14,6 @@
#include "internal/platform/cancellation_flag.h"
#include <functional>
#include <memory>
#include <utility>
+2 -3
View File
@@ -15,8 +15,7 @@
#ifndef PLATFORM_BASE_ERROR_CODE_RECORDER_H_
#define PLATFORM_BASE_ERROR_CODE_RECORDER_H_
#include <functional>
#include "absl/functional/any_invocable.h"
#include "internal/platform/error_code_params.h"
namespace nearby {
@@ -27,7 +26,7 @@ namespace nearby {
// medium platform supported whenever error occurred.
class ErrorCodeRecorder {
public:
using ErrorCodeListener = std::function<void(const ErrorCodeParams&)>;
using ErrorCodeListener = absl::AnyInvocable<void(const ErrorCodeParams&)>;
explicit ErrorCodeRecorder(ErrorCodeListener listener) {
listener_ = std::move(listener);
@@ -14,6 +14,8 @@
#include "internal/platform/error_code_recorder.h"
#include <utility>
#include "gmock/gmock.h"
#include "protobuf-matchers/protocol-buffer-matchers.h"
#include "gtest/gtest.h"
@@ -26,9 +28,8 @@ using ::testing::StrictMock;
TEST(ErrorCodeRecorderTest, TestListenerWork) {
StrictMock<MockFunction<void(const ErrorCodeParams& params)>> mock_listener;
ErrorCodeRecorder::ErrorCodeListener listener = mock_listener.AsStdFunction();
EXPECT_CALL(mock_listener, Call).Times(1);
ErrorCodeRecorder error_code_recorder(listener);
ErrorCodeRecorder error_code_recorder(mock_listener.AsStdFunction());
ErrorCodeRecorder::LogErrorCode(
location::nearby::proto::connections::BLE,
+1
View File
@@ -47,6 +47,7 @@ cc_library(
deps = [
"//internal/platform:base",
"@com_google_absl//absl/base:core_headers",
"@com_google_absl//absl/functional:any_invocable",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/time",
],
+2 -2
View File
@@ -100,7 +100,7 @@ class BleServerSocket : public api::ble_v2::BleServerSocket {
Exception Close() override ABSL_LOCKS_EXCLUDED(mutex_);
bool Connect(std::unique_ptr<BleSocket> socket) ABSL_LOCKS_EXCLUDED(mutex_);
void SetCloseNotifier(std::function<void()> notifier) ABSL_LOCKS_EXCLUDED(mutex_);
void SetCloseNotifier(absl::AnyInvocable<void()> notifier) ABSL_LOCKS_EXCLUDED(mutex_);
private:
Exception DoClose() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
@@ -108,7 +108,7 @@ class BleServerSocket : public api::ble_v2::BleServerSocket {
mutable absl::Mutex mutex_;
absl::CondVar cond_;
absl::flat_hash_set<std::unique_ptr<BleSocket>> pending_sockets_ ABSL_GUARDED_BY(mutex_);
std::function<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
absl::AnyInvocable<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
bool closed_ ABSL_GUARDED_BY(mutex_) = false;
};
@@ -15,7 +15,7 @@
#import "internal/platform/implementation/apple/ble.h"
#include <CoreBluetooth/CoreBluetooth.h>
#include <functional>
#include <string>
#include <utility>
@@ -283,7 +283,7 @@ bool BleServerSocket::Connect(std::unique_ptr<BleSocket> socket) {
return true;
}
void BleServerSocket::SetCloseNotifier(std::function<void()> notifier) {
void BleServerSocket::SetCloseNotifier(absl::AnyInvocable<void()> notifier) {
absl::MutexLock lock(&mutex_);
close_notifier_ = std::move(notifier);
}
@@ -18,7 +18,6 @@
#import <Foundation/Foundation.h>
#include <functional>
#include <memory>
#include "internal/platform/implementation/scheduled_executor.h"
@@ -16,7 +16,6 @@
#define PLATFORM_IMPL_APPLE_TIMER_H_
#ifdef __cplusplus
#include <functional>
#include <utility>
#include "internal/platform/implementation/timer.h"
@@ -29,7 +28,8 @@ class Timer : public api::Timer {
Timer() = default;
~Timer() override = default;
bool Create(int delay, int interval, std::function<void()> callback) override;
bool Create(int delay, int interval,
absl::AnyInvocable<void()> callback) override;
bool Stop() override;
@@ -14,7 +14,6 @@
#import "internal/platform/implementation/apple/timer.h"
#include <functional>
#include <utility>
#include "internal/platform/implementation/timer.h"
@@ -22,7 +21,7 @@
namespace nearby {
namespace apple {
bool Timer::Create(int delay, int interval, std::function<void()> callback) { return true; }
bool Timer::Create(int delay, int interval, absl::AnyInvocable<void()> callback) { return true; }
bool Timer::Stop() { return true; }
@@ -116,7 +116,7 @@ class WifiLanServerSocket : public api::WifiLanServerSocket {
Exception Close() override ABSL_LOCKS_EXCLUDED(mutex_);
bool Connect(std::unique_ptr<WifiLanSocket> socket) ABSL_LOCKS_EXCLUDED(mutex_);
void SetCloseNotifier(std::function<void()> notifier) ABSL_LOCKS_EXCLUDED(mutex_);
void SetCloseNotifier(absl::AnyInvocable<void()> notifier) ABSL_LOCKS_EXCLUDED(mutex_);
private:
Exception DoClose() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
@@ -126,7 +126,7 @@ class WifiLanServerSocket : public api::WifiLanServerSocket {
int port_ ABSL_GUARDED_BY(mutex_);
absl::CondVar cond_;
absl::flat_hash_set<std::unique_ptr<WifiLanSocket>> pending_sockets_ ABSL_GUARDED_BY(mutex_);
std::function<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
absl::AnyInvocable<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
bool closed_ ABSL_GUARDED_BY(mutex_) = false;
};
@@ -255,7 +255,7 @@ bool WifiLanServerSocket::Connect(std::unique_ptr<WifiLanSocket> socket) {
return true;
}
void WifiLanServerSocket::SetCloseNotifier(std::function<void()> notifier) {
void WifiLanServerSocket::SetCloseNotifier(absl::AnyInvocable<void()> notifier) {
absl::MutexLock lock(&mutex_);
close_notifier_ = std::move(notifier);
}
@@ -361,6 +361,7 @@ bool WifiLanMedium::StartDiscovery(const std::string& service_type,
return false;
}
}
__block DiscoveredServiceCallback client_callback = std::move(callback);
GNCMBonjourBrowser* browser = [[GNCMBonjourBrowser alloc]
initWithServiceType:serviceType
endpointFoundHandler:^GNCMEndpointLostHandler(
@@ -376,9 +377,9 @@ bool WifiLanMedium::StartDiscovery(const std::string& service_type,
nsd_service_info.SetTxtRecords(txt_records);
}
connection_requesters_.insert({CppStringFromObjCString(serviceType), requestConnection});
callback.service_discovered_cb(nsd_service_info);
client_callback.service_discovered_cb(nsd_service_info);
return ^{
callback.service_lost_cb(nsd_service_info);
client_callback.service_lost_cb(nsd_service_info);
};
}];
{
+7 -6
View File
@@ -15,9 +15,9 @@
#ifndef PLATFORM_API_BLE_H_
#define PLATFORM_API_BLE_H_
#include "internal/platform/implementation/bluetooth_classic.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/cancellation_flag.h"
#include "internal/platform/implementation/bluetooth_classic.h"
#include "internal/platform/input_stream.h"
#include "internal/platform/output_stream.h"
@@ -77,12 +77,13 @@ class BleMedium {
// Callback that is invoked when a discovered peripheral is found or lost.
struct DiscoveredPeripheralCallback {
std::function<void(BlePeripheral& peripheral, const std::string& service_id,
bool fast_advertisement)>
absl::AnyInvocable<void(BlePeripheral& peripheral,
const std::string& service_id,
bool fast_advertisement)>
peripheral_discovered_cb =
DefaultCallback<BlePeripheral&, const std::string&, bool>();
std::function<void(BlePeripheral& peripheral,
const std::string& service_id)>
absl::AnyInvocable<void(BlePeripheral& peripheral,
const std::string& service_id)>
peripheral_lost_cb =
DefaultCallback<BlePeripheral&, const std::string&>();
};
@@ -99,7 +100,7 @@ class BleMedium {
// Callback that is invoked when a new connection is accepted.
struct AcceptedConnectionCallback {
std::function<void(BleSocket& socket, const std::string& service_id)>
absl::AnyInvocable<void(BleSocket& socket, const std::string& service_id)>
accepted_cb = DefaultCallback<BleSocket&, const std::string&>();
};
@@ -17,7 +17,6 @@
#include <algorithm>
#include <cstdint>
#include <functional>
#include <limits>
#include <map>
#include <memory>
@@ -103,11 +103,11 @@ class BluetoothClassicMedium {
// and at any time afterwards, until device_lost_cb() is called.
// It is not safe to use BluetoothDevice after returning from
// device_lost_cb() callback.
std::function<void(BluetoothDevice& device)> device_discovered_cb =
absl::AnyInvocable<void(BluetoothDevice& device)> device_discovered_cb =
DefaultCallback<BluetoothDevice&>();
std::function<void(BluetoothDevice& device)> device_name_changed_cb =
absl::AnyInvocable<void(BluetoothDevice& device)> device_name_changed_cb =
DefaultCallback<BluetoothDevice&>();
std::function<void(BluetoothDevice& device)> device_lost_cb =
absl::AnyInvocable<void(BluetoothDevice& device)> device_lost_cb =
DefaultCallback<BluetoothDevice&>();
};
@@ -15,7 +15,6 @@
#ifndef THIRD_PARTY_NEARBY_INTERNAL_PLATFORM_IMPLEMENTATION_CREDENTIAL_CALLBACKS_H_
#define THIRD_PARTY_NEARBY_INTERNAL_PLATFORM_IMPLEMENTATION_CREDENTIAL_CALLBACKS_H_
#include <functional>
#include <ostream>
#include <string>
#include <vector>
@@ -15,7 +15,6 @@
#ifndef THIRD_PARTY_NEARBY_INTERNAL_PLATFORM_IMPLEMENTATION_CREDENTIAL_STORAGE_H_
#define THIRD_PARTY_NEARBY_INTERNAL_PLATFORM_IMPLEMENTATION_CREDENTIAL_STORAGE_H_
#include <functional>
#include <string>
#include <vector>
+5 -4
View File
@@ -19,11 +19,11 @@
#include <string>
#include "absl/synchronization/mutex.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/cancellation_flag_listener.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/shared/count_down_latch.h"
#include "internal/platform/logging.h"
#include "internal/platform/medium_environment.h"
#include "internal/platform/implementation/shared/count_down_latch.h"
namespace nearby {
namespace g3 {
@@ -135,7 +135,7 @@ bool BleServerSocket::Connect(BleSocket& socket) {
return true;
}
void BleServerSocket::SetCloseNotifier(std::function<void()> notifier) {
void BleServerSocket::SetCloseNotifier(absl::AnyInvocable<void()> notifier) {
absl::MutexLock lock(&mutex_);
close_notifier_ = std::move(notifier);
}
@@ -303,7 +303,8 @@ bool BleMedium::StartAcceptingConnections(const std::string& service_id,
NEARBY_LOGS(INFO) << "G3 Ble StartAcceptingConnections: service_id="
<< service_id;
auto& env = MediumEnvironment::Instance();
env.UpdateBleMediumForAcceptedConnection(*this, service_id, callback);
env.UpdateBleMediumForAcceptedConnection(*this, service_id,
std::move(callback));
return true;
}
+5 -5
View File
@@ -22,14 +22,14 @@
#include "absl/container/flat_hash_set.h"
#include "absl/strings/escaping.h"
#include "absl/synchronization/mutex.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/input_stream.h"
#include "internal/platform/output_stream.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/g3/bluetooth_adapter.h"
#include "internal/platform/implementation/g3/bluetooth_classic.h"
#include "internal/platform/implementation/g3/multi_thread_executor.h"
#include "internal/platform/implementation/g3/pipe.h"
#include "internal/platform/input_stream.h"
#include "internal/platform/output_stream.h"
namespace nearby {
namespace g3 {
@@ -125,7 +125,7 @@ class BleServerSocket {
// Called by the server side of a connection before passing ownership of
// BleServerSocker to user, to track validity of a pointer to this
// server socket,
void SetCloseNotifier(std::function<void()> notifier)
void SetCloseNotifier(absl::AnyInvocable<void()> notifier)
ABSL_LOCKS_EXCLUDED(mutex_);
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
@@ -138,7 +138,7 @@ class BleServerSocket {
absl::Mutex mutex_;
absl::CondVar cond_;
absl::flat_hash_set<BleSocket*> pending_sockets_ ABSL_GUARDED_BY(mutex_);
std::function<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
absl::AnyInvocable<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
bool closed_ ABSL_GUARDED_BY(mutex_) = false;
};
@@ -15,7 +15,6 @@
#include "internal/platform/implementation/g3/ble_v2.h"
#include <cstdint>
#include <functional>
#include <iostream>
#include <memory>
#include <optional>
@@ -166,7 +165,7 @@ bool BleV2ServerSocket::Connect(BleV2Socket& socket) {
return true;
}
void BleV2ServerSocket::SetCloseNotifier(std::function<void()> notifier) {
void BleV2ServerSocket::SetCloseNotifier(absl::AnyInvocable<void()> notifier) {
absl::MutexLock lock(&mutex_);
close_notifier_ = std::move(notifier);
}
+2 -3
View File
@@ -16,7 +16,6 @@
#define PLATFORM_IMPL_G3_BLE_V2_H_
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <string>
@@ -133,7 +132,7 @@ class BleV2ServerSocket : public api::ble_v2::BleServerSocket {
// Called by the server side of a connection before passing ownership of
// BleServerSocker to user, to track validity of a pointer to this
// server socket.
void SetCloseNotifier(std::function<void()> notifier)
void SetCloseNotifier(absl::AnyInvocable<void()> notifier)
ABSL_LOCKS_EXCLUDED(mutex_);
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
@@ -147,7 +146,7 @@ class BleV2ServerSocket : public api::ble_v2::BleServerSocket {
absl::CondVar cond_;
BluetoothAdapter* adapter_ = nullptr; // Our Adapter. Read only.
absl::flat_hash_set<BleV2Socket*> pending_sockets_ ABSL_GUARDED_BY(mutex_);
std::function<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
absl::AnyInvocable<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
bool closed_ ABSL_GUARDED_BY(mutex_) = false;
};
@@ -18,11 +18,11 @@
#include <string>
#include "absl/synchronization/mutex.h"
#include "internal/platform/implementation/bluetooth_classic.h"
#include "internal/platform/cancellation_flag_listener.h"
#include "internal/platform/implementation/bluetooth_classic.h"
#include "internal/platform/implementation/g3/bluetooth_adapter.h"
#include "internal/platform/logging.h"
#include "internal/platform/medium_environment.h"
#include "internal/platform/implementation/g3/bluetooth_adapter.h"
namespace nearby {
namespace g3 {
@@ -139,7 +139,8 @@ bool BluetoothServerSocket::Connect(BluetoothSocket& socket) {
return true;
}
void BluetoothServerSocket::SetCloseNotifier(std::function<void()> notifier) {
void BluetoothServerSocket::SetCloseNotifier(
absl::AnyInvocable<void()> notifier) {
absl::MutexLock lock(&mutex_);
close_notifier_ = std::move(notifier);
}
@@ -21,14 +21,14 @@
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/synchronization/mutex.h"
#include "internal/platform/implementation/bluetooth_classic.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/exception.h"
#include "internal/platform/implementation/bluetooth_classic.h"
#include "internal/platform/implementation/g3/bluetooth_adapter.h"
#include "internal/platform/implementation/g3/pipe.h"
#include "internal/platform/input_stream.h"
#include "internal/platform/listeners.h"
#include "internal/platform/output_stream.h"
#include "internal/platform/implementation/g3/bluetooth_adapter.h"
#include "internal/platform/implementation/g3/pipe.h"
namespace nearby {
namespace g3 {
@@ -137,7 +137,7 @@ class BluetoothServerSocket : public api::BluetoothServerSocket {
// Called by the server side of a connection before passing ownership of
// BluetoothServerSocker to user, to track validity of a pointer to this
// server socket,
void SetCloseNotifier(std::function<void()> notifier)
void SetCloseNotifier(absl::AnyInvocable<void()> notifier)
ABSL_LOCKS_EXCLUDED(mutex_);
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
@@ -152,7 +152,7 @@ class BluetoothServerSocket : public api::BluetoothServerSocket {
BluetoothAdapter* adapter_ = nullptr; // Our Adapter. Read only.
absl::flat_hash_set<BluetoothSocket*> pending_sockets_
ABSL_GUARDED_BY(mutex_);
std::function<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
absl::AnyInvocable<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
bool closed_ ABSL_GUARDED_BY(mutex_) = false;
};
+2 -3
View File
@@ -15,7 +15,6 @@
#ifndef PLATFORM_IMPL_G3_TIMER_H_
#define PLATFORM_IMPL_G3_TIMER_H_
#include <functional>
#include <utility>
#include "internal/platform/implementation/timer.h"
@@ -29,7 +28,7 @@ class Timer : public api::Timer {
~Timer() override = default;
bool Create(int delay, int interval,
std::function<void()> callback) override {
absl::AnyInvocable<void()> callback) override {
if (delay < 0 || interval < 0) {
return false;
}
@@ -61,7 +60,7 @@ class Timer : public api::Timer {
}
private:
std::function<void()> callback_;
absl::AnyInvocable<void()> callback_;
bool is_stopped_ = false;
};
@@ -15,6 +15,7 @@
#include "internal/platform/implementation/g3/webrtc.h"
#include <memory>
#include <utility>
#include "internal/platform/medium_environment.h"
#include "webrtc/api/task_queue/default_task_queue_factory.h"
@@ -39,8 +40,8 @@ bool WebRtcSignalingMessenger::StartReceivingMessages(
OnSignalingMessageCallback on_message_callback,
OnSignalingCompleteCallback on_complete_callback) {
auto& env = MediumEnvironment::Instance();
env.RegisterWebRtcSignalingMessenger(self_id_, on_message_callback,
on_complete_callback);
env.RegisterWebRtcSignalingMessenger(self_id_, std::move(on_message_callback),
std::move(on_complete_callback));
return true;
}
@@ -83,7 +84,7 @@ void WebRtcMedium::CreatePeerConnection(
single_thread_executor_.Execute(
[&env, callback = std::move(callback),
peer_connection = peer_connection_or_error.MoveValue()]() {
peer_connection = peer_connection_or_error.MoveValue()]() mutable {
absl::SleepFor(env.GetPeerConnectionLatency());
callback(peer_connection);
});
@@ -14,7 +14,6 @@
#include "internal/platform/implementation/g3/wifi_direct.h"
#include <functional>
#include <iostream>
#include <memory>
#include <optional>
@@ -30,7 +29,6 @@
namespace nearby {
namespace g3 {
// Code for WifiDirectSocket
WifiDirectSocket::~WifiDirectSocket() {
absl::MutexLock lock(&mutex_);
@@ -94,7 +92,7 @@ OutputStream& WifiDirectSocket::GetLocalOutputStream() {
// Code for WifiDirectServerSocket
std::string WifiDirectServerSocket::GetName(absl::string_view ip_address,
int port) {
int port) {
return absl::StrCat(ip_address, ":", port);
}
@@ -134,7 +132,8 @@ bool WifiDirectServerSocket::Connect(WifiDirectSocket& socket) {
return true;
}
void WifiDirectServerSocket::SetCloseNotifier(std::function<void()> notifier) {
void WifiDirectServerSocket::SetCloseNotifier(
absl::AnyInvocable<void()> notifier) {
absl::MutexLock lock(&mutex_);
close_notifier_ = std::move(notifier);
}
@@ -291,8 +290,8 @@ std::unique_ptr<api::WifiDirectSocket> WifiDirectMedium::ConnectToService(
return socket;
}
std::unique_ptr<api::WifiDirectServerSocket>
WifiDirectMedium::ListenForService(int port) {
std::unique_ptr<api::WifiDirectServerSocket> WifiDirectMedium::ListenForService(
int port) {
auto& env = MediumEnvironment::Instance();
auto server_socket = std::make_unique<WifiDirectServerSocket>();
@@ -15,7 +15,6 @@
#ifndef PLATFORM_IMPL_G3_WIFI_DIRECT_H_
#define PLATFORM_IMPL_G3_WIFI_DIRECT_H_
#include <functional>
#include <memory>
#include <optional>
#include <string>
@@ -144,7 +143,7 @@ class WifiDirectServerSocket : public api::WifiDirectServerSocket {
// Called by the server side of a connection before passing ownership of
// WifiDirectServerSocker to user, to track validity of a pointer to this
// server socket.
void SetCloseNotifier(std::function<void()> notifier)
void SetCloseNotifier(absl::AnyInvocable<void()> notifier)
ABSL_LOCKS_EXCLUDED(mutex_);
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
@@ -164,7 +163,7 @@ class WifiDirectServerSocket : public api::WifiDirectServerSocket {
absl::CondVar cond_;
absl::flat_hash_set<WifiDirectSocket*> pending_sockets_
ABSL_GUARDED_BY(mutex_);
std::function<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
absl::AnyInvocable<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
bool closed_ ABSL_GUARDED_BY(mutex_) = false;
};
@@ -14,7 +14,6 @@
#include "internal/platform/implementation/g3/wifi_hotspot.h"
#include <functional>
#include <iostream>
#include <memory>
#include <optional>
@@ -23,8 +22,8 @@
#include "absl/strings/str_format.h"
#include "absl/synchronization/mutex.h"
#include "internal/platform/implementation/wifi_hotspot.h"
#include "internal/platform/cancellation_flag_listener.h"
#include "internal/platform/implementation/wifi_hotspot.h"
#include "internal/platform/logging.h"
#include "internal/platform/medium_environment.h"
@@ -99,7 +98,7 @@ OutputStream& WifiHotspotSocket::GetLocalOutputStream() {
// Code for WifiHotspotServerSocket
std::string WifiHotspotServerSocket::GetName(absl::string_view ip_address,
int port) {
int port) {
return absl::StrCat(ip_address, ":", port);
}
@@ -139,7 +138,8 @@ bool WifiHotspotServerSocket::Connect(WifiHotspotSocket& socket) {
return true;
}
void WifiHotspotServerSocket::SetCloseNotifier(std::function<void()> notifier) {
void WifiHotspotServerSocket::SetCloseNotifier(
absl::AnyInvocable<void()> notifier) {
absl::MutexLock lock(&mutex_);
close_notifier_ = std::move(notifier);
}
@@ -186,8 +186,7 @@ bool WifiHotspotMedium::StartWifiHotspot(
HotspotCredentials* hotspot_credentials) {
absl::MutexLock lock(&mutex_);
if (!IsInterfaceValid())
return false;
if (!IsInterfaceValid()) return false;
std::string ssid = absl::StrCat("DIRECT-", Prng().NextUint32());
hotspot_credentials->SetSSID(ssid);
@@ -199,7 +198,8 @@ bool WifiHotspotMedium::StartWifiHotspot(
auto& env = MediumEnvironment::Instance();
env.UpdateWifiHotspotMediumForStartOrConnect(*this, hotspot_credentials,
/*is_ap=*/true, /*enabled=*/true);
/*is_ap=*/true,
/*enabled=*/true);
return true;
}
@@ -208,13 +208,12 @@ bool WifiHotspotMedium::StopWifiHotspot() {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << "G3 StopWifiHotspot";
if (!IsInterfaceValid())
return false;
if (!IsInterfaceValid()) return false;
auto& env = MediumEnvironment::Instance();
env.UpdateWifiHotspotMediumForStartOrConnect(*this, /*credentials*/nullptr,
/*is_ap=*/true,
/*enabled=*/false);
env.UpdateWifiHotspotMediumForStartOrConnect(*this, /*credentials*/ nullptr,
/*is_ap=*/true,
/*enabled=*/false);
return true;
}
@@ -230,13 +229,15 @@ bool WifiHotspotMedium::ConnectWifiHotspot(
auto* remote_medium = static_cast<WifiHotspotMedium*>(
env.GetWifiHotspotMedium(hotspot_credentials->GetSSID(), {}));
if (!remote_medium) {
env.UpdateWifiHotspotMediumForStartOrConnect(*this, hotspot_credentials,
/*is_ap=*/false, /*enabled=*/false);
env.UpdateWifiHotspotMediumForStartOrConnect(*this, hotspot_credentials,
/*is_ap=*/false,
/*enabled=*/false);
return false;
}
env.UpdateWifiHotspotMediumForStartOrConnect(*this, hotspot_credentials,
/*is_ap=*/false, /*enabled=*/true);
/*is_ap=*/false,
/*enabled=*/true);
return true;
}
@@ -246,8 +247,9 @@ bool WifiHotspotMedium::DisconnectWifiHotspot() {
NEARBY_LOGS(INFO) << "G3 DisconnectWifiHotspot";
auto& env = MediumEnvironment::Instance();
env.UpdateWifiHotspotMediumForStartOrConnect(*this, /*credentials*/nullptr,
/*is_ap=*/false, /*enabled=*/false);
env.UpdateWifiHotspotMediumForStartOrConnect(*this, /*credentials*/ nullptr,
/*is_ap=*/false,
/*enabled=*/false);
return true;
}
@@ -259,8 +261,8 @@ std::unique_ptr<api::WifiHotspotSocket> WifiHotspotMedium::ConnectToService(
<< ", ip address + port=" << socket_name;
// First, find an instance of remote medium, that exposed this service.
auto& env = MediumEnvironment::Instance();
auto* remote_medium = static_cast<WifiHotspotMedium*>(
env.GetWifiHotspotMedium({}, ip_address));
auto* remote_medium =
static_cast<WifiHotspotMedium*>(env.GetWifiHotspotMedium({}, ip_address));
if (remote_medium == nullptr) {
return {};
}
@@ -318,8 +320,7 @@ WifiHotspotMedium::ListenForService(int port) {
std::string dot_decimal_ip;
std::string ip_address = env.GetFakeIPAddress();
if (ip_address.empty())
return nullptr;
if (ip_address.empty()) return nullptr;
for (auto byte : ip_address) {
absl::StrAppend(&dot_decimal_ip, absl::StrFormat("%d", byte), ".");
@@ -15,19 +15,18 @@
#ifndef PLATFORM_IMPL_G3_WIFI_HOTSPOT_H_
#define PLATFORM_IMPL_G3_WIFI_HOTSPOT_H_
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include "absl/synchronization/mutex.h"
#include "internal/platform/implementation/wifi_hotspot.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/input_stream.h"
#include "internal/platform/output_stream.h"
#include "internal/platform/implementation/g3/multi_thread_executor.h"
#include "internal/platform/implementation/g3/pipe.h"
#include "internal/platform/implementation/wifi_hotspot.h"
#include "internal/platform/input_stream.h"
#include "internal/platform/output_stream.h"
namespace nearby {
namespace g3 {
@@ -64,7 +63,7 @@ class WifiHotspotSocket : public api::WifiHotspotSocket {
// Returns address of a remote WifiHotspotSocket or nullptr.
WifiHotspotSocket* GetRemoteSocket() ABSL_LOCKS_EXCLUDED(mutex_);
// Returns true if connection exists to the (possibly closed) remote socket.
// Returns true if connection exists to the (possibly closed) remote socket.
bool IsConnected() const ABSL_LOCKS_EXCLUDED(mutex_);
// Returns true if socket is closed.
@@ -148,7 +147,7 @@ class WifiHotspotServerSocket : public api::WifiHotspotServerSocket {
// Called by the server side of a connection before passing ownership of
// WifiHotspotServerSocker to user, to track validity of a pointer to this
// server socket.
void SetCloseNotifier(std::function<void()> notifier)
void SetCloseNotifier(absl::AnyInvocable<void()> notifier)
ABSL_LOCKS_EXCLUDED(mutex_);
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
@@ -168,7 +167,7 @@ class WifiHotspotServerSocket : public api::WifiHotspotServerSocket {
absl::CondVar cond_;
absl::flat_hash_set<WifiHotspotSocket*> pending_sockets_
ABSL_GUARDED_BY(mutex_);
std::function<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
absl::AnyInvocable<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
bool closed_ ABSL_GUARDED_BY(mutex_) = false;
};
@@ -184,7 +183,7 @@ class WifiHotspotMedium : public api::WifiHotspotMedium {
WifiHotspotMedium& operator=(WifiHotspotMedium&&) = delete;
// If the WiFi Adaptor supports to start a Hotspot interface.
bool IsInterfaceValid() const override { return true;}
bool IsInterfaceValid() const override { return true; }
// Discoverer connects to server socket
std::unique_ptr<api::WifiHotspotSocket> ConnectToService(
@@ -211,7 +210,7 @@ class WifiHotspotMedium : public api::WifiHotspotMedium {
private:
// Gets error message from exception pointer
// std::string GetErrorMessage(std::exception_ptr eptr);
// std::string GetErrorMessage(std::exception_ptr eptr);
// Protects to access some members
absl::Mutex mutex_;
@@ -220,7 +219,6 @@ class WifiHotspotMedium : public api::WifiHotspotMedium {
ABSL_GUARDED_BY(mutex_);
};
} // namespace g3
} // namespace nearby
@@ -22,8 +22,8 @@
#include "absl/strings/escaping.h"
#include "absl/strings/str_format.h"
#include "absl/synchronization/mutex.h"
#include "internal/platform/implementation/wifi_lan.h"
#include "internal/platform/cancellation_flag_listener.h"
#include "internal/platform/implementation/wifi_lan.h"
#include "internal/platform/logging.h"
#include "internal/platform/medium_environment.h"
#include "internal/platform/nsd_service_info.h"
@@ -146,7 +146,8 @@ bool WifiLanServerSocket::Connect(WifiLanSocket& socket) {
return true;
}
void WifiLanServerSocket::SetCloseNotifier(std::function<void()> notifier) {
void WifiLanServerSocket::SetCloseNotifier(
absl::AnyInvocable<void()> notifier) {
absl::MutexLock lock(&mutex_);
close_notifier_ = std::move(notifier);
}
@@ -22,13 +22,13 @@
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/synchronization/mutex.h"
#include "internal/platform/implementation/wifi_lan.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/implementation/g3/multi_thread_executor.h"
#include "internal/platform/implementation/g3/pipe.h"
#include "internal/platform/implementation/wifi_lan.h"
#include "internal/platform/input_stream.h"
#include "internal/platform/nsd_service_info.h"
#include "internal/platform/output_stream.h"
#include "internal/platform/implementation/g3/multi_thread_executor.h"
#include "internal/platform/implementation/g3/pipe.h"
namespace nearby {
namespace g3 {
@@ -144,7 +144,7 @@ class WifiLanServerSocket : public api::WifiLanServerSocket {
// Called by the server side of a connection before passing ownership of
// WifiLanServerSocker to user, to track validity of a pointer to this
// server socket.
void SetCloseNotifier(std::function<void()> notifier)
void SetCloseNotifier(absl::AnyInvocable<void()> notifier)
ABSL_LOCKS_EXCLUDED(mutex_);
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
@@ -159,7 +159,7 @@ class WifiLanServerSocket : public api::WifiLanServerSocket {
int port_ ABSL_GUARDED_BY(mutex_);
absl::CondVar cond_;
absl::flat_hash_set<WifiLanSocket*> pending_sockets_ ABSL_GUARDED_BY(mutex_);
std::function<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
absl::AnyInvocable<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
bool closed_ ABSL_GUARDED_BY(mutex_) = false;
};
@@ -15,12 +15,11 @@
#ifndef PLATFORM_API_LISTENABLE_FUTURE_H_
#define PLATFORM_API_LISTENABLE_FUTURE_H_
#include <functional>
#include <memory>
#include "internal/platform/exception.h"
#include "internal/platform/implementation/executor.h"
#include "internal/platform/implementation/future.h"
#include "internal/platform/exception.h"
#include "internal/platform/runnable.h"
namespace nearby {
@@ -16,7 +16,6 @@
#define PLATFORM_API_SCHEDULED_EXECUTOR_H_
#include <cstdint>
#include <functional>
#include <memory>
#include "absl/time/time.h"
@@ -15,7 +15,6 @@
#ifndef PLATFORM_API_SUBMITTABLE_EXECUTOR_H_
#define PLATFORM_API_SUBMITTABLE_EXECUTOR_H_
#include <functional>
#include <memory>
#include "internal/platform/implementation/executor.h"
@@ -28,7 +27,7 @@ namespace api {
// Main interface to be used by platform as a base class for
// - MultiThreadExecutorWrapper
// - SingleThreadExecutorWrapper
// Platform must override bool submit(std::function<void()>) method.
// Platform must override bool submit(absl::AnyInvocable<void()>) method.
class SubmittableExecutor : public Executor {
public:
~SubmittableExecutor() override = default;
+2 -2
View File
@@ -15,7 +15,7 @@
#ifndef PLATFORM_API_TIMER_H_
#define PLATFORM_API_TIMER_H_
#include <functional>
#include "absl/functional/any_invocable.h"
namespace nearby {
namespace api {
@@ -35,7 +35,7 @@ class Timer {
//
// @return return true if success, otherwise false
virtual bool Create(int delay, int interval,
std::function<void()> callback) = 0;
absl::AnyInvocable<void()> callback) = 0;
// Stops timer. No timer signal is sent after the call.
virtual bool Stop() = 0;
+4 -5
View File
@@ -15,7 +15,6 @@
#ifndef PLATFORM_API_WEBRTC_H_
#define PLATFORM_API_WEBRTC_H_
#include <functional>
#include <memory>
#include <string>
@@ -29,8 +28,8 @@ namespace api {
class WebRtcSignalingMessenger {
public:
using OnSignalingMessageCallback = std::function<void(const ByteArray&)>;
using OnSignalingCompleteCallback = std::function<void(bool)>;
using OnSignalingMessageCallback = absl::AnyInvocable<void(const ByteArray&)>;
using OnSignalingCompleteCallback = absl::AnyInvocable<void(bool)>;
virtual ~WebRtcSignalingMessenger() = default;
@@ -45,8 +44,8 @@ class WebRtcSignalingMessenger {
class WebRtcMedium {
public:
using PeerConnectionCallback =
std::function<void(rtc::scoped_refptr<webrtc::PeerConnectionInterface>)>;
using PeerConnectionCallback = absl::AnyInvocable<void(
rtc::scoped_refptr<webrtc::PeerConnectionInterface>)>;
virtual ~WebRtcMedium() = default;
+3 -3
View File
@@ -99,9 +99,9 @@ class WifiLanMedium {
// Callback that is invoked when a discovered service is found or lost.
struct DiscoveredServiceCallback {
std::function<void(NsdServiceInfo service_info)> service_discovered_cb =
DefaultCallback<NsdServiceInfo>();
std::function<void(NsdServiceInfo service_info)> service_lost_cb =
absl::AnyInvocable<void(NsdServiceInfo service_info)>
service_discovered_cb = DefaultCallback<NsdServiceInfo>();
absl::AnyInvocable<void(NsdServiceInfo service_info)> service_lost_cb =
DefaultCallback<NsdServiceInfo>();
};
@@ -17,7 +17,6 @@
#include <guiddef.h>
#include <functional>
#include <future> // NOLINT
#include <memory>
#include <string>
@@ -121,4 +120,3 @@ class BleMedium : public api::BleMedium {
} // namespace nearby
#endif // THIRD_PARTY_NEARBY_INTERNAL_PLATFORM_IMPLEMENTATION_WINDOWS_BLE_MEDIUM_H_
@@ -229,8 +229,7 @@ TEST(BleMedium, DISABLED_StartAdvertising_ExtendedAdvertising) {
ByteArray advertising_data(advertising_data_byte_array);
EXPECT_TRUE(
ble_medium.StartAdvertising("NearbyShare", advertising_data, ""));
EXPECT_TRUE(ble_medium.StartAdvertising("NearbyShare", advertising_data, ""));
}
TEST(BleMedium, DISABLED_StopAdvertising) {
@@ -254,35 +253,30 @@ TEST(BleMedium, DISABLED_StartScanning) {
BluetoothAdapter bluetoothAdapter;
BleMedium ble_medium(bluetoothAdapter);
BleMedium::DiscoveredPeripheralCallback discovered_peripheral_callback = {
.peripheral_discovered_cb = [this](api::BlePeripheral& peripheral,
const std::string& service_id,
bool fast_advertisement) {},
.peripheral_lost_cb = [this](api::BlePeripheral& peripheral,
const std::string& service_id) {}};
EXPECT_TRUE(ble_medium.StartScanning("NearbyShare", "\xfe\xf3",
discovered_peripheral_callback));
EXPECT_TRUE(ble_medium.StartScanning(
"NearbyShare", "\xfe\xf3",
{.peripheral_discovered_cb = [](api::BlePeripheral& peripheral,
const std::string& service_id,
bool fast_advertisement) {},
.peripheral_lost_cb = [](api::BlePeripheral& peripheral,
const std::string& service_id) {}}));
}
TEST(BleMedium, DISABLED_ReceiveAdvertisement) {
absl::Notification advertisement_received_notification;
BluetoothAdapter bluetoothAdapter;
BleMedium ble_medium(bluetoothAdapter);
BleMedium::DiscoveredPeripheralCallback discovered_peripheral_callback = {
.peripheral_discovered_cb =
[this, &advertisement_received_notification](
api::BlePeripheral& peripheral, const std::string& service_id,
bool fast_advertisement) {
advertisement_received_notification.Notify();
},
.peripheral_lost_cb = [this](api::BlePeripheral& peripheral,
const std::string& service_id) {}};
EXPECT_TRUE(ble_medium.StartScanning(
"NearbyShare", "\xfe\xf3",
{.peripheral_discovered_cb =
[&](api::BlePeripheral& peripheral, const std::string& service_id,
bool fast_advertisement) {
advertisement_received_notification.Notify();
},
.peripheral_lost_cb = [](api::BlePeripheral& peripheral,
const std::string& service_id) {}}));
EXPECT_TRUE(ble_medium.StartScanning("NearbyShare", "\xfe\xf3",
discovered_peripheral_callback));
EXPECT_TRUE(
advertisement_received_notification.WaitForNotificationWithTimeout(
absl::Seconds(5)));
@@ -292,15 +286,14 @@ TEST(BleMedium, DISABLED_StopScanning) {
BluetoothAdapter bluetoothAdapter;
BleMedium ble_medium(bluetoothAdapter);
BleMedium::DiscoveredPeripheralCallback discovered_peripheral_callback = {
.peripheral_discovered_cb =
[this](api::BlePeripheral& peripheral, const std::string& service_id,
bool fast_advertisement) { EXPECT_TRUE(fast_advertisement); },
.peripheral_lost_cb = [this](api::BlePeripheral& peripheral,
const std::string& service_id) {}};
EXPECT_TRUE(ble_medium.StartScanning(
"NearbyShare", "\xfe\xf3",
{.peripheral_discovered_cb =
[](api::BlePeripheral& peripheral, const std::string& service_id,
bool fast_advertisement) { EXPECT_TRUE(fast_advertisement); },
.peripheral_lost_cb = [](api::BlePeripheral& peripheral,
const std::string& service_id) {}}));
EXPECT_TRUE(ble_medium.StartScanning("NearbyShare", "\xfe\xf3",
discovered_peripheral_callback));
EXPECT_TRUE(ble_medium.StopScanning("NearbyShare"));
}
@@ -15,7 +15,6 @@
#ifndef THIRD_PARTY_NEARBY_INTERNAL_PLATFORM_IMPLEMENTATION_WINDOWS_BLE_V2_H_
#define THIRD_PARTY_NEARBY_INTERNAL_PLATFORM_IMPLEMENTATION_WINDOWS_BLE_V2_H_
#include <functional>
#include <memory>
#include <string>
@@ -107,18 +106,20 @@ class BleV2Medium : public api::ble_v2::BleMedium {
BluetoothLEAdvertisementPublisher publisher,
winrt::Windows::Devices::Bluetooth::Advertisement::
BluetoothLEAdvertisementPublisherStatusChangedEventArgs args);
std::function<void()> publisher_started_callback_ ABSL_GUARDED_BY(mutex_);
std::function<void()> publisher_stopped_callback_ ABSL_GUARDED_BY(mutex_);
std::function<void()> publisher_error_callback_ ABSL_GUARDED_BY(mutex_);
absl::AnyInvocable<void()> publisher_started_callback_
ABSL_GUARDED_BY(mutex_);
absl::AnyInvocable<void()> publisher_stopped_callback_
ABSL_GUARDED_BY(mutex_);
absl::AnyInvocable<void()> publisher_error_callback_ ABSL_GUARDED_BY(mutex_);
winrt::event_token watcher_token_;
void WatcherHandler(winrt::Windows::Devices::Bluetooth::Advertisement::
BluetoothLEAdvertisementWatcher watcher,
winrt::Windows::Devices::Bluetooth::Advertisement::
BluetoothLEAdvertisementWatcherStoppedEventArgs args);
std::function<void()> watcher_started_callback_ ABSL_GUARDED_BY(mutex_);
std::function<void()> watcher_stopped_callback_ ABSL_GUARDED_BY(mutex_);
std::function<void()> watcher_error_callback_ ABSL_GUARDED_BY(mutex_);
absl::AnyInvocable<void()> watcher_started_callback_ ABSL_GUARDED_BY(mutex_);
absl::AnyInvocable<void()> watcher_stopped_callback_ ABSL_GUARDED_BY(mutex_);
absl::AnyInvocable<void()> watcher_error_callback_ ABSL_GUARDED_BY(mutex_);
winrt::event_token advertisement_received_token_;
void AdvertisementReceivedHandler(
@@ -20,10 +20,11 @@
#include <guiddef.h>
// clang-format on
#include <functional>
#include <optional>
#include <string>
#include <utility>
#include "absl/functional/any_invocable.h"
#include "internal/platform/implementation/bluetooth_adapter.h"
#include "internal/platform/implementation/windows/generated/winrt/Windows.Devices.Bluetooth.h"
#include "internal/platform/implementation/windows/generated/winrt/Windows.Devices.Radios.h"
@@ -52,7 +53,8 @@ class BluetoothAdapter : public api::BluetoothAdapter {
~BluetoothAdapter() override = default;
typedef std::function<void(api::BluetoothAdapter::ScanMode)> ScanModeCallback;
typedef absl::AnyInvocable<void(api::BluetoothAdapter::ScanMode)>
ScanModeCallback;
// Synchronously sets the status of the BluetoothAdapter to 'status', and
// returns true if the operation was a success.
@@ -88,8 +90,8 @@ class BluetoothAdapter : public api::BluetoothAdapter {
std::string GetNameFromComputerName() const;
void SetOnScanModeChanged(ScanModeCallback callback) {
if (scan_mode_changed_ == nullptr) {
scan_mode_changed_ = callback;
if (scan_mode_changed_) {
scan_mode_changed_ = std::move(callback);
}
}
@@ -111,7 +113,7 @@ class BluetoothAdapter : public api::BluetoothAdapter {
void find_and_replace(char *source, const char *strFind,
const char *strReplace) const;
ScanMode scan_mode_ = ScanMode::kNone;
ScanModeCallback scan_mode_changed_ = nullptr;
ScanModeCallback scan_mode_changed_;
// Used to fake the device name when the device name is longer than android
// limitation.
@@ -163,16 +163,14 @@ TEST(BluetoothAdapter, DISABLED_SetOnScanModeChanged) {
api::BluetoothAdapter::ScanMode mode =
api::BluetoothAdapter::ScanMode::kUnknown;
absl::Notification scan_mode_changed_notification;
BluetoothAdapter::ScanModeCallback callback =
[&mode, &scan_mode_changed_notification](
api::BluetoothAdapter::ScanMode scan_mode) {
mode = scan_mode;
scan_mode_changed_notification.Notify();
};
BluetoothAdapter bluetooth_adapter;
bluetooth_adapter.SetScanMode(mode);
bluetooth_adapter.SetOnScanModeChanged(callback);
bluetooth_adapter.SetOnScanModeChanged(
[&](api::BluetoothAdapter::ScanMode scan_mode) {
mode = scan_mode;
scan_mode_changed_notification.Notify();
});
bluetooth_adapter.SetScanMode(
api::BluetoothAdapter::ScanMode::kConnectableDiscoverable);
EXPECT_TRUE(scan_mode_changed_notification.WaitForNotificationWithTimeout(
@@ -154,7 +154,7 @@ bool BluetoothClassicMedium::StartDiscovery(
NEARBY_LOGS(INFO) << "StartDiscovery is called.";
bool result = false;
discovery_callback_ = discovery_callback;
discovery_callback_ = std::move(discovery_callback);
if (!IsWatcherStarted()) {
result = StartScanning();
@@ -16,7 +16,6 @@
#include <codecvt>
#include <exception>
#include <functional>
#include <locale>
#include <memory>
#include <string>
@@ -55,7 +54,8 @@ std::unique_ptr<api::BluetoothSocket> BluetoothServerSocket::Accept() {
return std::make_unique<BluetoothSocket>(bluetooth_socket);
}
void BluetoothServerSocket::SetCloseNotifier(std::function<void()> notifier) {
void BluetoothServerSocket::SetCloseNotifier(
absl::AnyInvocable<void()> notifier) {
close_notifier_ = std::move(notifier);
}
@@ -17,7 +17,6 @@
#include <Windows.h>
#include <functional>
#include <memory>
#include <queue>
#include <string>
@@ -74,7 +73,7 @@ class BluetoothServerSocket : public api::BluetoothServerSocket {
// Called by the server side of a connection before passing ownership of
// WifiLanServerSocker to user, to track validity of a pointer to this
// server socket.
void SetCloseNotifier(std::function<void()> notifier);
void SetCloseNotifier(absl::AnyInvocable<void()> notifier);
bool listen();
@@ -98,7 +97,7 @@ class BluetoothServerSocket : public api::BluetoothServerSocket {
winrt::event_token listener_event_token_{};
// Close notifier
std::function<void()> close_notifier_ = nullptr;
absl::AnyInvocable<void()> close_notifier_ = nullptr;
// IP addresses of the computer. mDNS uses them to advertise.
std::vector<std::string> ip_addresses_{};
@@ -24,7 +24,7 @@ namespace windows {
// Main interface to be used by platform as a base class for
// - MultiThreadExecutorWrapper
// - SingleThreadExecutorWrapper
// Platform must override bool submit(std::function<void()>) method.
// Platform must override bool submit(absl::AnyInvocable<void()>) method.
class SubmittableExecutor : public api::SubmittableExecutor {
public:
SubmittableExecutor();
@@ -14,7 +14,6 @@
#include "internal/platform/implementation/windows/thread_pool.h"
#include <functional>
#include <vector>
#include "gtest/gtest.h"
@@ -14,7 +14,6 @@
#include "internal/platform/implementation/windows/timer.h"
#include <functional>
#include <memory>
#include "internal/platform/logging.h"
@@ -24,7 +23,8 @@ namespace windows {
Timer::~Timer() { Stop(); }
bool Timer::Create(int delay, int interval, std::function<void()> callback) {
bool Timer::Create(int delay, int interval,
absl::AnyInvocable<void()> callback) {
if ((delay < 0) || (interval < 0)) {
NEARBY_LOGS(WARNING) << "Delay and interval shouldn\'t be negative value.";
return false;
@@ -90,8 +90,8 @@ bool Timer::FireNow() {
}
void CALLBACK Timer::TimerRoutine(PVOID lpParam, BOOLEAN TimerOrWaitFired) {
std::function<void()>* callback =
reinterpret_cast<std::function<void()>*>(lpParam);
absl::AnyInvocable<void()>* callback =
reinterpret_cast<absl::AnyInvocable<void()>*>(lpParam);
if (*callback != NULL) {
(*callback)();
}
@@ -17,8 +17,6 @@
#include <windows.h>
#include <functional>
#include "internal/platform/implementation/timer.h"
namespace nearby {
@@ -29,7 +27,8 @@ class Timer : public api::Timer {
Timer() = default;
~Timer() override;
bool Create(int delay, int interval, std::function<void()> callback) override;
bool Create(int delay, int interval,
absl::AnyInvocable<void()> callback) override;
bool Stop() override;
bool FireNow() override;
@@ -38,7 +37,7 @@ class Timer : public api::Timer {
int delay_;
int interval_;
std::function<void()> callback_;
absl::AnyInvocable<void()> callback_;
HANDLE handle_ = NULL;
HANDLE timer_queue_handle_ = NULL;
};
@@ -14,8 +14,8 @@
#include "internal/platform/implementation/timer.h"
#include <chrono> // NOLINT
#include <functional> // NOLINT
#include <chrono> // NOLINT
// NOLINT
#include <memory>
#include <thread> // NOLINT
@@ -28,26 +28,24 @@ namespace {
TEST(Timer, TestCreateTimer) {
int count = 0;
std::function<void()> callback = [&count]() { ++count; };
std::unique_ptr<nearby::api::Timer> timer =
nearby::api::ImplementationPlatform::CreateTimer();
ASSERT_TRUE(timer != nullptr);
EXPECT_FALSE(timer->Create(-100, 0, callback));
EXPECT_FALSE(timer->Create(-100, 0, [&]() { ++count; }));
EXPECT_TRUE(timer->Stop());
}
// This test case cannot run on Google3
TEST(Timer, DISABLED_TestRepeatTimer) {
int count = 0;
std::function<void()> callback = [&count]() { count++; };
std::unique_ptr<nearby::api::Timer> timer =
nearby::api::ImplementationPlatform::CreateTimer();
ASSERT_TRUE(timer != nullptr);
EXPECT_TRUE(timer->Create(300, 300, callback));
EXPECT_TRUE(timer->Create(300, 300, [&]() { ++count; }));
std::this_thread::sleep_for(std::chrono::seconds(1));
EXPECT_TRUE(timer->Stop());
EXPECT_EQ(count, 3);
@@ -55,10 +53,11 @@ TEST(Timer, DISABLED_TestRepeatTimer) {
TEST(Timer, DISABLED_TestFireNow) {
int count = 0;
std::function<void()> callback = [&count]() { ++count; };
auto timer = nearby::api::ImplementationPlatform::CreateTimer();
EXPECT_TRUE(timer != nullptr);
EXPECT_TRUE(timer->Create(3000, 3000, callback));
EXPECT_TRUE(timer->Create(3000, 3000, [&]() { ++count; }));
EXPECT_TRUE(timer->FireNow());
EXPECT_TRUE(timer->Stop());
EXPECT_EQ(count, 1);
@@ -22,7 +22,6 @@
// Standard C/C++ headers
#include <deque>
#include <exception>
#include <functional>
#include <memory>
#include <optional>
#include <string>
@@ -191,7 +190,7 @@ class WifiDirectServerSocket : public api::WifiDirectServerSocket {
// Called by the server side of a connection before passing ownership of
// WifiDirectServerSocker to user, to track validity of a pointer to this
// server socket.
void SetCloseNotifier(std::function<void()> notifier);
void SetCloseNotifier(absl::AnyInvocable<void()> notifier);
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
Exception Close() override;
@@ -217,7 +216,7 @@ class WifiDirectServerSocket : public api::WifiDirectServerSocket {
winrt::event_token listener_event_token_{};
// Close notifier
std::function<void()> close_notifier_ = nullptr;
absl::AnyInvocable<void()> close_notifier_ = nullptr;
// IP addresses of the computer. mDNS uses them to advertise.
std::vector<std::string> ip_addresses_{};
@@ -15,7 +15,6 @@
#include <windows.h>
#include <exception>
#include <functional>
#include <memory>
#include <string>
#include <vector>
@@ -82,7 +81,8 @@ std::unique_ptr<api::WifiDirectSocket> WifiDirectServerSocket::Accept() {
return std::make_unique<WifiDirectSocket>(wifi_direct_socket);
}
void WifiDirectServerSocket::SetCloseNotifier(std::function<void()> notifier) {
void WifiDirectServerSocket::SetCloseNotifier(
absl::AnyInvocable<void()> notifier) {
close_notifier_ = std::move(notifier);
}
@@ -20,7 +20,7 @@
#include <wlanapi.h>
// Standard C/C++ headers
#include <functional>
#include <memory>
#include <optional>
#include <string>
@@ -185,7 +185,7 @@ class WifiHotspotServerSocket : public api::WifiHotspotServerSocket {
// Called by the server side of a connection before passing ownership of
// WifiHotspotServerSocker to user, to track validity of a pointer to this
// server socket.
void SetCloseNotifier(std::function<void()> notifier);
void SetCloseNotifier(absl::AnyInvocable<void()> notifier);
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
Exception Close() override;
@@ -211,7 +211,7 @@ class WifiHotspotServerSocket : public api::WifiHotspotServerSocket {
winrt::event_token listener_event_token_{};
// Close notifier
std::function<void()> close_notifier_ = nullptr;
absl::AnyInvocable<void()> close_notifier_ = nullptr;
// IP addresses of the computer. mDNS uses them to advertise.
std::vector<std::string> ip_addresses_{};
@@ -15,7 +15,6 @@
#include <windows.h>
#include <exception>
#include <functional>
#include <memory>
#include <string>
#include <vector>
@@ -82,7 +81,8 @@ std::unique_ptr<api::WifiHotspotSocket> WifiHotspotServerSocket::Accept() {
return std::make_unique<WifiHotspotSocket>(wifi_hotspot_socket);
}
void WifiHotspotServerSocket::SetCloseNotifier(std::function<void()> notifier) {
void WifiHotspotServerSocket::SetCloseNotifier(
absl::AnyInvocable<void()> notifier) {
close_notifier_ = std::move(notifier);
}
@@ -23,7 +23,6 @@
// Standard C/C++ headers
#include <exception>
#include <functional>
#include <memory>
#include <optional>
#include <string>
@@ -35,8 +34,8 @@
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include "absl/types/optional.h"
#include "internal/platform/count_down_latch.h"
#include "internal/platform/cancellation_flag_listener.h"
#include "internal/platform/count_down_latch.h"
#include "internal/platform/exception.h"
#include "internal/platform/implementation/wifi_lan.h"
#include "internal/platform/implementation/windows/scheduled_executor.h"
@@ -187,7 +186,7 @@ class WifiLanServerSocket : public api::WifiLanServerSocket {
// Called by the server side of a connection before passing ownership of
// WifiLanServerSocker to user, to track validity of a pointer to this
// server socket.
void SetCloseNotifier(std::function<void()> notifier);
void SetCloseNotifier(absl::AnyInvocable<void()> notifier);
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
Exception Close() override;
@@ -208,7 +207,7 @@ class WifiLanServerSocket : public api::WifiLanServerSocket {
winrt::event_token listener_event_token_{};
// Close notifier
std::function<void()> close_notifier_ = nullptr;
absl::AnyInvocable<void()> close_notifier_ = nullptr;
// IP addresses of the computer. mDNS uses them to advertise.
std::vector<std::string> ip_addresses_{};
@@ -15,7 +15,6 @@
#include <windows.h>
#include <exception>
#include <functional>
#include <memory>
#include <string>
#include <vector>
@@ -84,7 +83,8 @@ std::unique_ptr<api::WifiLanSocket> WifiLanServerSocket::Accept() {
return std::make_unique<WifiLanSocket>(wifi_lan_socket);
}
void WifiLanServerSocket::SetCloseNotifier(std::function<void()> notifier) {
void WifiLanServerSocket::SetCloseNotifier(
absl::AnyInvocable<void()> notifier) {
close_notifier_ = std::move(notifier);
}
+3 -3
View File
@@ -15,7 +15,7 @@
#ifndef PLATFORM_BASE_LISTENERS_H_
#define PLATFORM_BASE_LISTENERS_H_
#include <functional>
#include "absl/functional/any_invocable.h"
namespace nearby {
@@ -23,8 +23,8 @@ namespace nearby {
// instead of nullptr. This allows partial initialization
// of a set of listeners.
template <typename... Args>
constexpr std::function<void(Args...)> DefaultCallback() {
return std::function<void(Args...)>{[](Args...) {}};
constexpr absl::AnyInvocable<void(Args...)> DefaultCallback() {
return absl::AnyInvocable<void(Args...)>{[](Args...) {}};
}
} // namespace nearby
+5 -6
View File
@@ -18,7 +18,6 @@
#include <atomic>
#include <cinttypes>
#include <cstdint>
#include <functional>
#include <new>
#include <string>
#include <type_traits>
@@ -352,7 +351,7 @@ void MediumEnvironment::UpdateBluetoothMedium(
api::BluetoothClassicMedium& medium, BluetoothDiscoveryCallback callback) {
if (!enabled_) return;
RunOnMediumEnvironmentThread(
[this, &medium, callback = std::move(callback)]() {
[this, &medium, callback = std::move(callback)]() mutable {
auto item = bluetooth_mediums_.find(&medium);
if (item == bluetooth_mediums_.end()) return;
auto& context = item->second;
@@ -431,7 +430,7 @@ void MediumEnvironment::UpdateBleMediumForScanning(
if (!enabled_) return;
RunOnMediumEnvironmentThread(
[this, &medium, service_id, fast_advertisement_service_uuid,
callback = std::move(callback), enabled]() {
callback = std::move(callback), enabled]() mutable {
auto item = ble_mediums_.find(&medium);
if (item == ble_mediums_.end()) {
NEARBY_LOGS(INFO)
@@ -467,7 +466,7 @@ void MediumEnvironment::UpdateBleMediumForAcceptedConnection(
BleAcceptedConnectionCallback callback) {
if (!enabled_) return;
RunOnMediumEnvironmentThread(
[this, &medium, service_id, callback = std::move(callback)]() {
[this, &medium, service_id, callback = std::move(callback)]() mutable {
auto item = ble_mediums_.find(&medium);
if (item == ble_mediums_.end()) {
NEARBY_LOGS(INFO)
@@ -742,7 +741,7 @@ void MediumEnvironment::RegisterWebRtcSignalingMessenger(
RunOnMediumEnvironmentThread([this, self_id{std::string(self_id)},
message_callback{std::move(message_callback)},
complete_callback{
std::move(complete_callback)}]() {
std::move(complete_callback)}]() mutable {
webrtc_signaling_message_callback_[self_id] = std::move(message_callback);
webrtc_signaling_complete_callback_[self_id] = std::move(complete_callback);
NEARBY_LOGS(INFO) << "Registered signaling message callback for id = "
@@ -875,7 +874,7 @@ void MediumEnvironment::UpdateWifiLanMediumForDiscovery(
const std::string& service_type, bool enabled) {
if (!enabled_) return;
RunOnMediumEnvironmentThread([this, &medium, callback = std::move(callback),
service_type, enabled]() {
service_type, enabled]() mutable {
auto item = wifi_lan_mediums_.find(&medium);
if (item == wifi_lan_mediums_.end()) {
NEARBY_LOGS(INFO)
-1
View File
@@ -16,7 +16,6 @@
#define PLATFORM_BASE_MEDIUM_ENVIRONMENT_H_
#include <atomic>
#include <functional>
#include <memory>
#include <string>
#include <utility>
@@ -15,7 +15,6 @@
#include "internal/platform/multi_thread_executor.h"
#include <atomic>
#include <functional>
#include "gtest/gtest.h"
#include "absl/synchronization/mutex.h"
-1
View File
@@ -16,7 +16,6 @@
#define PLATFORM_PUBLIC_SCHEDULED_EXECUTOR_H_
#include <cstdint>
#include <functional>
#include <memory>
#include "absl/base/thread_annotations.h"
+1 -2
View File
@@ -15,14 +15,13 @@
#include "internal/platform/scheduled_executor.h"
#include <atomic>
#include <functional>
#include "gtest/gtest.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "internal/platform/exception.h"
#include "internal/platform/count_down_latch.h"
#include "internal/platform/exception.h"
namespace nearby {
@@ -15,7 +15,6 @@
#include "internal/platform/single_thread_executor.h"
#include <atomic>
#include <functional>
#include <string>
#include "gtest/gtest.h"
+1 -2
View File
@@ -16,7 +16,6 @@
#define PLATFORM_PUBLIC_SUBMITTABLE_EXECUTOR_H_
#include <cstddef>
#include <functional>
#include <memory>
#include <utility>
@@ -86,7 +85,7 @@ class ABSL_LOCKABLE SubmittableExecutor : public api::SubmittableExecutor,
MutexLock lock(&mutex_);
bool submitted =
DoSubmit([callable = ThreadCheckCallable<T>(this, std::move(callable)),
future]() {
future]() mutable {
ExceptionOr<T> result = callable();
if (result.ok()) {
future->Set(result.result());
+3 -4
View File
@@ -15,8 +15,7 @@
#ifndef PLATFORM_PUBLIC_TASK_RUNNER_H_
#define PLATFORM_PUBLIC_TASK_RUNNER_H_
#include <functional>
#include "absl/functional/any_invocable.h"
#include "absl/time/time.h"
namespace nearby {
@@ -30,13 +29,13 @@ class TaskRunner {
// Posts a task to task runner. The task runs immediately or not depends on
// the implementation of class. If the implementation supports multiple
// threads, posted tasks could run concurrently.
virtual bool PostTask(std::function<void()> task) = 0;
virtual bool PostTask(absl::AnyInvocable<void()> task) = 0;
// Posts a task to run with delay. Multiple tasks can be scheduled. Tasks will
// execute in the order of their delay expiring, not in the order they were
// posted.
virtual bool PostDelayedTask(absl::Duration delay,
std::function<void()> task) = 0;
absl::AnyInvocable<void()> task) = 0;
};
} // namespace nearby
+6 -11
View File
@@ -14,13 +14,11 @@
#include "internal/platform/task_runner_impl.h"
#include <functional>
#include <iostream>
#include <limits>
#include <memory>
#include <utility>
#include "absl/random/random.h"
#include "absl/functional/any_invocable.h"
#include "internal/crypto/random.h"
#include "internal/platform/timer_impl.h"
namespace nearby {
@@ -31,7 +29,7 @@ TaskRunnerImpl::TaskRunnerImpl(uint32_t runner_count) {
TaskRunnerImpl::~TaskRunnerImpl() = default;
bool TaskRunnerImpl::PostTask(std::function<void()> task) {
bool TaskRunnerImpl::PostTask(absl::AnyInvocable<void()> task) {
if (task) {
// Because of cannot get the executor status from platform API, just returns
// true after calling the Execute method.
@@ -42,7 +40,7 @@ bool TaskRunnerImpl::PostTask(std::function<void()> task) {
}
bool TaskRunnerImpl::PostDelayedTask(absl::Duration delay,
std::function<void()> task) {
absl::AnyInvocable<void()> task) {
if (!task) {
return true;
}
@@ -52,7 +50,7 @@ bool TaskRunnerImpl::PostDelayedTask(absl::Duration delay,
std::unique_ptr<Timer> timer = std::make_unique<TimerImpl>();
if (timer->Start(delay / absl::Milliseconds(1), 0,
[this, id, task = std::move(task)]() {
[this, id, task = std::move(task)]() mutable {
if (task) {
PostTask(std::move(task));
}
@@ -68,9 +66,6 @@ bool TaskRunnerImpl::PostDelayedTask(absl::Duration delay,
return false;
}
uint64_t TaskRunnerImpl::GenerateId() {
absl::BitGen bitgen;
return absl::Uniform(bitgen, 0u, std::numeric_limits<uint64_t>::max());
}
uint64_t TaskRunnerImpl::GenerateId() { return ::crypto::RandData<uint64_t>(); }
} // namespace nearby
+3 -3
View File
@@ -23,12 +23,12 @@
#undef UNICODE
#endif
#include <functional>
#include <memory>
#include <utility>
#include "absl/base/thread_annotations.h"
#include "absl/container/flat_hash_map.h"
#include "absl/functional/any_invocable.h"
#include "absl/synchronization/mutex.h"
#include "internal/platform/multi_thread_executor.h"
#include "internal/platform/task_runner.h"
@@ -41,9 +41,9 @@ class TaskRunnerImpl : public TaskRunner {
explicit TaskRunnerImpl(uint32_t runner_count);
~TaskRunnerImpl() override;
bool PostTask(std::function<void()> task) override;
bool PostTask(absl::AnyInvocable<void()> task) override;
bool PostDelayedTask(absl::Duration delay,
std::function<void()> task) override
absl::AnyInvocable<void()> task) override
ABSL_LOCKS_EXCLUDED(mutex_);
private:
+3 -3
View File
@@ -26,10 +26,10 @@ namespace nearby {
template <typename T>
class ThreadCheckCallable {
public:
ThreadCheckCallable(const Lockable *lockable, Callable<T> &&callable)
: lockable_{lockable}, callable_{callable} {}
ThreadCheckCallable(const Lockable *lockable, Callable<T> callable)
: lockable_(lockable), callable_(std::move(callable)) {}
ExceptionOr<T> operator()() const {
ExceptionOr<T> operator()() {
ThreadLockHolder thread_lock(lockable_);
return callable_();
}
+3 -2
View File
@@ -15,7 +15,7 @@
#ifndef PLATFORM_PUBLIC_TIMER_H_
#define PLATFORM_PUBLIC_TIMER_H_
#include <functional>
#include "absl/functional/any_invocable.h"
namespace nearby {
class Timer {
@@ -33,7 +33,8 @@ class Timer {
// @param callback The callback is called when timer is signaled
//
// @return Returns true if succeed, otherwise false is returned.
virtual bool Start(int delay, int period, std::function<void()> callback) = 0;
virtual bool Start(int delay, int period,
absl::AnyInvocable<void()> callback) = 0;
virtual bool Stop() = 0;
virtual bool IsRunning() = 0;
virtual bool FireNow() = 0;
+3 -4
View File
@@ -14,7 +14,6 @@
#include "internal/platform/timer_impl.h"
#include <functional>
#include <utility>
#include "absl/time/clock.h"
@@ -22,7 +21,8 @@
namespace nearby {
bool TimerImpl::Start(int delay, int period, std::function<void()> callback) {
bool TimerImpl::Start(int delay, int period,
absl::AnyInvocable<void()> callback) {
if (internal_timer_ != nullptr) {
NEARBY_LOGS(INFO) << "The timer is already running.";
return false;
@@ -30,9 +30,8 @@ bool TimerImpl::Start(int delay, int period, std::function<void()> callback) {
delay_ = delay;
period_ = period;
callback_ = std::move(callback);
internal_timer_ = api::ImplementationPlatform::CreateTimer();
if (!internal_timer_->Create(delay, period, callback_)) {
if (!internal_timer_->Create(delay, period, std::move(callback))) {
NEARBY_LOGS(INFO) << "Failed to create timer.";
internal_timer_ = nullptr;
return false;
+3 -3
View File
@@ -15,9 +15,9 @@
#ifndef PLATFORM_PUBLIC_TIMER_IMPL_H_
#define PLATFORM_PUBLIC_TIMER_IMPL_H_
#include <functional>
#include <memory>
#include "absl/functional/any_invocable.h"
#include "internal/platform/implementation/platform.h"
#include "internal/platform/timer.h"
@@ -26,7 +26,8 @@ class TimerImpl : public Timer {
public:
~TimerImpl() override { Stop(); }
bool Start(int delay, int period, std::function<void()> callback) override;
bool Start(int delay, int period,
absl::AnyInvocable<void()> callback) override;
bool Stop() override;
bool IsRunning() override;
bool FireNow() override;
@@ -34,7 +35,6 @@ class TimerImpl : public Timer {
private:
int delay_ = 0;
int period_ = 0;
std::function<void()> callback_ = nullptr;
std::unique_ptr<api::Timer> internal_timer_ = nullptr;
};
+2 -2
View File
@@ -44,8 +44,8 @@ class WebRtcSignalingMessenger final {
bool StartReceivingMessages(
OnSignalingMessageCallback on_message_callback,
OnSignalingCompleteCallback on_complete_callback) {
return impl_->StartReceivingMessages(on_message_callback,
on_complete_callback);
return impl_->StartReceivingMessages(std::move(on_message_callback),
std::move(on_complete_callback));
}
void StopReceivingMessages() { impl_->StopReceivingMessages(); }
+2 -2
View File
@@ -80,7 +80,7 @@ bool WifiLanMedium::StartDiscovery(const std::string& service_id,
<< ", service_name=" << service_info.GetServiceName();
std::string service_id = it->second->service_id;
DiscoveredServiceCallback medium_callback =
DiscoveredServiceCallback& medium_callback =
it->second->medium_callback;
medium_callback.service_discovered_cb(service_info, service_id);
},
@@ -106,7 +106,7 @@ bool WifiLanMedium::StartDiscovery(const std::string& service_id,
const auto& it = service_type_to_callback_map_.find(service_type);
if (it != service_type_to_callback_map_.end()) {
std::string service_id = it->second->service_id;
DiscoveredServiceCallback medium_callback =
DiscoveredServiceCallback& medium_callback =
it->second->medium_callback;
medium_callback.service_lost_cb(service_info, service_id);
}
+4 -5
View File
@@ -15,7 +15,6 @@
#ifndef PLATFORM_PUBLIC_WIFI_LAN_H_
#define PLATFORM_PUBLIC_WIFI_LAN_H_
#include <functional>
#include <memory>
#include <string>
#include <utility>
@@ -129,12 +128,12 @@ class WifiLanMedium {
using Platform = api::ImplementationPlatform;
struct DiscoveredServiceCallback {
std::function<void(NsdServiceInfo service_info,
const std::string& service_type)>
absl::AnyInvocable<void(NsdServiceInfo service_info,
const std::string& service_type)>
service_discovered_cb =
DefaultCallback<NsdServiceInfo, const std::string&>();
std::function<void(NsdServiceInfo service_info,
const std::string& service_type)>
absl::AnyInvocable<void(NsdServiceInfo service_info,
const std::string& service_type)>
service_lost_cb = DefaultCallback<NsdServiceInfo, const std::string&>();
};