Internal refactor

PiperOrigin-RevId: 682563440
This commit is contained in:
Guogang Li
2024-10-04 22:11:41 -07:00
committed by Copybara-Service
parent 5d8b9156e0
commit 707e85d3fc
27 changed files with 0 additions and 3086 deletions
-106
View File
@@ -12,9 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
load("@bazel_skylib//:bzl_library.bzl", "bzl_library")
load("//third_party/cpptoolchains/windows_llvm/build_defs:windows.bzl", "windows")
load("expand_version_template.bzl", "expand_version_template")
package(default_visibility = [
"//connections:__subpackages__",
@@ -23,95 +21,6 @@ package(default_visibility = [
licenses(["notice"])
cc_library(
name = "types",
hdrs = [
"dll_config.h",
],
defines = ["CORE_ADAPTER_DLL"],
visibility = ["//visibility:private"],
deps = ["@com_google_absl//absl/strings"],
)
bzl_library(
name = "expand_version_template_bzl",
srcs = ["expand_version_template.bzl"],
parse_tests = False,
visibility = ["//visibility:private"],
)
# Default version if none is provided.
vardef("VERSION", "1.0.0.0")
# When built with rapid, a version value will be passed down from the build config via blaze
# When built manually, invoke blaze with --define=VERSION=1.2.3.4
# If VERSION is not passed from blaze, the default value defined above will be used.
expand_version_template(
name = "version_expanded",
out = "version.rc",
template = "version.rc.tpl",
version = varref("VERSION"),
)
windows.resource_files(
name = "resources",
rc_files = [
":version_expanded",
],
)
cc_library(
name = "c",
srcs = [
"advertising_options_w.cc",
"connection_options_w.cc",
"core_adapter.cc",
"discovery_options_w.cc",
"file_w.cc",
"listeners_w.cc",
"payload_w.cc",
"strategy_w.cc",
],
hdrs = [
"advertising_options_w.h",
"connection_options_w.h",
"core_adapter.h",
"discovery_options_w.h",
"file_w.h",
"listeners_w.h",
"medium_selector_w.h",
"options_base_w.h",
"out_of_band_connection_metadata_w.h",
"params_w.h",
"payload_w.h",
"strategy_w.h",
],
deps = [
":types",
"//connections:core",
"//connections:core_types",
"//internal/platform:base",
"//internal/platform:types",
"//proto:connections_enums_cc_proto",
"@com_google_absl//absl/log",
"@com_google_absl//absl/strings:str_format",
"@com_google_absl//absl/strings:string_view",
"@com_google_absl//absl/types:span",
],
)
# Build with --config=windows
windows.cc_windows_dll(
name = "nearby_connections",
tags = ["windows-dll"],
deps = [
":c",
":types",
"//internal/platform/implementation/windows",
"@com_google_absl//absl/strings",
],
)
cc_library(
name = "nc_types",
hdrs = [
@@ -158,18 +67,3 @@ windows.cc_windows_dll(
"@com_google_absl//absl/strings",
],
)
cc_test(
name = "connections_test",
size = "small",
srcs = [
"bluetooth_classic_server_socket_test.cc",
],
deps = [
"//connections:core",
"//internal/platform:types",
"//internal/platform/implementation/windows",
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_googletest//:gtest_main",
],
)
-48
View File
@@ -1,48 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "connections/c/advertising_options_w.h"
#include <string>
namespace nearby::windows {
// Returns a copy and normalizes allowed mediums:
// (1) If is_out_of_band_connection is true, verifies that there is only one
// medium allowed, defaulting to only Bluetooth if unspecified.
// (2) If no mediums are allowed, allow all mediums.
AdvertisingOptionsW AdvertisingOptionsW::CompatibleOptions() const {
AdvertisingOptionsW result = *this;
// Out-of-band connections initiate connections via an injected endpoint
// rather than through the normal discovery flow. These types of connections
// can only be injected via a single medium.
if (is_out_of_band_connection) {
int num_enabled = result.allowed.Count(true);
// Default to allow only Bluetooth if no single medium is specified.
if (num_enabled != 1) {
result.allowed.SetAll(false);
result.allowed.bluetooth = true;
}
return result;
}
// Normal connections (i.e., not out-of-band) connections can specify
// multiple mediums. If none are specified, default to allowing all mediums.
if (!allowed.Any(true)) result.allowed.SetAll(true);
return result;
}
} // namespace nearby::windows
-49
View File
@@ -1,49 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_NEARBY_CONNECTIONS_C_ADVERTISING_OPTIONS_W_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_C_ADVERTISING_OPTIONS_W_H_
#include "connections/c/options_base_w.h"
namespace nearby::windows {
extern "C" {
// Advertising Options: used for Advertising.
// All fields are mutable, to make the type copy-assignable.
struct DLL_API AdvertisingOptionsW : public OptionsBaseW {
bool auto_upgrade_bandwidth = true;
bool enforce_topology_constraints;
bool low_power;
// Whether this is intended to be used in conjunction with InjectEndpoint().
bool is_out_of_band_connection = false;
const char* fast_advertisement_service_uuid;
// The information about this device (eg. name, device type),
// to appear on the remote device.
// Defined by client/application.
const char* device_info;
// Returns a copy and normalizes allowed mediums:
// (1) If is_out_of_band_connection is true, verifies that there is only one
// medium allowed, defaulting to only Bluetooth if unspecified.
// (2) If no mediums are allowed, allow all mediums.
AdvertisingOptionsW CompatibleOptions() const;
};
} // extern "C"
} // namespace nearby::windows
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_C_ADVERTISING_OPTIONS_W_H_
@@ -1,612 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <windows.h>
#include <cstdint>
#include <string>
#include "gtest/gtest.h"
#include "absl/synchronization/notification.h"
#include "connections/advertising_options.h"
#include "connections/core.h"
#include "connections/implementation/service_controller_router.h"
#include "connections/listeners.h"
#include "connections/status.h"
#include "connections/strategy.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/count_down_latch.h"
namespace nearby::windows {
using ::nearby::ByteArray;
using ::nearby::connections::AdvertisingOptions;
using ::nearby::connections::ConnectionListener;
using ::nearby::connections::ConnectionRequestInfo;
using ::nearby::connections::Core;
using ::nearby::connections::ServiceControllerRouter;
using ::nearby::connections::Status;
using ::nearby::connections::Strategy;
constexpr absl::string_view SERVICE_ID =
"com.google.location.nearby.apps.helloconnections";
constexpr int TimeoutSeconds = 3;
constexpr int LoopCount = 10;
constexpr absl::string_view device_name = "12345678901";
AdvertisingOptions AdvertiseOptions{
{
// Strategy
{
Strategy::kP2pPointToPoint,
},
// Allowed:
{
true, // bluetooth
true, // ble
true, // webrtc
true, // wifi_lan
true, // wifi_hotspot
},
},
true, // auto_upgrade_bandwidth
true, // enforce_topology_constraints
false, // low_power
false, // enable_bluetooth_listening
false, // enable_webrtc_listening
false, // is_out_of_band_connection
"", // fast_advertisement_service_uuid
};
class PerformanceTimer {
public:
static void start() {
QueryPerformanceFrequency(&frequency_);
QueryPerformanceCounter(&starting_time_);
}
static void stop() {
QueryPerformanceCounter(&ending_time_);
elapsed_microseconds_.QuadPart =
ending_time_.QuadPart - starting_time_.QuadPart;
elapsed_milliseconds_ = elapsed_microseconds_.QuadPart / 100;
}
static uint64_t ElapsedMilliseconds() { return elapsed_milliseconds_; }
private:
static uint64_t elapsed_milliseconds_;
static LARGE_INTEGER starting_time_;
static LARGE_INTEGER ending_time_;
static LARGE_INTEGER elapsed_microseconds_;
static LARGE_INTEGER frequency_;
};
uint64_t PerformanceTimer::elapsed_milliseconds_;
LARGE_INTEGER PerformanceTimer::starting_time_;
LARGE_INTEGER PerformanceTimer::ending_time_;
LARGE_INTEGER PerformanceTimer::elapsed_microseconds_;
LARGE_INTEGER PerformanceTimer::frequency_;
TEST(BluetoothClassicServerSocketTest,
DISABLED_SingleRunWithTimeoutReproStuck) {
ServiceControllerRouter router;
Core core(&router);
ConnectionListener listener;
ConnectionRequestInfo request_info;
request_info.endpoint_info = ByteArray(std::string(device_name));
request_info.listener = listener;
Status request_result;
absl::Notification notification;
PerformanceTimer::start();
core.StartAdvertising(SERVICE_ID, AdvertiseOptions, request_info,
[&](Status status) {
request_result = status;
notification.Notify();
});
if (notification.WaitForNotificationWithTimeout(
absl::Seconds(TimeoutSeconds))) {
PerformanceTimer::stop();
NEARBY_LOGS(INFO) << "SingleRunWithTimeoutReproStuck Line: " << __LINE__
<< " Started advertising elapsed time: "
<< std::to_string(
PerformanceTimer::ElapsedMilliseconds());
#ifdef TEST_OUTPUT
EXPECT_TRUE(false) << "Started advertising elapsed time: "
<< std::to_string(ElapsedMilliseconds);
#endif
std::cout << "StartAdvertising started once:" << request_result.ToString()
<< std::endl;
NEARBY_LOGS(INFO) << "StartAdvertising started once:"
<< request_result.ToString();
} else {
PerformanceTimer::stop();
NEARBY_LOGS(INFO) << "SingleRunWithTimeoutReproStuck Line: " << __LINE__
<< " Timeout on starting advertising elapsed time: "
<< std::to_string(
PerformanceTimer::ElapsedMilliseconds());
EXPECT_TRUE(false) << "Timeout on starting advertising elapsed time: "
<< std::to_string(
PerformanceTimer::ElapsedMilliseconds());
std::cout << "StartAdvertising failed to start once:"
<< request_result.ToString() << std::endl;
NEARBY_LOGS(INFO) << "StartAdvertising failed to start once:"
<< request_result.ToString();
}
absl::Notification notification2;
PerformanceTimer::start();
core.StartAdvertising(SERVICE_ID, AdvertiseOptions, request_info,
[&](Status status) {
request_result = status;
notification2.Notify();
});
if (notification2.WaitForNotificationWithTimeout(
absl::Seconds(TimeoutSeconds))) {
PerformanceTimer::stop();
NEARBY_LOGS(INFO) << "SingleRunWithTimeoutReproStuck Line: " << __LINE__
<< " Started advertising second time elapsed time: "
<< std::to_string(
PerformanceTimer::ElapsedMilliseconds());
#ifdef TEST_OUTPUT
EXPECT_TRUE(false) << "Started advertising elapsed time: "
<< std::to_string(ElapsedMilliseconds);
#endif
std::cout << "StartAdvertising started twice:" << request_result.ToString()
<< std::endl;
NEARBY_LOGS(INFO) << "StartAdvertising started twice:"
<< request_result.ToString();
} else {
PerformanceTimer::stop();
NEARBY_LOGS(INFO)
<< "SingleRunWithTimeoutReproStuck Line: " << __LINE__
<< " Timeout on starting advertising the second time elapsed time: "
<< std::to_string(PerformanceTimer::ElapsedMilliseconds());
EXPECT_TRUE(false) << "SingleRunWithTimeoutReproStuck Line: " << __LINE__
<< " Timeout for started advertising elapsed time: "
<< std::to_string(
PerformanceTimer::ElapsedMilliseconds());
std::cout << "StartAdvertising failed to start twice:"
<< request_result.ToString() << std::endl;
NEARBY_LOGS(INFO) << "StartAdvertising failed to start twice:"
<< request_result.ToString();
}
absl::Notification notification3;
PerformanceTimer::start();
core.StopAdvertising([&](Status status) {
request_result = status;
notification3.Notify();
});
if (notification3.WaitForNotificationWithTimeout(
absl::Seconds(TimeoutSeconds))) {
PerformanceTimer::stop();
NEARBY_LOGS(INFO) << "SingleRunWithTimeoutReproStuck Line: " << __LINE__
<< " Stopped advertising first time elapsed time: "
<< std::to_string(
PerformanceTimer::ElapsedMilliseconds());
#ifdef TEST_OUTPUT
EXPECT_TRUE(false) << "Started advertising elapsed time: "
<< std::to_string(elapsed_microseconds);
#endif
std::cout << "StopAdvertising called once:" << request_result.ToString()
<< std::endl;
NEARBY_LOGS(INFO) << "StopAdvertising called once:"
<< request_result.ToString();
} else {
PerformanceTimer::stop();
NEARBY_LOGS(INFO)
<< "SingleRunWithTimeoutReproStuck Line: " << __LINE__
<< " Timeout on stopping advertising the first time elapsed time: "
<< std::to_string(PerformanceTimer::ElapsedMilliseconds());
EXPECT_TRUE(false) << "SingleRunWithTimeoutReproStuck Line: " << __LINE__
<< " Timeout on stop advertising elapsed time: "
<< std::to_string(
PerformanceTimer::ElapsedMilliseconds());
std::cout << "StopAdvertising failed to stop once:"
<< request_result.ToString() << std::endl;
NEARBY_LOGS(INFO) << "StopAdvertising failed to stop once:"
<< request_result.ToString();
}
std::cout << "Test completed." << std::endl;
NEARBY_LOGS(INFO) << "Test completed.";
}
TEST(BluetoothClassicServerSocketTest, DISABLED_MultiRunWithTimeoutReproStuck) {
ServiceControllerRouter router;
Core core(&router);
ConnectionListener listener;
ConnectionRequestInfo request_info;
request_info.endpoint_info = ByteArray(std::string(device_name));
request_info.listener = listener;
for (int loop_count = 0; loop_count < LoopCount; ++loop_count) {
Status request_result;
absl::Notification notification;
PerformanceTimer::start();
core.StartAdvertising(SERVICE_ID, AdvertiseOptions, request_info,
[&](Status status) {
request_result = status;
notification.Notify();
});
if (notification.WaitForNotificationWithTimeout(
absl::Seconds(TimeoutSeconds))) {
PerformanceTimer::stop();
NEARBY_LOGS(INFO) << "SingleRunWithTimeoutReproStuck Line: " << __LINE__
<< " Started advertising elapsed time: "
<< std::to_string(
PerformanceTimer::ElapsedMilliseconds());
#ifdef TEST_OUTPUT
EXPECT_TRUE(false) << "Started advertising elapsed time : "
<< std::to_string(ElapsedMilliseconds);
#endif
std::cout << "StartAdvertising started once:" << request_result.ToString()
<< std::endl;
NEARBY_LOGS(INFO) << "StartAdvertising started once:"
<< request_result.ToString();
} else {
PerformanceTimer::stop();
NEARBY_LOGS(INFO) << "SingleRunWithTimeoutReproStuck Line: " << __LINE__
<< " Timeout on starting advertising elapsed time: "
<< std::to_string(
PerformanceTimer::ElapsedMilliseconds());
EXPECT_TRUE(false) << "Timeout on starting advertising elapsed time: "
<< std::to_string(
PerformanceTimer::ElapsedMilliseconds());
std::cout << "StartAdvertising failed to start once:"
<< request_result.ToString() << std::endl;
NEARBY_LOGS(INFO) << "StartAdvertising failed to start once:"
<< request_result.ToString();
}
absl::Notification notification2;
PerformanceTimer::start();
core.StartAdvertising(SERVICE_ID, AdvertiseOptions, request_info,
[&](Status status) {
request_result = status;
notification2.Notify();
});
if (notification2.WaitForNotificationWithTimeout(
absl::Seconds(TimeoutSeconds))) {
PerformanceTimer::stop();
NEARBY_LOGS(INFO) << "SingleRunWithTimeoutReproStuck Line: " << __LINE__
<< " Started advertising second time elapsed time: "
<< std::to_string(
PerformanceTimer::ElapsedMilliseconds());
// EXPECT_TRUE(false)
// << "Started advertising elapsed time: "
// << std::to_string(ElapsedMilliseconds);
std::cout << "StartAdvertising started twice:"
<< request_result.ToString() << std::endl;
NEARBY_LOGS(INFO) << "StartAdvertising started twice:"
<< request_result.ToString();
} else {
PerformanceTimer::stop();
NEARBY_LOGS(INFO)
<< "SingleRunWithTimeoutReproStuck Line: " << __LINE__
<< " Timeout on starting advertising the second time elapsed time: "
<< std::to_string(PerformanceTimer::ElapsedMilliseconds());
EXPECT_TRUE(false)
<< "Timeout on starting advertising the second time elapsed time: "
<< std::to_string(PerformanceTimer::ElapsedMilliseconds());
std::cout << "StartAdvertising failed to start twice:"
<< request_result.ToString() << std::endl;
NEARBY_LOGS(INFO) << "StartAdvertising failed to start twice:"
<< request_result.ToString();
}
absl::Notification notification3;
PerformanceTimer::start();
core.StopAdvertising([&](Status status) {
request_result = status;
notification3.Notify();
});
if (notification3.WaitForNotificationWithTimeout(
absl::Seconds(TimeoutSeconds))) {
PerformanceTimer::stop();
NEARBY_LOGS(INFO) << "SingleRunWithTimeoutReproStuck Line: " << __LINE__
<< " Stopped advertising first time elapsed time: "
<< std::to_string(
PerformanceTimer::ElapsedMilliseconds());
#ifdef TEST_OUTPUT
EXPECT_TRUE(false) << "Started advertising elapsed time: "
<< std::to_string(ElapsedMilliseconds);
#endif
std::cout << "StopAdvertising called once:" << request_result.ToString()
<< std::endl;
NEARBY_LOGS(INFO) << "StopAdvertising called once:"
<< request_result.ToString();
} else {
PerformanceTimer::stop();
NEARBY_LOGS(INFO)
<< "SingleRunWithTimeoutReproStuck Line: " << __LINE__
<< " Timeout on stopping advertising the first time elapsed time: "
<< std::to_string(PerformanceTimer::ElapsedMilliseconds());
EXPECT_TRUE(false) << "Timeout on started advertising elapsed time: "
<< std::to_string(
PerformanceTimer::ElapsedMilliseconds());
std::cout << "StopAdvertising failed to stop once:"
<< request_result.ToString() << std::endl;
NEARBY_LOGS(INFO) << "StopAdvertising failed to stop once:"
<< request_result.ToString();
}
}
std::cout << "Test completed." << std::endl;
NEARBY_LOGS(INFO) << "Test completed.";
}
TEST(BluetoothClassicServerSocketTest, DISABLED_SingleRunNoTimeoutReproStuck) {
ServiceControllerRouter router;
Core core(&router);
ConnectionListener listener;
ConnectionRequestInfo request_info;
request_info.endpoint_info = ByteArray(std::string(device_name));
request_info.listener = listener;
Status request_result;
absl::Notification notification;
PerformanceTimer::start();
core.StartAdvertising(SERVICE_ID, AdvertiseOptions, request_info,
[&](Status status) {
request_result = status;
notification.Notify();
});
notification.WaitForNotification();
PerformanceTimer::stop();
NEARBY_LOGS(INFO) << "SingleRunNoTimeoutReproStuck Line: " << __LINE__
<< " Started advertising first time elapsed time: "
<< std::to_string(PerformanceTimer::ElapsedMilliseconds());
#ifdef TEST_OUTPUT
EXPECT_TRUE(false) << "Started advertising first time elapsed time: "
<< std::to_string(ElapsedMilliseconds);
#endif
std::cout << "StartAdvertising started once:" << request_result.ToString()
<< std::endl;
NEARBY_LOGS(INFO) << "StartAdvertising started once:"
<< request_result.ToString();
absl::Notification notification2;
PerformanceTimer::start();
core.StartAdvertising(SERVICE_ID, AdvertiseOptions, request_info,
[&](Status status) {
request_result = status;
notification2.Notify();
});
notification2.WaitForNotification();
PerformanceTimer::stop();
NEARBY_LOGS(INFO) << "SingleRunNoTimeoutReproStuck Line: " << __LINE__
<< " Started advertising first time elapsed time: "
<< std::to_string(PerformanceTimer::ElapsedMilliseconds());
#ifdef TEST_OUTPUT
EXPECT_TRUE(false) << "Started advertising first time elapsed time: "
<< std::to_string(ElapsedMilliseconds);
#endif
std::cout << "StartAdvertising started twice:" << request_result.ToString()
<< std::endl;
NEARBY_LOGS(INFO) << "StartAdvertising started twice:"
<< request_result.ToString();
absl::Notification notification3;
PerformanceTimer::start();
core.StopAdvertising([&](Status status) {
request_result = status;
notification3.Notify();
});
notification3.WaitForNotification();
PerformanceTimer::stop();
NEARBY_LOGS(INFO) << "SingleRunNoTimeoutReproStuck " << __LINE__
<< "Stopped advertising elapsed time: "
<< std::to_string(PerformanceTimer::ElapsedMilliseconds());
#ifdef TEST_OUTPUT
EXPECT_TRUE(false) << "Stopped advertising elapsed time: "
<< std::to_string(ElapsedMilliseconds);
#endif
std::cout << "StopAdvertising called once:" << request_result.ToString()
<< std::endl;
NEARBY_LOGS(INFO) << "StopAdvertising called once:"
<< request_result.ToString();
std::cout << "Test completed." << std::endl;
NEARBY_LOGS(INFO) << "Test completed.";
}
TEST(BluetoothClassicServerSocketTest, DISABLED_MultiRunNoTimeoutReproStuck) {
ServiceControllerRouter router;
Core core(&router);
ConnectionListener listener;
ConnectionRequestInfo request_info;
request_info.endpoint_info = ByteArray(std::string(device_name));
request_info.listener = listener;
for (int loop_count = 0; loop_count < LoopCount; ++loop_count) {
Status request_result;
absl::Notification notification;
PerformanceTimer::start();
core.StartAdvertising(SERVICE_ID, AdvertiseOptions, request_info,
[&](Status status) {
request_result = status;
notification.Notify();
});
notification.WaitForNotification();
PerformanceTimer::stop();
NEARBY_LOGS(INFO) << "MultiRunNoTimeoutReproStuck " << __LINE__
<< "Started advertising elapsed time: "
<< std::to_string(
PerformanceTimer::ElapsedMilliseconds());
#ifdef TEST_OUTPUT
EXPECT_TRUE(false) << "Started advertising elapsed time: "
<< std::to_string(ElapsedMilliseconds);
#endif
std::cout << "MultiRunNoTimeoutReproStuck " << __LINE__
<< " : StartAdvertising started once: "
<< request_result.ToString() << std::endl;
NEARBY_LOGS(INFO) << "StartAdvertising started once:"
<< request_result.ToString();
absl::Notification notification2;
PerformanceTimer::start();
core.StartAdvertising(SERVICE_ID, AdvertiseOptions, request_info,
[&](Status status) {
request_result = status;
notification2.Notify();
});
notification2.WaitForNotification();
PerformanceTimer::stop();
NEARBY_LOGS(INFO) << "MultiRunNoTimeoutReproStuck " << __LINE__
<< "Started advertising elapsed time: "
<< std::to_string(
PerformanceTimer::ElapsedMilliseconds());
#ifdef TEST_OUTPUT
EXPECT_TRUE(false) << "Started advertising elapsed time: "
<< std::to_string(ElapsedMilliseconds);
#endif
std::cout << "MultiRunNoTimeoutReproStuck " << __LINE__
<< "StartAdvertising started twice:" << request_result.ToString()
<< std::endl;
NEARBY_LOGS(INFO) << "MultiRunNoTimeoutReproStuck " << __LINE__
<< "StartAdvertising started twice:"
<< request_result.ToString();
absl::Notification notification3;
PerformanceTimer::start();
core.StopAdvertising([&](Status status) {
request_result = status;
notification3.Notify();
});
notification3.WaitForNotification();
PerformanceTimer::stop();
NEARBY_LOGS(INFO) << "MultiRunNoTimeoutReproStuck " << __LINE__
<< "Stopped advertising elapsed time: "
<< std::to_string(
PerformanceTimer::ElapsedMilliseconds());
#ifdef TEST_OUTPUT
EXPECT_TRUE(false) << "Stop advertising elapsed time: "
<< std::to_string(ElapsedMilliseconds);
#endif
std::cout << "StopAdvertising called once:" << request_result.ToString()
<< std::endl;
NEARBY_LOGS(INFO) << "MultiRunNoTimeoutReproStuck " << __LINE__
<< "StopAdvertising called once:"
<< request_result.ToString();
}
std::cout << "Test completed." << std::endl;
NEARBY_LOGS(INFO) << "Test completed.";
}
} // namespace nearby::windows
-35
View File
@@ -1,35 +0,0 @@
// Copyright 2021-2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "connections/c/connection_options_w.h"
#include <string>
namespace nearby::windows {
void ConnectionOptionsW::GetMediums(const MediumW* mediums,
size_t* mediums_size) const {
// Create a collection of enabled mediums
auto allowedMediums = allowed.GetMediums(true);
auto iter = allowedMediums.begin();
int index = 0;
// There is a fixed buffer of 5 for these, fill it up and leave.
while (iter != allowedMediums.end() && index < MAX_MEDIUMS) {
*mediums_[index++] = iter[index];
}
*mediums_size = allowed.GetMediums(true).size();
return;
}
} // namespace nearby::windows
-52
View File
@@ -1,52 +0,0 @@
// Copyright 2021-2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_NEARBY_CONNECTIONS_C_CONNECTION_OPTIONS_W_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_C_CONNECTION_OPTIONS_W_H_
#include <string>
#include "connections/c/dll_config.h"
#include "connections/c/medium_selector_w.h"
#include "connections/c/options_base_w.h"
namespace nearby::windows {
extern "C" {
#define MAX_MEDIUMS 6
// Connection Options: used for both Advertising and Discovery.
// All fields are mutable, to make the type copy-assignable.
struct DLL_API ConnectionOptionsW : public OptionsBaseW {
bool auto_upgrade_bandwidth = true;
bool enforce_topology_constraints;
bool low_power;
// Whether this is intended to be used in conjunction with InjectEndpoint().
bool is_out_of_band_connection = false;
const char* remote_bluetooth_mac_address;
const char* fast_advertisement_service_uuid;
int keep_alive_interval_millis = 0;
int keep_alive_timeout_millis = 0;
void GetMediums(const MediumW*, size_t*) const;
private:
MediumW* mediums_[MAX_MEDIUMS];
size_t mediums_size;
};
} // extern "C"
} // namespace nearby::windows
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_C_CONNECTION_OPTIONS_W_H_
-291
View File
@@ -1,291 +0,0 @@
// Copyright 2021-2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "connections/c/core_adapter.h"
#include "absl/strings/str_format.h"
#include "connections/core.h"
#include "internal/platform/bluetooth_utils.h"
#include "internal/platform/logging.h"
namespace nearby::windows {
Core *InitCore(connections::ServiceControllerRouter *router) {
#if defined(LOG_SEVERITY_VERBOSE)
absl::SetGlobalVLogLevel(1);
#endif // LOG_SEVERITY_VERBOSE;
return new nearby::connections::Core(router);
}
void CloseCore(Core *pCore) {
if (pCore == nullptr) {
return;
}
pCore->StopAllEndpoints([](Status) {});
delete pCore;
}
void StartAdvertising(Core *pCore, const char *service_id,
AdvertisingOptionsW advertising_options_w,
ConnectionRequestInfoW info, ResultCallbackW callback) {
if (pCore == nullptr) {
return;
}
connections::ConnectionRequestInfo crInfo;
crInfo.endpoint_info = ByteArray(info.endpoint_info, info.endpoint_info_size);
crInfo.listener = std::move(*(info.listener.GetImpl()));
connections::AdvertisingOptions advertising_options;
advertising_options.allowed.bluetooth =
advertising_options_w.allowed.bluetooth;
advertising_options.allowed.ble = advertising_options_w.allowed.ble;
advertising_options.allowed.wifi_lan = advertising_options_w.allowed.wifi_lan;
advertising_options.allowed.web_rtc = advertising_options_w.allowed.web_rtc;
advertising_options.allowed.wifi_hotspot =
advertising_options_w.allowed.wifi_hotspot;
advertising_options.enable_bluetooth_listening = false;
advertising_options.enable_webrtc_listening = false;
advertising_options.auto_upgrade_bandwidth =
advertising_options_w.auto_upgrade_bandwidth;
advertising_options.enforce_topology_constraints =
advertising_options_w.enforce_topology_constraints;
if (advertising_options_w.fast_advertisement_service_uuid != nullptr) {
advertising_options.fast_advertisement_service_uuid =
std::string(advertising_options_w.fast_advertisement_service_uuid);
}
advertising_options.is_out_of_band_connection =
advertising_options_w.is_out_of_band_connection;
advertising_options.low_power = advertising_options_w.low_power;
if (advertising_options_w.strategy == StrategyW::kNone)
advertising_options.strategy = connections::Strategy::kNone;
if (advertising_options_w.strategy == StrategyW::kP2pCluster)
advertising_options.strategy = connections::Strategy::kP2pCluster;
if (advertising_options_w.strategy == StrategyW::kP2pPointToPoint)
advertising_options.strategy = connections::Strategy::kP2pPointToPoint;
if (advertising_options_w.strategy == StrategyW::kP2pStar)
advertising_options.strategy = connections::Strategy::kP2pStar;
pCore->StartAdvertising(service_id, advertising_options, crInfo,
std::move(*callback.GetImpl()));
}
void StopAdvertising(connections::Core *pCore, ResultCallbackW callback) {
if (pCore == nullptr) {
return;
}
pCore->StopAdvertising(std::move(*callback.GetImpl()));
}
void StartDiscovery(connections::Core *pCore, const char *service_id,
DiscoveryOptionsW discovery_options_w,
DiscoveryListenerW listener, ResultCallbackW callback) {
if (pCore == nullptr) {
return;
}
connections::DiscoveryOptions discovery_options;
if (discovery_options_w.strategy == StrategyW::kNone)
discovery_options.strategy = connections::Strategy::kNone;
if (discovery_options_w.strategy == StrategyW::kP2pCluster)
discovery_options.strategy = connections::Strategy::kP2pCluster;
if (discovery_options_w.strategy == StrategyW::kP2pPointToPoint)
discovery_options.strategy = connections::Strategy::kP2pPointToPoint;
if (discovery_options_w.strategy == StrategyW::kP2pStar)
discovery_options.strategy = connections::Strategy::kP2pStar;
discovery_options.auto_upgrade_bandwidth =
discovery_options_w.auto_upgrade_bandwidth;
discovery_options.enforce_topology_constraints =
discovery_options_w.enforce_topology_constraints;
discovery_options.is_out_of_band_connection =
discovery_options_w.is_out_of_band_connection;
if (discovery_options_w.fast_advertisement_service_uuid) {
discovery_options.fast_advertisement_service_uuid =
std::string(discovery_options_w.fast_advertisement_service_uuid);
}
discovery_options.allowed.bluetooth = discovery_options_w.allowed.bluetooth;
discovery_options.allowed.ble = discovery_options_w.allowed.ble;
discovery_options.allowed.wifi_lan = discovery_options_w.allowed.wifi_lan;
discovery_options.allowed.wifi_hotspot =
discovery_options_w.allowed.wifi_hotspot;
discovery_options.allowed.web_rtc = discovery_options_w.allowed.web_rtc;
pCore->StartDiscovery(service_id, discovery_options,
std::move(*listener.GetImpl()),
std::move(*callback.GetImpl()));
}
void StopDiscovery(connections::Core *pCore, ResultCallbackW callback) {
if (pCore == nullptr) {
return;
}
pCore->StopDiscovery(std::move(*callback.GetImpl()));
}
void InjectEndpoint(connections::Core *pCore, char *service_id,
OutOfBandConnectionMetadataW metadata,
ResultCallbackW callback) {
if (pCore == nullptr) {
return;
}
connections::OutOfBandConnectionMetadata outOfBandConnectionMetadata;
outOfBandConnectionMetadata.endpoint_id = metadata.endpoint_id;
outOfBandConnectionMetadata.endpoint_info = {metadata.endpoint_info,
metadata.endpoint_info_size};
outOfBandConnectionMetadata.medium = metadata.medium;
outOfBandConnectionMetadata.remote_bluetooth_mac_address = {
metadata.remote_bluetooth_mac_address,
metadata.remote_bluetooth_mac_address_size};
pCore->InjectEndpoint(service_id, outOfBandConnectionMetadata,
std::move(*callback.GetImpl()));
}
void RequestConnection(connections::Core *pCore, const char *endpoint_id,
ConnectionRequestInfoW info,
ConnectionOptionsW connection_options_w,
ResultCallbackW callback) {
if (pCore == nullptr) {
return;
}
connections::ConnectionRequestInfo connectionRequestInfo =
connections::ConnectionRequestInfo();
connectionRequestInfo.endpoint_info = ByteArray(info.endpoint_info);
connectionRequestInfo.listener = std::move(*info.listener.GetImpl());
connections::ConnectionOptions connection_options;
connection_options.allowed.ble = connection_options_w.allowed.ble;
connection_options.allowed.bluetooth = connection_options_w.allowed.bluetooth;
connection_options.allowed.web_rtc = connection_options_w.allowed.web_rtc;
connection_options.allowed.wifi_lan = connection_options_w.allowed.wifi_lan;
connection_options.auto_upgrade_bandwidth =
connection_options_w.auto_upgrade_bandwidth;
connection_options.enforce_topology_constraints =
connection_options_w.enforce_topology_constraints;
if (connection_options_w.fast_advertisement_service_uuid) {
connection_options.fast_advertisement_service_uuid =
std::string(connection_options_w.fast_advertisement_service_uuid);
}
connection_options.is_out_of_band_connection =
connection_options_w.is_out_of_band_connection;
connection_options.keep_alive_interval_millis =
connection_options_w.keep_alive_interval_millis;
connection_options.keep_alive_timeout_millis =
connection_options_w.keep_alive_timeout_millis;
connection_options.low_power = connection_options_w.low_power;
if (connection_options_w.remote_bluetooth_mac_address) {
connection_options.remote_bluetooth_mac_address =
BluetoothUtils::FromString(
connection_options_w.remote_bluetooth_mac_address);
}
if (connection_options_w.strategy == StrategyW::kNone)
connection_options.strategy = connections::Strategy::kNone;
if (connection_options_w.strategy == StrategyW::kP2pCluster)
connection_options.strategy = connections::Strategy::kP2pCluster;
if (connection_options_w.strategy == StrategyW::kP2pPointToPoint)
connection_options.strategy = connections::Strategy::kP2pPointToPoint;
if (connection_options_w.strategy == StrategyW::kP2pStar)
connection_options.strategy = connections::Strategy::kP2pStar;
pCore->RequestConnection(endpoint_id, connectionRequestInfo,
connection_options, std::move(*callback.GetImpl()));
}
void AcceptConnection(connections::Core *pCore, const char *endpoint_id,
PayloadListenerW listener, ResultCallbackW callback) {
if (pCore == nullptr) {
return;
}
connections::PayloadListener payload_listener =
std::move(*listener.GetImpl());
pCore->AcceptConnection(endpoint_id, std::move(payload_listener),
std::move(*callback.GetImpl()));
}
void RejectConnection(connections::Core *pCore, const char *endpoint_id,
ResultCallbackW callback) {
if (pCore == nullptr) {
return;
}
pCore->RejectConnection(endpoint_id, std::move(*callback.GetImpl()));
}
void SendPayload(connections::Core *pCore,
// todo(jfcarroll) this is being exported, needs to be
// refactored to return a plain old c type
const char **endpoint_ids, size_t endpoint_ids_size,
PayloadW payloadw, ResultCallbackW callback) {
if (pCore == nullptr) {
return;
}
std::string payloadData = std::string(*endpoint_ids);
absl::Span<const std::string> span{&payloadData, 1};
pCore->SendPayload(span, std::move(*payloadw.GetImpl()),
std::move(*callback.GetImpl()));
}
void CancelPayload(connections::Core *pCore, std::int64_t payload_id,
ResultCallbackW callback) {
if (pCore == nullptr) {
return;
}
pCore->CancelPayload(payload_id, std::move(*callback.GetImpl()));
}
void DisconnectFromEndpoint(connections::Core *pCore, const char *endpoint_id,
ResultCallbackW callback) {
if (pCore == nullptr) {
return;
}
pCore->DisconnectFromEndpoint(endpoint_id, std::move(*callback.GetImpl()));
}
void StopAllEndpoints(connections::Core *pCore, ResultCallbackW callback) {
if (pCore == nullptr) {
return;
}
pCore->StopAllEndpoints(std::move(*callback.GetImpl()));
}
void InitiateBandwidthUpgrade(connections::Core *pCore, char *endpoint_id,
ResultCallbackW callback) {
if (pCore == nullptr) {
return;
}
pCore->InitiateBandwidthUpgrade(endpoint_id, std::move(*callback.GetImpl()));
}
const char *GetLocalEndpointId(connections::Core *pCore) {
if (pCore == nullptr) {
return "Null-Core";
}
std::string endpoint_id = pCore->GetLocalEndpointId();
char *result = new char[endpoint_id.length() + 1];
absl::SNPrintF(result, endpoint_id.length() + 1, "%s", endpoint_id);
return result;
}
connections::ServiceControllerRouter *InitServiceControllerRouter() {
return new connections::ServiceControllerRouter();
}
void CloseServiceControllerRouter(
connections::ServiceControllerRouter *pRouter) {
if (pRouter != nullptr) {
delete pRouter;
}
}
} // namespace nearby::windows
-260
View File
@@ -1,260 +0,0 @@
// Copyright 2021-2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_NEARBY_CONNECTIONS_C_CORE_ADAPTER_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_C_CORE_ADAPTER_H_
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "connections/c/advertising_options_w.h"
#include "connections/c/connection_options_w.h"
#include "connections/c/discovery_options_w.h"
#include "connections/c/listeners_w.h"
#include "connections/c/out_of_band_connection_metadata_w.h"
#include "connections/c/params_w.h"
#include "connections/c/payload_w.h"
namespace nearby::connections {
class Core;
class ServiceController;
class ServiceControllerRouter;
class OfflineServiceController;
} // namespace nearby::connections
namespace nearby::windows {
extern "C" {
using Core = connections::Core;
using ServiceControllerRouter = connections::ServiceControllerRouter;
// Initializes a Core instance, providing the ServiceController factory from
// app side. If no factory is provided, it will initialize a new
// factory creating OfflineServiceController.
// Returns the instance handle to c# client.
// TODO(jfcarroll): Is this method needed? The trouble is we can't
// new up a forward declared class (OfflineServiceController). If this
// is necessary, must find another way to implement it.
// DLL_API Core *__stdcall InitCoreWithServiceControllerFactory(
// std::function<ServiceController *()> factory = []() {
// return new OfflineServiceController;
// });
// Initializes a default Core instance.
// Returns the instance handle to c# client.
DLL_API Core* __stdcall InitCore(ServiceControllerRouter*);
// Closes the core with stopping all endpoints, then free the memory.
DLL_API void __stdcall CloseCore(Core*);
// Starts advertising an endpoint for a local app.
//
// service_id - An identifier to advertise your app to other endpoints.
// This can be an arbitrary string, so long as it uniquely
// identifies your service. A good default is to use your
// app's package name.
// advertising_options - The options for advertising.
// info - Connection parameters:
// > name - A human readable name for this endpoint, to appear on
// other devices.
// > listener - A callback notified when remote endpoints request a
// connection to this endpoint.
// callback - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK if advertising started successfully.
// Status::STATUS_ALREADY_ADVERTISING if the app is already advertising.
// Status::STATUS_OUT_OF_ORDER_API_CALL if the app is currently
// connected to remote endpoints; call StopAllEndpoints first.
DLL_API void __stdcall StartAdvertising(Core*, const char*, AdvertisingOptionsW,
ConnectionRequestInfoW,
ResultCallbackW);
// Stops advertising a local endpoint. Should be called after calling
// StartAdvertising, as soon as the application no longer needs to advertise
// itself or goes inactive. Payloads can still be sent to connected
// endpoints after advertising ends.
//
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK if none of the above errors occurred.
DLL_API void __stdcall StopAdvertising(Core*, ResultCallbackW);
// Starts discovery for remote endpoints with the specified service ID.
//
// service_id - The ID for the service to be discovered, as specified in
// the corresponding call to StartAdvertising.
// listener - A callback notified when a remote endpoint is discovered.
// discovery_options - The options for discovery.
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK if discovery started successfully.
// Status::STATUS_ALREADY_DISCOVERING if the app is already
// discovering the specified service.
// Status::STATUS_OUT_OF_ORDER_API_CALL if the app is currently
// connected to remote endpoints; call StopAllEndpoints first.
DLL_API void __stdcall StartDiscovery(Core*, const char*, DiscoveryOptionsW,
DiscoveryListenerW, ResultCallbackW);
// Stops discovery for remote endpoints, after a previous call to
// StartDiscovery, when the client no longer needs to discover endpoints or
// goes inactive. Payloads can still be sent to connected endpoints after
// discovery ends.
//
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK if none of the above errors occurred.
DLL_API void __stdcall StopDiscovery(Core*, ResultCallbackW);
// Invokes the discovery callback from a previous call to StartDiscovery()
// with the given endpoint info. The previous call to StartDiscovery() must
// have been passed ConnectionOptions with is_out_of_band_connection == true.
//
// service_id - The ID for the service to be discovered, as
// specified in the corresponding call to
// StartDiscovery().
// metadata - Metadata used in order to inject the endpoint.
// result_cb - to access the status of the operation when
// available.
// Possible status codes include:
// Status::kSuccess if endpoint injection was attempted.
// Status::kError if endpoint_id, endpoint_info, or
// remote_bluetooth_mac_address are malformed.
// Status::kOutOfOrderApiCall if the app is not discovering.
DLL_API void __stdcall InjectEndpoint(Core*, char*,
OutOfBandConnectionMetadataW,
ResultCallbackW);
// Sends a request to connect to a remote endpoint.
//
// endpoint_id - The identifier for the remote endpoint to which a
// connection request will be sent. Should match the value
// provided in a call to
// DiscoveryListener::endpoint_found_cb()
// info - Connection parameters:
// > name - A human readable name for the local endpoint, to appear on
// the remote endpoint.
// > listener - A callback notified when the remote endpoint sends a
// response to the connection request.
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK if the connection request was sent.
// Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT if the app already
// has a connection to the specified endpoint.
// Status::STATUS_RADIO_ERROR if we failed to connect because of an
// issue with Bluetooth/WiFi.
// Status::STATUS_ERROR if we failed to connect for any other reason.
DLL_API void __stdcall RequestConnection(Core*, const char*,
ConnectionRequestInfoW,
ConnectionOptionsW, ResultCallbackW);
// Accepts a connection to a remote endpoint. This method must be called
// before Payloads can be exchanged with the remote endpoint.
//
// endpoint_id - The identifier for the remote endpoint. Should match the
// value provided in a call to
// ConnectionListener::onConnectionInitiated.
// listener - A callback for payloads exchanged with the remote endpoint.
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK if the connection request was accepted.
// Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT if the app already.
// has a connection to the specified endpoint.
DLL_API void __stdcall AcceptConnection(Core*, const char*, PayloadListenerW,
ResultCallbackW);
// Rejects a connection to a remote endpoint.
//
// endpoint_id - The identifier for the remote endpoint. Should match the
// value provided in a call to
// ConnectionListener::onConnectionInitiated().
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK} if the connection request was rejected.
// Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT} if the app already
// has a connection to the specified endpoint.
DLL_API void __stdcall RejectConnection(Core*, const char*, ResultCallbackW);
// Sends a Payload to a remote endpoint. Payloads can only be sent to remote
// endpoints once a notice of connection acceptance has been delivered via
// ConnectionListener::onConnectionResult().
//
// endpoint_ids - Array of remote endpoint identifiers for the to which the
// payload should be sent.
// payload - The Payload to be sent.
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OUT_OF_ORDER_API_CALL if the device has not first
// performed advertisement or discovery (to set the Strategy.)
// Status::STATUS_ENDPOINT_UNKNOWN if there's no active (or pending)
// connection to the remote endpoint.
// Status::STATUS_OK if none of the above errors occurred. Note that this
// indicates that Nearby Connections will attempt to send the Payload,
// but not that the send has successfully completed yet. Errors might
// still occur during transmission (and at different times for
// different endpoints), and will be delivered via
// PayloadCallback#onPayloadTransferUpdate.
DLL_API void __stdcall SendPayload(Core*, const char**, size_t, PayloadW,
ResultCallbackW);
// Cancels a Payload currently in-flight to or from remote endpoint(s).
//
// payload_id - The identifier for the Payload to be canceled.
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK if none of the above errors occurred.
DLL_API void __stdcall CancelPayload(Core*, int64_t, ResultCallbackW);
// Disconnects from a remote endpoint. {@link Payload}s can no longer be sent
// to or received from the endpoint after this method is called.
//
// endpoint_id - The identifier for the remote endpoint to disconnect from.
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK - finished successfully.
DLL_API void __stdcall DisconnectFromEndpoint(Core*, const char*,
ResultCallbackW);
// Disconnects from, and removes all traces of, all connected and/or
// discovered endpoints. This call also stops advertising and discovery. After
// calling StopAllEndpoints, no further operations with remote endpoints will be
// possible until a new call to one of StartAdvertising() or StartDiscovery().
//
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK - finished successfully.
DLL_API void __stdcall StopAllEndpoints(Core*, ResultCallbackW);
// Sends a request to initiate connection bandwidth upgrade.
//
// endpoint_id - The identifier for the remote endpoint which will be
// switching to a higher connection data rate and possibly
// different wireless protocol. On success, calls
// ConnectionListener::bandwidth_changed_cb().
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK - finished successfully.
DLL_API void __stdcall InitiateBandwidthUpgrade(Core*, char*, ResultCallbackW);
// Gets the local endpoint generated by Nearby Connections.
DLL_API const char* __stdcall GetLocalEndpointId(Core*);
// Initializes a default ServiceControllerRouter instance.
// Returns the instance handle to c# client.
DLL_API ServiceControllerRouter* __stdcall InitServiceControllerRouter();
// Close a ServiceControllerRouter instance.
DLL_API void __stdcall CloseServiceControllerRouter(ServiceControllerRouter*);
} // extern "C"
} // namespace nearby::windows
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_C_CORE_ADAPTER_H_
-48
View File
@@ -1,48 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "connections/c/discovery_options_w.h"
#include <string>
namespace nearby::windows {
// Returns a copy and normalizes allowed mediums:
// (1) If is_out_of_band_connection is true, verifies that there is only one
// medium allowed, defaulting to only Bluetooth if unspecified.
// (2) If no mediums are allowed, allow all mediums.
DiscoveryOptionsW DiscoveryOptionsW::CompatibleOptions() const {
DiscoveryOptionsW result = *this;
// Out-of-band connections initiate connections via an injected endpoint
// rather than through the normal discovery flow. These types of connections
// can only be injected via a single medium.
if (is_out_of_band_connection) {
int num_enabled = result.allowed.Count(true);
// Default to allow only Bluetooth if no single medium is specified.
if (num_enabled != 1) {
result.allowed.SetAll(false);
result.allowed.bluetooth = true;
}
return result;
}
// Normal connections (i.e., not out-of-band) connections can specify
// multiple mediums. If none are specified, default to allowing all mediums.
if (!allowed.Any(true)) result.allowed.SetAll(true);
return result;
}
} // namespace nearby::windows
-44
View File
@@ -1,44 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_NEARBY_CONNECTIONS_C_DISCOVERY_OPTIONS_W_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_C_DISCOVERY_OPTIONS_W_H_
#include <string>
#include "connections/c/options_base_w.h"
namespace nearby::windows {
extern "C" {
// Connection Options: used for both Advertising and Discovery.
// All fields are mutable, to make the type copy-assignable.
struct DLL_API DiscoveryOptionsW : public OptionsBaseW {
bool auto_upgrade_bandwidth = true;
bool enforce_topology_constraints;
// Whether this is intended to be used in conjunction with InjectEndpoint().
bool is_out_of_band_connection = false;
const char* fast_advertisement_service_uuid;
// Returns a copy and normalizes allowed mediums:
// (1) If is_out_of_band_connection is true, verifies that there is only one
// medium allowed, defaulting to only Bluetooth if unspecified.
// (2) If no mediums are allowed, allow all mediums.
DiscoveryOptionsW CompatibleOptions() const;
};
} // extern "C"
} // namespace nearby::windows
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_C_DISCOVERY_OPTIONS_W_H_
-34
View File
@@ -1,34 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_NEARBY_CONNECTIONS_C_CONFIG_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_C_CONFIG_H_
namespace nearby::windows {
#ifdef _WIN32 // These storage class specifiers only matter to win32 dll
// builds.
#ifdef CORE_ADAPTER_DLL
#define DLL_API \
__declspec(dllexport) // If we're building the core, we're exporting.
#else // !CORE_ADAPTER_DLL
#define DLL_API \
__declspec(dllimport) // If we're not building the core, we're importing.
#endif // CORE_ADAPTER_DLL
#else // !_WIN32
#define DLL_API // We're not building a win32 dll, leave the source unchanged.
#endif // _WIN32
} // namespace nearby::windows
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_C_CONFIG_H_
-58
View File
@@ -1,58 +0,0 @@
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Rule for specialized expansion of template files. This performs a simple search over the template
file for the keys $VERSION and $VS_VERSION and replaces them with the corresponding values, derived
from the version provided. Supports make variables.
Typical usage:
load("expand_version_template.bzl", "expand_version_template")
expand_version_template(
name = "ExpandMyTemplate",
out = "my.txt",
template = "my.template",
version = varref("VERSION"),
)
Args:
name: The name of the rule.
out: The destination of the expanded file
template: The template file to expand
version: A string containing the version number. Supports make variables.
"""
def expand_version_template_impl(ctx):
version = ctx.expand_make_variables(
"expand_version_template",
ctx.attr.version,
{},
)
vs_version = version.replace(".", ",")
ctx.actions.expand_template(
template = ctx.file.template,
output = ctx.outputs.out,
substitutions = {
"$VERSION": version,
"$VS_VERSION": vs_version,
},
)
expand_version_template = rule(
implementation = expand_version_template_impl,
attrs = {
"template": attr.label(mandatory = True, allow_single_file = True),
"version": attr.string(mandatory = False),
"out": attr.output(mandatory = True),
},
)
-67
View File
@@ -1,67 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "connections/c/file_w.h"
#include <string>
#include "internal/platform/file.h"
namespace nearby {
void InputFileDeleter::operator()(nearby::InputFile* p) { delete p; }
void OutputFileDeleter::operator()(nearby::OutputFile* p) { delete p; }
namespace windows {
InputFileW::InputFileW(InputFile* input_file)
: impl_(std::unique_ptr<nearby::InputFile, nearby::InputFileDeleter>(
new nearby::InputFile(std::move(*input_file)))) {}
InputFileW::InputFileW(PayloadId payload_id, size_t size)
: impl_(std::unique_ptr<nearby::InputFile, nearby::InputFileDeleter>(
new nearby::InputFile(payload_id, size))) {}
InputFileW::InputFileW(const char* file_path, size_t size)
: impl_(std::unique_ptr<nearby::InputFile, nearby::InputFileDeleter>(
new nearby::InputFile(file_path, size))) {}
InputFileW::InputFileW(InputFileW&& other) noexcept
: impl_(std::move(other.impl_)) {}
// Returns a string that uniquely identifies this file.
// Caller allocates buffer[MAX_PATH] and is responsible
// for freeing.
void InputFileW::GetFilePath(char* file_path) const {
std::string fp = impl_->GetFilePath();
strncpy(file_path, fp.c_str(), fp.length());
}
// Returns total size of this file in bytes.
size_t InputFileW::GetTotalSize() const { return impl_->GetTotalSize(); }
std::unique_ptr<nearby::InputFile, nearby::InputFileDeleter>
InputFileW::GetImpl() {
return std::move(impl_);
}
OutputFileW::OutputFileW(PayloadId payload_id) {}
OutputFileW::OutputFileW(const char* file_path) {}
OutputFileW::OutputFileW(OutputFileW&&) noexcept {}
OutputFileW& OutputFileW::operator=(OutputFileW&& other) noexcept {
impl_ = std::move(other.impl_);
return *this;
}
std::unique_ptr<nearby::OutputFile, nearby::OutputFileDeleter>
OutputFileW::GetImpl() {
return std::move(impl_);
}
} // namespace windows
} // namespace nearby
-74
View File
@@ -1,74 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_NEARBY_CONNECTIONS_C_FILE_W_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_C_FILE_W_H_
#include <memory>
#include <string>
#include "connections/c/dll_config.h"
#include "internal/platform/payload_id.h"
namespace nearby {
class InputFile;
struct DLL_API InputFileDeleter {
void operator()(InputFile* p);
};
class OutputFile;
struct DLL_API OutputFileDeleter {
void operator()(OutputFile* p);
};
} // namespace nearby
namespace nearby {
namespace windows {
class DLL_API InputFileW {
public:
explicit InputFileW(nearby::InputFile* input_file);
InputFileW(nearby::PayloadId payload_id, size_t size);
InputFileW(const char* file_path, size_t size);
InputFileW(InputFileW&&) noexcept;
// Returns a string that uniquely identifies this file.
void GetFilePath(char* file_path) const;
// Returns total size of this file in bytes.
size_t GetTotalSize() const;
std::unique_ptr<nearby::InputFile, nearby::InputFileDeleter> GetImpl();
private:
std::unique_ptr<nearby::InputFile, nearby::InputFileDeleter> impl_;
};
class DLL_API OutputFileW {
public:
explicit OutputFileW(nearby::PayloadId payload_id);
explicit OutputFileW(const char* file_path);
OutputFileW(OutputFileW&&) noexcept;
OutputFileW& operator=(OutputFileW&&) noexcept;
std::unique_ptr<nearby::OutputFile, nearby::OutputFileDeleter> GetImpl();
private:
std::unique_ptr<nearby::OutputFile, nearby::OutputFileDeleter> impl_;
};
} // namespace windows
} // namespace nearby
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_C_FILE_W_H_
-50
View File
@@ -1,50 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "connections/c/input_stream_w.h"
#include "internal/platform/input_stream.h"
namespace nearby {
void InputStreamDeleter::operator()(nearby::InputStream* p) { delete p; }
} // namespace nearby
namespace nearby {
namespace windows {
char* InputStreamW::Read(size_t size) {
auto result = impl_->Read(size);
if (result.ok()) {
return result.GetResult().data();
}
return nullptr;
}
int64_t InputStreamW::Skip(size_t offset) {
auto result = impl_->Skip(offset);
if (result.ok()) {
return result.GetResult();
}
return -1;
}
int64_t InputStreamW::Close() {
auto result = impl_->Close();
if (result.Ok()) {
return 0;
}
return -1;
}
} // namespace windows
} // namespace nearby
-47
View File
@@ -1,47 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_NEARBY_CONNECTIONS_C_INPUT_STREAM_W_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_C_INPUT_STREAM_W_H_
#include <memory>
namespace nearby {
class InputStream;
struct InputStreamDeleter {
void operator()(InputStream* p);
};
} // namespace nearby
namespace nearby {
namespace windows {
class InputStreamW {
public:
char* Read(size_t size);
// throws Exception::kIo
int64_t Skip(size_t offset);
// throws Exception::kIo
int64_t Close();
private:
std::unique_ptr<nearby::InputStream, nearby::InputStreamDeleter> impl_;
};
} // namespace windows
} // namespace nearby
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_C_INPUT_STREAM_W_H_
-267
View File
@@ -1,267 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <memory>
#include <utility>
#include "connections/c/listeners_w.h"
#include "connections/listeners.h"
namespace nearby {
// Must implement Deleters, since the connections classes weren't
// fully defined in the header
namespace connections {
void ConnectionListenerDeleter::operator()(connections::ConnectionListener *p) {
delete p;
}
void DiscoveryListenerDeleter::operator()(connections::DiscoveryListener *p) {
delete p;
}
void PayloadListenerDeleter::operator()(connections::PayloadListener *p) {
delete p;
}
} // namespace connections
namespace windows {
static ResultCallbackW *ResultCallbackImpl;
void ResultCB(Status status) { ResultCallbackImpl->result_cb(status); }
ResultCallbackW::ResultCallbackW()
: impl(std::make_unique<connections::ResultCallback>(ResultCB)) {
ResultCallbackImpl = this;
}
ResultCallbackW::~ResultCallbackW() {}
ResultCallbackW::ResultCallbackW(ResultCallbackW &other) {
impl = std::move(other.impl);
}
ResultCallbackW::ResultCallbackW(ResultCallbackW &&other) noexcept {
impl = std::move(other.impl);
}
ConnectionListenerW::ConnectionListenerW(InitiatedCB initiatedCB,
AcceptedCB acceptedCB,
RejectedCB rejectedCB,
DisconnectedCB disconnectedCB,
BandwidthChangedCB bandwidthChangedCB)
: initiated_cb(initiatedCB),
accepted_cb(acceptedCB),
rejected_cb(rejectedCB),
disconnected_cb(disconnectedCB),
bandwidth_changed_cb(bandwidthChangedCB),
impl_(std::unique_ptr<connections::ConnectionListener,
connections::ConnectionListenerDeleter>(
new connections::ConnectionListener())) {
CHECK(initiated_cb != nullptr);
auto i = initiated_cb;
impl_->initiated_cb =
[i](const std::string &endpoint_id,
const connections::ConnectionResponseInfo connection_response_info) {
ConnectionResponseInfoW connection_response_info_w{
connection_response_info.remote_endpoint_info.data(),
connection_response_info.remote_endpoint_info.size(),
connection_response_info.authentication_token.c_str(),
connection_response_info.raw_authentication_token.data(),
connection_response_info.raw_authentication_token.size(),
connection_response_info.is_incoming_connection,
connection_response_info.is_connection_verified};
i(endpoint_id.c_str(), connection_response_info_w);
};
CHECK(accepted_cb != nullptr);
auto a = accepted_cb;
impl_->accepted_cb = [a](const std::string &endpoint_id) {
a(endpoint_id.c_str());
};
CHECK(rejected_cb != nullptr);
auto r = rejected_cb;
impl_->rejected_cb = [r](const std::string &endpoint_id, Status status) {
r(endpoint_id.c_str(), status);
};
CHECK(disconnected_cb != nullptr);
auto d = disconnected_cb;
impl_->disconnected_cb = [d](const std::string &endpoint_id) {
d(endpoint_id.c_str());
};
CHECK(bandwidth_changed_cb != nullptr);
auto bwc = bandwidth_changed_cb;
impl_->bandwidth_changed_cb = [bwc](const std::string &endpoint_id,
connections::Medium medium) {
bwc(endpoint_id.c_str(), medium);
};
}
ConnectionListenerW::ConnectionListenerW(ConnectionListenerW &other) {
impl_ = std::move(other.impl_);
accepted_cb = other.accepted_cb;
bandwidth_changed_cb = other.bandwidth_changed_cb;
disconnected_cb = other.disconnected_cb;
initiated_cb = other.initiated_cb;
rejected_cb = other.rejected_cb;
}
ConnectionListenerW::ConnectionListenerW(ConnectionListenerW &&other) noexcept =
default;
DiscoveryListenerW::DiscoveryListenerW(
EndpointFoundCB endpointFoundCB, EndpointLostCB endpointLostCB,
EndpointDistanceChangedCB endpointDistanceChangedCB)
: endpoint_found_cb(endpointFoundCB),
endpoint_lost_cb(endpointLostCB),
endpoint_distance_changed_cb(endpointDistanceChangedCB),
impl_(new connections::DiscoveryListener()) {
CHECK(endpoint_distance_changed_cb != nullptr);
auto epdc = endpoint_distance_changed_cb;
impl_->endpoint_distance_changed_cb =
[epdc](const std::string &endpoint_id,
connections::DistanceInfo distance_info) {
DistanceInfoW distanceInfoW = DistanceInfoW::kUnknown;
switch (distance_info) {
case connections::DistanceInfo::kFar:
distanceInfoW = DistanceInfoW::kFar;
break;
case connections::DistanceInfo::kClose:
distanceInfoW = DistanceInfoW::kFar;
break;
case connections::DistanceInfo::kVeryClose:
distanceInfoW = DistanceInfoW::kVeryClose;
break;
case connections::DistanceInfo::kUnknown:
break;
}
epdc(endpoint_id.c_str(), distanceInfoW);
};
CHECK(endpoint_found_cb != nullptr);
auto epf = endpoint_found_cb;
impl_->endpoint_found_cb = [epf](const std::string &endpoint_id,
ByteArray endpoint_info,
const std::string &service_id) {
epf(endpoint_id.c_str(), endpoint_info.data(), endpoint_info.size(),
service_id.c_str());
};
CHECK(endpoint_lost_cb != nullptr);
auto epl = endpoint_lost_cb;
impl_->endpoint_lost_cb = [epl](const std::string &endpoint_id) {
epl(endpoint_id.c_str());
};
}
DiscoveryListenerW::DiscoveryListenerW(DiscoveryListenerW &other) {
endpoint_distance_changed_cb = other.endpoint_distance_changed_cb;
endpoint_found_cb = other.endpoint_found_cb;
endpoint_lost_cb = other.endpoint_lost_cb;
impl_ = std::move(other.impl_);
}
DiscoveryListenerW::DiscoveryListenerW(DiscoveryListenerW &&other) noexcept {
endpoint_distance_changed_cb = other.endpoint_distance_changed_cb;
endpoint_found_cb = other.endpoint_found_cb;
endpoint_lost_cb = other.endpoint_lost_cb;
impl_ = std::move(other.impl_);
}
PayloadListenerW::PayloadListenerW(PayloadCB payloadCB,
PayloadProgressCB payloadProgressCB)
: payload_cb(payloadCB),
payload_progress_cb(payloadProgressCB),
impl_(std::unique_ptr<connections::PayloadListener,
connections::PayloadListenerDeleter>(
new connections::PayloadListener())) {
CHECK(payload_cb != nullptr);
auto pcb = payload_cb;
impl_->payload_cb = [pcb](absl::string_view endpoint_id,
connections::Payload payload) {
PayloadW payloadW;
switch (payload.GetType()) {
case connections::PayloadType::kBytes: {
payloadW = PayloadW(payload.GetId(), payload.AsBytes().data(),
payload.AsBytes().size());
break;
}
case connections::PayloadType::kFile: {
InputFileW file(std::move(payload.AsFile()));
payloadW = PayloadW(payload.GetId(), std::move(file));
} break;
// TODO(jfcarroll): Figure out how to capture type kStream.
// case connections::PayloadType::kStream: {
// payloadW = PayloadW(payload.AsStream());
//}
case connections::PayloadType::kStream: {
InputFileW file(std::move(payload.AsFile()));
payloadW = PayloadW(payload.GetId(), std::move(file));
} break;
case connections::PayloadType::kUnknown: {
// Throw exception here?
break;
}
}
pcb(std::string(endpoint_id).c_str(), payloadW);
};
CHECK(payload_progress_cb != nullptr);
auto ppcb = payload_progress_cb;
impl_->payload_progress_cb =
[ppcb](absl::string_view endpoint_id,
connections::PayloadProgressInfo payload_progress_info) {
PayloadProgressInfoW payload_progress_info_w;
payload_progress_info_w.payload_id = payload_progress_info.payload_id;
payload_progress_info_w.total_bytes = payload_progress_info.total_bytes;
payload_progress_info_w.bytes_transferred =
payload_progress_info.bytes_transferred;
switch (payload_progress_info.status) {
case connections::PayloadProgressInfo::Status::kCanceled:
payload_progress_info_w.status =
PayloadProgressInfoW::Status::kCanceled;
break;
case connections::PayloadProgressInfo::Status::kFailure:
payload_progress_info_w.status =
PayloadProgressInfoW::Status::kFailure;
break;
case connections::PayloadProgressInfo::Status::kInProgress:
payload_progress_info_w.status =
PayloadProgressInfoW::Status::kInProgress;
break;
case connections::PayloadProgressInfo::Status::kSuccess:
payload_progress_info_w.status =
PayloadProgressInfoW::Status::kSuccess;
break;
}
ppcb(std::string(endpoint_id).c_str(), payload_progress_info_w);
};
}
PayloadListenerW::PayloadListenerW(PayloadListenerW &other) {
impl_ = std::move(other.impl_);
}
PayloadListenerW::PayloadListenerW(PayloadListenerW &&other) noexcept {
impl_ = std::move(other.impl_);
}
} // namespace windows
} // namespace nearby
-291
View File
@@ -1,291 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_NEARBY_CONNECTIONS_C_LISTENERS_W_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_C_LISTENERS_W_H_
#include <memory>
#include <utility>
// This file defines all the protocol listeners and their parameter structures.
// Listeners are defined as collections of std::function<T> instances, which is
// more flexible than a virtual function:
// - a subset of listener callbacks may be overridden, while others may remain
// default-initialized.
// - callbacks may be initialized with lambdas; lambda definitions are concize.
#include "connections/c/medium_selector_w.h"
#include "connections/c/payload_w.h"
#include "connections/status.h"
#include "internal/platform/payload_id.h"
namespace nearby {
// Forward declarations
namespace connections {
struct ConnectionListener;
struct DLL_API ConnectionListenerDeleter {
void operator()(connections::ConnectionListener* p);
};
struct DiscoveryListener;
struct DLL_API DiscoveryListenerDeleter {
void operator()(connections::DiscoveryListener* p);
};
struct PayloadListener;
struct DLL_API PayloadListenerDeleter {
void operator()(connections::PayloadListener* p);
};
using ResultCallback = absl::AnyInvocable<void(Status)>;
struct ConnectionResponseInfo;
struct PayloadProgressInfo;
} // namespace connections
namespace windows {
using ::nearby::connections::Status;
template <class T>
T DefaultConstructor() {
return T();
}
template <class T>
void DefaultConstructor(T t) {}
template <class T, class C>
void DefaultConstructor(T t, C c) {}
template <class T, class C, class D>
void DefaultConstructor(T t, C c, size_t size, D d) {}
extern "C" {
// Common callback for asynchronously invoked methods.
// Called after a job scheduled for execution is completed.
// This is not the same as completion of the associated process,
// which may have many states, and multiple async jobs, and be still ongoing.
// Progress on the overall process is reported by the associated listener.
struct DLL_API ResultCallbackW {
// Callback to access the status of the operation when available.
// status - result of job execution;
// Status::kSuccess, if successful; anything else indicates failure.
ResultCallbackW();
~ResultCallbackW();
ResultCallbackW(ResultCallbackW& other);
ResultCallbackW(ResultCallbackW&& other) noexcept;
void (*result_cb)(Status status) = DefaultConstructor;
std::unique_ptr<connections::ResultCallback> GetImpl() {
return std::move(impl);
}
private:
std::unique_ptr<connections::ResultCallback> impl;
};
struct DLL_API ConnectionResponseInfoW {
const char* remote_endpoint_info;
size_t remote_endpoint_info_size;
const char* authentication_token;
const char* raw_authentication_token;
size_t raw_authentication_token_size;
bool is_incoming_connection = false;
bool is_connection_verified = false;
};
struct DLL_API PayloadProgressInfoW {
PayloadId payload_id = 0;
enum class Status {
kSuccess,
kFailure,
kInProgress,
kCanceled,
} status = Status::kSuccess;
size_t total_bytes = 0;
size_t bytes_transferred = 0;
};
enum class DLL_API DistanceInfoW {
kUnknown = 1,
kVeryClose = 2,
kClose = 3,
kFar = 4,
};
struct DLL_API ConnectionListenerW {
typedef void (*InitiatedCB)(const char* endpoint_id,
const ConnectionResponseInfoW& info);
typedef void (*AcceptedCB)(const char* endpoint_id);
typedef void (*RejectedCB)(const char* endpoint_id, Status status);
typedef void (*DisconnectedCB)(const char* endpoint_id);
typedef void (*BandwidthChangedCB)(const char* endpoint_id, MediumW medium);
ConnectionListenerW(InitiatedCB, AcceptedCB, RejectedCB, DisconnectedCB,
BandwidthChangedCB);
ConnectionListenerW(ConnectionListenerW& other);
ConnectionListenerW(ConnectionListenerW&& other) noexcept;
// A basic encrypted channel has been created between you and the endpoint.
// Both sides are now asked if they wish to accept or reject the connection
// before any data can be sent over this channel.
//
// This is your chance, before you accept the connection, to confirm that you
// connected to the correct device. Both devices are given an identical token;
// it's up to you to decide how to verify it before proceeding. Typically this
// involves showing the token on both devices and having the users manually
// compare and confirm; however, this is only required if you desire a secure
// connection between the devices.
//
// Whichever route you decide to take (including not authenticating the other
// device), call Core::AcceptConnection() when you're ready to talk, or
// Core::RejectConnection() to close the connection.
//
// endpoint_id - The identifier for the remote endpoint.
// info - Other relevant information about the connection.
InitiatedCB initiated_cb = DefaultConstructor;
// Called after both sides have accepted the connection.
// Both sides may now send Payloads to each other.
// Call Core::SendPayload() or wait for incoming PayloadListener::OnPayload().
//
// endpoint_id - The identifier for the remote endpoint.
AcceptedCB accepted_cb = DefaultConstructor;
// Called when either side rejected the connection.
// Payloads can not be exchanged. Call Core::DisconnectFromEndpoint()
// to terminate connection.
//
// endpoint_id - The identifier for the remote endpoint.
RejectedCB rejected_cb = DefaultConstructor;
// 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.
DisconnectedCB disconnected_cb = DefaultConstructor;
// Called when the connection's available bandwidth has changed.
//
// endpoint_id - The identifier for the remote endpoint.
// medium - Medium we upgraded to.
BandwidthChangedCB bandwidth_changed_cb = DefaultConstructor;
std::unique_ptr<connections::ConnectionListener,
connections::ConnectionListenerDeleter>
GetImpl() {
return std::move(impl_);
}
private:
std::unique_ptr<connections::ConnectionListener,
connections::ConnectionListenerDeleter>
impl_;
};
struct DLL_API DiscoveryListenerW {
typedef void (*EndpointFoundCB)(const char* endpoint_id,
const char* endpoint_info,
size_t endpoint_info_size,
const char* service_id);
typedef void (*EndpointLostCB)(const char* endpoint_id);
typedef void (*EndpointDistanceChangedCB)(const char* endpoint_id,
DistanceInfoW info);
DiscoveryListenerW(EndpointFoundCB endpointFoundCB,
EndpointLostCB endpointLostCB,
EndpointDistanceChangedCB endpointDistanceChangedCB);
DiscoveryListenerW(DiscoveryListenerW& other);
DiscoveryListenerW(DiscoveryListenerW&& other) noexcept;
// Called when a remote endpoint is discovered.
//
// endpoint_id - The ID of the remote endpoint that was discovered.
// endpoint_info - The info of the remote endpoint represented by ByteArray.
// service_id - The ID of the service advertised by the remote endpoint.
EndpointFoundCB endpoint_found_cb = DefaultConstructor;
// Called when a remote endpoint is no longer discoverable; only called for
// endpoints that previously had been passed to {@link
// #onEndpointFound(String, DiscoveredEndpointInfo)}.
//
// endpoint_id - The ID of the remote endpoint that was lost.
EndpointLostCB endpoint_lost_cb = DefaultConstructor;
// Called when a remote endpoint is found with an updated distance.
//
// arguments:
// endpoint_id - The ID of the remote endpoint that was lost.
// info - The distance info, encoded as enum value.
EndpointDistanceChangedCB endpoint_distance_changed_cb = DefaultConstructor;
std::unique_ptr<connections::DiscoveryListener,
connections::DiscoveryListenerDeleter>
GetImpl() {
return std::move(impl_);
}
private:
std::unique_ptr<connections::DiscoveryListener,
connections::DiscoveryListenerDeleter>
impl_;
};
struct DLL_API PayloadListenerW {
typedef void (*PayloadCB)(const char* endpoint_id, PayloadW& payload);
typedef void (*PayloadProgressCB)(const char* endpoint_id,
const PayloadProgressInfoW& info);
PayloadListenerW(PayloadCB, PayloadProgressCB);
PayloadListenerW(PayloadListenerW& other);
PayloadListenerW(PayloadListenerW&& other) noexcept;
// Called when a Payload is received from a remote endpoint. Depending
// on the type of the Payload, all of the data may or may not have been
// received at the time of this call. Use OnPayloadProgress() to
// get updates on the status of the data received.
//
// endpoint_id - The identifier for the remote endpoint that sent the
// payload.
// payload - The Payload object received.
PayloadCB payload_cb = DefaultConstructor;
// Called with progress information about an active Payload transfer, either
// incoming or outgoing.
//
// endpoint_id - The identifier for the remote endpoint that is sending or
// receiving this payload.
// info - The PayloadProgressInfo structure describing the status of
// the transfer.
PayloadProgressCB payload_progress_cb = DefaultConstructor;
std::unique_ptr<connections::PayloadListener,
connections::PayloadListenerDeleter>
GetImpl() {
return std::move(impl_);
}
private:
std::unique_ptr<connections::PayloadListener,
connections::PayloadListenerDeleter>
impl_;
};
} // extern "C"
} // namespace windows
} // namespace nearby
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_C_LISTENERS_W_H_
-84
View File
@@ -1,84 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_NEARBY_CONNECTIONS_C_MEDIUM_SELECTOR_W_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_C_MEDIUM_SELECTOR_W_H_
#include <vector>
#include "proto/connections_enums.pb.h"
namespace nearby::windows {
using MediumW = ::location::nearby::proto::connections::Medium;
// Feature On/Off switch for mediums.
struct BooleanMediumSelectorW {
bool bluetooth;
bool ble;
bool web_rtc;
bool wifi_lan;
bool wifi_hotspot;
bool wifi_direct;
BooleanMediumSelectorW() = default;
constexpr BooleanMediumSelectorW(const BooleanMediumSelectorW&) = default;
constexpr BooleanMediumSelectorW& operator=(const BooleanMediumSelectorW&) =
default;
constexpr bool Any(const bool value) const {
return bluetooth == value || ble == value || web_rtc == value ||
wifi_lan == value || wifi_hotspot == value || wifi_direct == value;
}
constexpr bool All(const bool value) const {
return bluetooth == value && ble == value && web_rtc == value &&
wifi_lan == value && wifi_hotspot == value && wifi_direct == value;
}
constexpr int Count(const bool value) const {
int count = 0;
if (bluetooth == value) ++count;
if (ble == value) ++count;
if (wifi_lan == value) ++count;
if (wifi_hotspot == value) ++count;
if (wifi_direct == value) ++count;
if (web_rtc == value) ++count;
return count;
}
constexpr BooleanMediumSelectorW& SetAll(const bool value) {
bluetooth = value;
ble = value;
web_rtc = value;
wifi_lan = value;
wifi_hotspot = value;
wifi_direct = value;
return *this;
}
std::vector<MediumW> GetMediums(const bool value) const {
std::vector<MediumW> mediums;
// Mediums are sorted in order of decreasing preference.
if (wifi_lan == value) mediums.push_back(MediumW::WIFI_LAN);
if (wifi_direct == value) mediums.push_back(MediumW::WIFI_DIRECT);
if (wifi_hotspot == value) mediums.push_back(MediumW::WIFI_HOTSPOT);
if (web_rtc == value) mediums.push_back(MediumW::WEB_RTC);
if (bluetooth == value) mediums.push_back(MediumW::BLUETOOTH);
if (ble == value) mediums.push_back(MediumW::BLE);
return mediums;
}
};
} // namespace nearby::windows
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_C_MEDIUM_SELECTOR_W_H_
-34
View File
@@ -1,34 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_NEARBY_CONNECTIONS_C_OPTIONS_BASE_W_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_C_OPTIONS_BASE_W_H_
#include "connections/c/medium_selector_w.h"
#include "connections/c/strategy_w.h"
namespace nearby::windows {
extern "C" {
// Connection Options: used for both Advertising and Discovery.
// All fields are mutable, to make the type copy-assignable.
struct OptionsBaseW {
nearby::windows::StrategyW strategy;
BooleanMediumSelectorW allowed{BooleanMediumSelectorW().SetAll(true)};
};
} // extern "C"
} // namespace nearby::windows
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_C_OPTIONS_BASE_W_H_
@@ -1,58 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_NEARBY_CONNECTIONS_C_OUT_OF_BAND_CONNECTION_METADATA_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_C_OUT_OF_BAND_CONNECTION_METADATA_H_
#include <string>
#include "connections/c/medium_selector_w.h"
#include "connections/c/strategy_w.h"
#include "internal/platform/byte_array.h"
#include "proto/connections_enums.pb.h"
namespace nearby::windows {
extern "C" {
// Metadata injected to facilitate out-of-band connections. The medium field is
// required, and the other fields are only specified for a specific medium.
// Currently, Bluetooth is the only supported medium for out-of-band
// connections.
struct DLL_API OutOfBandConnectionMetadataW {
// Medium to use for the out-of-band connection.
MediumW medium;
// Endpoint ID to use for the injected connection; will be included in the
// endpoint_found_cb callback. Must be exactly 4 bytes and should be randomly-
// generated such that no two IDs are identical.
const char* endpoint_id;
// Endpoint info to use for the injected connection; will be included in the
// endpoint_found_cb callback. Should uniquely identify the InjectEndpoint()
// call so that the client which made the call can verify the endpoint
// that was found is the one that was injected.
//
// Cannot be empty, and must be <131 bytes.
const char* endpoint_info;
size_t endpoint_info_size;
// Used for Bluetooth connections.
const char* remote_bluetooth_mac_address;
size_t remote_bluetooth_mac_address_size;
};
} // extern "C"
} // namespace nearby::windows
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_C_OUT_OF_BAND_CONNECTION_METADATA_H_
-42
View File
@@ -1,42 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_NEARBY_CONNECTIONS_C_PARAMS_W_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_C_PARAMS_W_H_
#include <string>
#include "connections/c/listeners_w.h"
namespace nearby::windows {
extern "C" {
// Used by Discovery in Core::RequestConnection().
// Used by Advertising in Core::StartAdvertising().
struct DLL_API ConnectionRequestInfoW {
// endpoint_info - Identifying information about this endpoint (eg. name,
// device type).
// listener - A set of callbacks notified when remote endpoints request a
// connection to this endpoint.
// ByteArray endpoint_info;
const char* endpoint_info;
size_t endpoint_info_size;
ConnectionListenerW& listener;
};
} // extern "C"
} // namespace nearby::windows
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_C_PARAMS_W_H_
-138
View File
@@ -1,138 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "connections/c/payload_w.h"
#include <cstddef>
#include <cstdint>
#include <memory>
#include <utility>
#include "connections/c/file_w.h"
#include "connections/payload.h"
#include "connections/payload_type.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/input_stream.h"
#include "internal/platform/payload_id.h"
namespace nearby {
// Must implement Deleter since Payload wasn't fully defined in
// the header
namespace connections {
class Payload;
void PayloadDeleter::operator()(connections::Payload *p) { delete p; }
} // namespace connections
namespace windows {
PayloadW::PayloadW()
: impl_(std::unique_ptr<connections::Payload, connections::PayloadDeleter>(
new connections::Payload())) {}
PayloadW::~PayloadW() = default;
PayloadW::PayloadW(PayloadW &&other) noexcept : impl_(std::move(other.impl_)) {}
PayloadW &PayloadW::operator=(PayloadW &&other) noexcept {
impl_ = std::move(other.impl_);
return *this;
}
// Constructors for outgoing payloads.
PayloadW::PayloadW(const char *bytes, const size_t bytes_size)
: impl_(std::unique_ptr<connections::Payload, connections::PayloadDeleter>(
new connections::Payload(ByteArray(bytes, bytes_size)))) {}
PayloadW::PayloadW(InputFileW &file)
: impl_(std::unique_ptr<connections::Payload, connections::PayloadDeleter>(
new connections::Payload(InputFile(std::move(*file.GetImpl()))))) {}
PayloadW::PayloadW(std::unique_ptr<InputStream> stream)
: impl_(std::unique_ptr<connections::Payload, connections::PayloadDeleter>(
new connections::Payload(std::move(stream)))) {}
// Constructors for incoming payloads.
PayloadW::PayloadW(PayloadId id, const char *bytes, const size_t bytes_size)
: impl_(std::unique_ptr<connections::Payload, connections::PayloadDeleter>(
new connections::Payload(id, ByteArray(bytes, bytes_size)))) {}
PayloadW::PayloadW(PayloadId id, InputFileW file)
: impl_(std::unique_ptr<connections::Payload, connections::PayloadDeleter>(
new connections::Payload(id, std::move(*file.GetImpl())))) {}
PayloadW::PayloadW(const char *parent_folder, const char *file_name,
InputFileW file)
: impl_(std::unique_ptr<connections::Payload, connections::PayloadDeleter>(
new connections::Payload(parent_folder, file_name,
std::move(*file.GetImpl())))) {}
PayloadW::PayloadW(PayloadId id, std::unique_ptr<InputStream> stream)
: impl_(std::unique_ptr<connections::Payload, connections::PayloadDeleter>(
new connections::Payload(id, std::move(stream)))) {}
// Returns ByteArray payload, if it has been defined, or empty ByteArray.
bool PayloadW::AsBytes(const char *&bytes, size_t &bytes_size) const & {
auto byteArray = impl_->AsBytes();
if (bytes_size < byteArray.size()) {
bytes_size = byteArray.size();
bytes = nullptr;
return false;
}
bytes_size = byteArray.size();
bytes = byteArray.data();
return true;
}
bool PayloadW::AsBytes(const char *&bytes, size_t &bytes_size) && {
auto byteArray = impl_->AsBytes();
if (bytes_size < byteArray.size()) {
bytes_size = byteArray.size();
bytes = nullptr;
return false;
}
bytes_size = byteArray.size();
bytes = byteArray.data();
return true;
}
// Returns InputStream* payload, if it has been defined, or nullptr.
InputStream *PayloadW::AsStream() { return impl_->AsStream(); }
// Returns InputFile* payload, if it has been defined, or nullptr.
InputFile *PayloadW::AsFile() const { return impl_->AsFile(); }
// Returns Payload unique ID.
int64_t PayloadW::GetId() const { return impl_->GetId(); }
// Returns Payload type.
const connections::PayloadType PayloadW::GetType() const {
return static_cast<connections::PayloadType>(impl_->GetType());
}
// Sets the payload offset in bytes
void PayloadW::SetOffset(size_t offset) { impl_->SetOffset(offset); }
size_t PayloadW::GetOffset() { return impl_->GetOffset(); }
// Generate Payload Id; to be passed to outgoing file constructor.
PayloadId PayloadW::GenerateId() { return connections::Payload::GenerateId(); }
const char *PayloadW::GetParentFolder() const { return nullptr; }
const char *PayloadW::GetFileName() const { return nullptr; }
std::unique_ptr<connections::Payload, connections::PayloadDeleter>
PayloadW::GetImpl() {
return std::move(impl_);
}
} // namespace windows
} // namespace nearby
-112
View File
@@ -1,112 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_NEARBY_CONNECTIONS_C_PAYLOAD_W_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_C_PAYLOAD_W_H_
#include <cstdint>
#include <functional>
#include <memory>
#include <utility>
#include "connections/c/dll_config.h"
#include "connections/c/file_w.h"
#include "connections/payload_type.h"
#include "internal/platform/payload_id.h"
namespace nearby {
namespace connections {
class Payload;
struct PayloadDeleter {
void operator()(Payload* p);
};
} // namespace connections
} // namespace nearby
namespace nearby {
class InputFile;
class InputStream;
} // namespace nearby
namespace nearby {
namespace windows {
extern "C" {
// Payload is default-constructible, and moveable, but not copyable container
// that holds at most one instance of one of:
// ByteArray, InputStream, or InputFile.
class DLL_API PayloadW {
public:
PayloadW(PayloadW&& other) noexcept;
PayloadW& operator=(PayloadW&& other) noexcept;
// Default (invalid) payload.
PayloadW();
~PayloadW();
// Constructors for outgoing payloads.
explicit PayloadW(const char* bytes, size_t size);
explicit PayloadW(InputFileW& file);
explicit PayloadW(std::unique_ptr<InputStream> stream);
// Constructors for incoming payloads.
PayloadW(PayloadId id, const char* bytes, size_t size);
PayloadW(PayloadId id, InputFileW file);
explicit PayloadW(const char* parent_folder, const char* file_name,
InputFileW file);
PayloadW(PayloadId id, std::unique_ptr<InputStream> stream);
// Returns ByteArray payload, if it has
// been defined, or empty ByteArray.
bool AsBytes(const char*& bytes, size_t& bytes_size) const&;
bool AsBytes(const char*& bytes, size_t& bytes_size) &&;
// Returns InputStream* payload, if it has been defined, or nullptr.
InputStream* AsStream();
// Returns InputFile* payload, if it has been defined, or nullptr.
InputFile* AsFile() const;
// Returns Payload unique ID.
int64_t GetId() const;
// Returns Payload type.
const nearby::connections::PayloadType GetType() const;
// Sets the payload offset in bytes
void SetOffset(size_t offset);
size_t GetOffset();
// Generate Payload Id; to be passed to outgoing file constructor.
static PayloadId GenerateId();
const char* GetFileName() const;
const char* GetParentFolder() const;
std::unique_ptr<connections::Payload, connections::PayloadDeleter> GetImpl();
private:
std::unique_ptr<connections::Payload, connections::PayloadDeleter> impl_;
};
} // extern "C"
} // namespace windows
} // namespace nearby
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_C_PAYLOAD_W_H_
-77
View File
@@ -1,77 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "connections/c/strategy_w.h"
#include <string>
namespace nearby::windows {
const StrategyW StrategyW::kNone = {StrategyW::ConnectionType::kNone,
StrategyW::TopologyType::kUnknown};
const StrategyW StrategyW::kP2pCluster{StrategyW::ConnectionType::kPointToPoint,
StrategyW::TopologyType::kManyToMany};
const StrategyW StrategyW::kP2pStar{StrategyW::ConnectionType::kPointToPoint,
StrategyW::TopologyType::kOneToMany};
const StrategyW StrategyW::kP2pPointToPoint{
StrategyW::ConnectionType::kPointToPoint,
StrategyW::TopologyType::kOneToOne};
// static
const StrategyW& StrategyW::GetStrategyNone() { return StrategyW::kNone; }
// static
const StrategyW& StrategyW::GetStrategyP2pCluster() {
return StrategyW::kP2pCluster;
}
// static
const StrategyW& StrategyW::GetStrategyP2pStar() { return StrategyW::kP2pStar; }
// static
const StrategyW& StrategyW::GetStrategyPointToPoint() {
return StrategyW::kP2pPointToPoint;
}
bool StrategyW::IsNone() const { return *this == kNone; }
bool StrategyW::IsValid() const {
return *this == kP2pStar || *this == kP2pCluster || *this == kP2pPointToPoint;
}
std::string StrategyW::GetName() const {
if (*this == StrategyW::kP2pCluster) {
return "P2P_CLUSTER";
}
if (*this == StrategyW::kP2pStar) {
return "P2P_STAR";
}
if (*this == StrategyW::kP2pPointToPoint) {
return "P2P_POINT_TO_POINT";
}
return "UNKNOWN";
}
void StrategyW::Clear() { *this = kNone; }
bool operator==(const StrategyW& lhs, const StrategyW& rhs) {
return lhs.connection_type_ == rhs.connection_type_ &&
lhs.topology_type_ == rhs.topology_type_;
}
bool operator!=(const StrategyW& lhs, const StrategyW& rhs) {
return !(lhs == rhs);
}
} // namespace nearby::windows
-76
View File
@@ -1,76 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_NEARBY_CONNECTIONS_C_STRATEGY_W_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_C_STRATEGY_W_H_
#include <string>
#include "connections/c/dll_config.h"
namespace nearby::windows {
// Defines a copyable, comparable connection strategy type.
// It is one of: kP2pCluster, kP2pStar, kP2pPointToPoint.
class DLL_API StrategyW {
public:
static const StrategyW kNone;
static const StrategyW kP2pCluster;
static const StrategyW kP2pStar;
static const StrategyW kP2pPointToPoint;
constexpr StrategyW() : StrategyW(kNone) {}
constexpr StrategyW(const StrategyW&) = default;
constexpr StrategyW& operator=(const StrategyW&) = default;
// Helper functions for exe to access static member variables in the dll.
static const StrategyW& GetStrategyNone();
static const StrategyW& GetStrategyP2pCluster();
static const StrategyW& GetStrategyP2pStar();
static const StrategyW& GetStrategyPointToPoint();
// Returns true, if strategy is kNone, false otherwise.
bool IsNone() const;
// Returns true, if a strategy is one of the supported strategies,
// false otherwise.
bool IsValid() const;
// Returns a string representing given strategy, for every valid strategy.
std::string GetName() const;
// Undefined strategy.
void Clear();
friend bool operator==(const StrategyW& lhs, const StrategyW& rhs);
friend bool operator!=(const StrategyW& lhs, const StrategyW& rhs);
private:
enum class ConnectionType {
kNone = 0,
kPointToPoint = 1,
};
enum class TopologyType {
kUnknown = 0,
kOneToOne = 1,
kOneToMany = 2,
kManyToMany = 3,
};
constexpr StrategyW(ConnectionType connection_type,
TopologyType topology_type)
: connection_type_(connection_type), topology_type_(topology_type) {}
ConnectionType connection_type_;
TopologyType topology_type_;
};
} // namespace nearby::windows
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_C_STRATEGY_W_H_
-32
View File
@@ -1,32 +0,0 @@
#include "winres.h"
VS_VERSION_INFO VERSIONINFO
FILEVERSION $VS_VERSION
PRODUCTVERSION $VS_VERSION
FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
#ifdef _DEBUG
FILEFLAGS VS_FF_DEBUG
#else
FILEFLAGS 0x0L
#endif
FILEOS VOS__WINDOWS32
FILETYPE VFT_APP
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904e4"
BEGIN
VALUE "CompanyName", "Google LLC"
VALUE "FileDescription", "Nearby Connections"
VALUE "FileVersion", "$VERSION"
VALUE "LegalCopyright", "Copyright (C) 2022 Google. All rights reserved." "\0"
VALUE "ProductName", "Nearby Connections"
VALUE "ProductVersion", "$VERSION"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1252
END
END