Merged from google/nearby main

This commit is contained in:
lasan
2024-10-22 11:27:36 +05:30
988 changed files with 175061 additions and 15634 deletions
+3 -2
View File
@@ -1,3 +1,4 @@
build --action_env=BAZEL_CXXOPTS=-std=c++17
build --action_env=BAZEL_CXXOPTS=-"std=c++20"
# Definition of --config=memcheck
build:memcheck --strip=never --test_timeout=3600
build:memcheck --strip=never --test_timeout=3600
common --enable_bzlmod
+14
View File
@@ -1,3 +1,17 @@
# 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.
name: 🐛 Bug Report
description: Report a reproducible bug or regression.
labels:
@@ -1,3 +1,17 @@
# 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.
name: 🪄 Feature Request
description: Request a new feature or enhancement.
labels:
+19 -5
View File
@@ -1,3 +1,17 @@
# 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.
name: Validate
on: [push, pull_request]
@@ -31,12 +45,12 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
submodules: recursive
- name: Build Connections
run: CC=clang CXX=clang++ bazel build --check_visibility=false //connections:core --spawn_strategy=standalone
run: CC=clang-15 CXX=clang-15++ bazel build --copt='-DGITHUB_BUILD' //connections:core
- name: Build Presence
run: CC=clang CXX=clang++ bazel build --check_visibility=false //presence --spawn_strategy=standalone
run: CC=clang-15 CXX=clang-15++ bazel build --copt='-DGITHUB_BUILD' //presence
- name: Build Sharing
run: CC=clang-15 CXX=clang-15++ bazel build --verbose_failures --copt='-DGITHUB_BUILD' //sharing:nearby_sharing_service //sharing/certificates //sharing/contacts //sharing/local_device_data //sharing/proto/... //sharing/internal/public:nearby_context //sharing/common:all //sharing/scheduling //sharing/fast_initiation:nearby_fast_initiation //sharing/analytics
build-rust-linux:
name: Build Rust on Linux
@@ -63,4 +77,4 @@ jobs:
run: cargo test --manifest-path fastpair/rust/bluetooth/Cargo.toml
- name: Build Fast Pair
run: cargo test --manifest-path fastpair/rust/demo/rust/Cargo.toml
+1 -4
View File
@@ -54,8 +54,5 @@ Carthage/Build
# Rust
Cargo.lock
# Bazel Build Directories
# Bazel
bazel-*
# Clang LSP compilation database
compile_commands.json
+99
View File
@@ -0,0 +1,99 @@
bazel_dep(name = "platforms", version = "0.0.8")
bazel_dep(name = "rules_cc", version = "0.0.9")
bazel_dep(name = "rules_rust", version = "0.42.1")
bazel_dep(name = "bazel_skylib", version = "1.5.0")
bazel_dep(name = "abseil-cpp", version = "20240116.1", repo_name = "com_google_absl")
bazel_dep(name = "protobuf", version = "21.7", repo_name = "com_google_protobuf")
bazel_dep(name = "googletest", version = "1.14.0", repo_name = "com_google_googletest")
bazel_dep(name = "boringssl", version = "0.0.0-20240126-22d349c")
git_repository = use_repo_rule("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
git_repository(
name = "beto-core",
remote = "https://beto-core.googlesource.com/beto-core",
commit = "415bd032561d078720642d52e28fd3bc9d5155d4",
)
rust = use_extension("@rules_rust//rust:extensions.bzl", "rust")
rust.toolchain(
edition = "2021",
versions = ["1.77.1"],
)
use_repo(rust, "rust_toolchains")
register_toolchains("@rust_toolchains//:all")
crate = use_extension(
"@rules_rust//crate_universe:extension.bzl",
"crate",
)
crate.from_cargo(
name = "crate_index",
cargo_lockfile = "@beto-core//:bazel_placeholder/Cargo.lock",
manifests = [
"@beto-core//:bazel_placeholder/Cargo.toml",
],
)
use_repo(crate, "crate_index")
http_archive = use_repo_rule("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "com_google_ukey2",
strip_prefix = "ukey2-master",
urls = ["https://github.com/google/ukey2/archive/master.zip"],
)
http_archive(
name = "aappleby_smhasher",
strip_prefix = "smhasher-master",
build_file_content = """
package(default_visibility = ["//visibility:public"])
cc_library(
name = "libmurmur3",
srcs = ["src/MurmurHash3.cpp"],
hdrs = ["src/MurmurHash3.h"],
copts = ["-Wno-implicit-fallthrough"],
licenses = ["unencumbered"], # MurmurHash is explicity public-domain
)""",
urls = ["https://github.com/aappleby/smhasher/archive/master.zip"],
)
http_archive(
name = "nlohmann_json",
strip_prefix = "json-3.10.5",
build_file_content = """
cc_library(
name = "json",
hdrs = glob([
"include/nlohmann/**/*.hpp",
]),
includes = ["include"],
visibility = ["//visibility:public"],
alwayslink = True,
)""",
urls = [
"https://github.com/nlohmann/json/archive/refs/tags/v3.10.5.tar.gz",
],
)
# ----------------------------------------------
# Nisaba: Script processing library from Google:
# ----------------------------------------------
# We depend on some of core C++ libraries from Nisaba and use the fresh code
# from the HEAD. See
# https://github.com/google-research/nisaba
http_archive(
name = "com_google_nisaba",
url = "https://github.com/google-research/nisaba/archive/refs/heads/main.zip",
strip_prefix = "nisaba-main",
)
# -------------------------------------------------------------------------
# Protocol buffer matches (should be part of gmock and gtest, but not yet):
# https://github.com/inazarenko/protobuf-matchers
http_archive(
name = "com_github_protobuf_matchers",
urls = ["https://github.com/inazarenko/protobuf-matchers/archive/refs/heads/master.zip"],
strip_prefix = "protobuf-matchers-master",
)
+14755
View File
File diff suppressed because it is too large Load Diff
+20 -22
View File
@@ -1,25 +1,23 @@
{
"object": {
"pins": [
{
"package": "abseil",
"repositoryURL": "https://github.com/bourdakos1/abseil-cpp-SwiftPM.git",
"state": {
"branch": "cxx17",
"revision": "a7042563d167160f56e614cd1e2a32616510d9ec",
"version": null
}
},
{
"package": "BoringSSL-GRPC",
"repositoryURL": "https://github.com/firebase/boringssl-SwiftPM.git",
"state": {
"branch": null,
"revision": "734a8247442fde37df4364c21f6a0085b6a36728",
"version": "0.7.2"
}
"pins" : [
{
"identity" : "abseil-cpp-swiftpm",
"kind" : "remoteSourceControl",
"location" : "https://github.com/bourdakos1/abseil-cpp-SwiftPM.git",
"state" : {
"branch" : "cxx17-test",
"revision" : "f2c56293ba0c7dc4fed62c38dfea5c5c2d632166"
}
]
},
"version": 1
},
{
"identity" : "boringssl-swiftpm",
"kind" : "remoteSourceControl",
"location" : "https://github.com/firebase/boringssl-SwiftPM.git",
"state" : {
"revision" : "734a8247442fde37df4364c21f6a0085b6a36728",
"version" : "0.7.2"
}
}
],
"version" : 2
}
+40 -14
View File
@@ -1,5 +1,20 @@
// swift-tools-version:5.5
// swift-tools-version:5.7
// The swift-tools-version declares the minimum version of Swift required to build this package.
// 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.
import PackageDescription
let package = Package(
@@ -13,23 +28,22 @@ let package = Package(
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "NearbyCoreAdapter",
targets: ["NearbyCoreAdapter"]
name: "NearbyConnections",
targets: ["NearbyConnections"]
),
.library(
name: "NearbyConnections",
name: "NearbyConnectionsDynamic",
type: .dynamic,
targets: ["NearbyConnections"]
),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(
name: "abseil",
url: "https://github.com/bourdakos1/abseil-cpp-SwiftPM.git",
branch: "cxx17"
branch: "cxx17-test"
),
.package(
name: "BoringSSL-GRPC",
url: "https://github.com/firebase/boringssl-SwiftPM.git",
"0.7.1"..<"0.8.0"
),
@@ -172,8 +186,10 @@ let package = Package(
name: "ukey2",
dependencies: [
"protobuf",
.product(name: "abseil", package: "abseil"),
.product(name: "openssl_grpc", package: "BoringSSL-GRPC"),
.product(name: "AbseilCXX17", package: "abseil-cpp-SwiftPM"),
.product(
name: "openssl_grpc", package: "boringssl-SwiftPM",
moduleAliases: ["NearbySSL": "openssl_grpc"]),
],
path: "third_party/ukey2",
exclude: [
@@ -362,7 +378,7 @@ let package = Package(
"smhasher",
"ukey2",
"protobuf",
.product(name: "abseil", package: "abseil"),
.product(name: "AbseilCXX17", package: "abseil-cpp-SwiftPM"),
],
path: ".",
exclude: [
@@ -372,12 +388,14 @@ let package = Package(
"connections/c",
"connections/connectionsd",
"connections/dart",
"connections/java",
"connections/clients/ios",
"connections/README.md",
"connections/swift/NearbyConnections",
"connections/swift/NearbyCoreAdapter/BUILD",
"connections/swift/NearbyCoreAdapter/Tests",
"internal/platform/implementation/g3",
"internal/platform/implementation/android",
"internal/platform/implementation/apple/Tests",
"internal/platform/implementation/apple/Mediums/Ble/Sockets/Tests",
"internal/platform/implementation/linux",
@@ -391,6 +409,7 @@ let package = Package(
"connections/implementation/analytics/BUILD",
"connections/implementation/flags/BUILD",
"connections/implementation/mediums/ble_v2/BUILD",
"connections/implementation/mediums/multiplex/BUILD",
"connections/implementation/mediums/BUILD",
"connections/implementation/BUILD",
"connections/implementation/fuzzers",
@@ -431,8 +450,9 @@ let package = Package(
"connections/implementation/payload_manager_test.cc",
"connections/implementation/offline_frames_validator_test.cc",
"connections/implementation/service_controller_router_test.cc",
"connections/implementation/bluetooth_bwu_test.cc",
"connections/implementation/wifi_direct_bwu_test.cc",
"connections/implementation/wifi_hotspot_test.cc",
"connections/implementation/wifi_hotspot_bwu_test.cc",
"connections/implementation/analytics/analytics_recorder_test.cc",
"connections/implementation/analytics/throughput_recorder_test.cc",
"connections/implementation/mediums/ble_v2_test.cc",
@@ -443,6 +463,11 @@ let package = Package(
"connections/implementation/mediums/ble_v2/ble_advertisement_header_test.cc",
"connections/implementation/mediums/ble_v2/ble_utils_test.cc",
"connections/implementation/mediums/ble_v2/discovered_peripheral_tracker_test.cc",
"connections/implementation/mediums/ble_v2/instant_on_lost_advertisement_test.cc",
"connections/implementation/mediums/ble_v2/instant_on_lost_manager_test.cc",
"connections/implementation/mediums/multiplex/multiplex_frames_test.cc",
"connections/implementation/mediums/multiplex/multiplex_socket_test.cc",
"connections/implementation/mediums/multiplex/multiplex_output_stream_test.cc",
"connections/implementation/mediums/webrtc_peer_id_test.cc",
"connections/implementation/mediums/wifi_lan_test.cc",
"connections/implementation/mediums/bluetooth_classic_test.cc",
@@ -462,6 +487,7 @@ let package = Package(
"connections/implementation/pcp_manager_test.cc",
"connections/implementation/ble_advertisement_test.cc",
"connections/implementation/base_endpoint_channel_test.cc",
"connections/implementation/reconnect_manager_test.cc",
"connections/v3/connections_device_test.cc",
"connections/v3/connections_device_provider_test.cc",
"connections/implementation/connections_authentication_transport_test.cc",
@@ -469,13 +495,13 @@ let package = Package(
"connections/status_test.cc",
"connections/payload_test.cc",
"internal/base/bluetooth_address_test.cc",
"internal/base/files_test.cc",
"internal/crypto/ed25519_unittest.cc",
"internal/crypto_cros/aead_unittest.cc",
"internal/crypto_cros/ec_private_key_unittest.cc",
"internal/crypto_cros/ec_signature_creator_unittest.cc",
"internal/crypto_cros/encryptor_unittest.cc",
"internal/crypto_cros/hmac_unittest.cc",
"internal/crypto_cros/random_unittest.cc",
"internal/crypto_cros/rsa_private_key_unittest.cc",
"internal/crypto_cros/secure_hash_unittest.cc",
"internal/crypto_cros/sha2_unittest.cc",
@@ -504,7 +530,6 @@ let package = Package(
"internal/platform/wifi_hotspot_test.cc",
"internal/platform/wifi_lan_test.cc",
"internal/platform/wifi_test.cc",
"internal/platform/wifi_utils_test.cc",
"internal/platform/connection_info_test.cc",
"internal/platform/condition_variable_test.cc",
"internal/platform/thread_check_nocompile_test.py",
@@ -512,7 +537,6 @@ let package = Package(
"internal/platform/bluetooth_connection_info_test.cc",
"internal/platform/mutex_test.cc",
"internal/platform/atomic_reference_test.cc",
"internal/platform/logging_test.cc",
"internal/platform/multi_thread_executor_test.cc",
"internal/platform/ble_connection_info_test.cc",
"internal/platform/ble_test.cc",
@@ -524,6 +548,7 @@ let package = Package(
"internal/platform/implementation/apple/atomic_boolean_test.cc",
"internal/platform/implementation/apple/atomic_uint32_test.cc",
"internal/platform/implementation/shared/file_test.cc",
"internal/platform/implementation/wifi_utils_test.cc",
"internal/platform/atomic_boolean_test.cc",
"internal/platform/exception_test.cc",
"internal/platform/error_code_recorder_test.cc",
@@ -597,6 +622,7 @@ let package = Package(
"compiled_proto",
"connections/c",
"connections/dart",
"connections/java",
"connections/clients/ios",
"connections/swift/NearbyCoreAdapter",
"connections/swift/NearbyConnections/BUILD",
+3 -192
View File
@@ -1,192 +1,3 @@
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
# Rule repository, note that it's recommended to use a pinned commit to a released version of the rules
http_archive(
name = "rules_foreign_cc",
strip_prefix = "rules_foreign_cc-0.6.0",
url = "https://github.com/bazelbuild/rules_foreign_cc/archive/0.6.0.tar.gz",
)
load("@rules_foreign_cc//foreign_cc:repositories.bzl", "rules_foreign_cc_dependencies")
# This sets up some common toolchains for building targets. For more details, please see
# https://github.com/bazelbuild/rules_foreign_cc/tree/main/docs#rules_foreign_cc_dependencies
rules_foreign_cc_dependencies()
_ALL_CONTENT = """\
filegroup(
name = "all_srcs",
srcs = glob(["**"]),
visibility = ["//visibility:public"],
)
"""
http_archive(
name = "com_google_absl",
strip_prefix = "abseil-cpp-master",
urls = ["https://github.com/abseil/abseil-cpp/archive/master.zip"],
)
# Using a protobuf javalite version that contains @com_google_protobuf_javalite//:javalite_toolchain
http_archive(
name = "com_google_protobuf_javalite",
strip_prefix = "protobuf-javalite",
urls = ["https://github.com/google/protobuf/archive/javalite.zip"],
)
http_archive(
name = "com_google_protobuf",
strip_prefix = "protobuf-3.17.0",
urls = ["https://github.com/protocolbuffers/protobuf/archive/v3.17.0.tar.gz"],
)
http_archive(
name = "com_google_protobuf_cc",
strip_prefix = "protobuf-3.17.0",
urls = ["https://github.com/protocolbuffers/protobuf/archive/v3.17.0.tar.gz"],
)
http_archive(
name = "com_google_protobuf_java",
strip_prefix = "protobuf-3.17.0",
urls = ["https://github.com/protocolbuffers/protobuf/archive/v3.17.0.tar.gz"],
)
http_archive(
name = "com_google_glog",
sha256 = "f28359aeba12f30d73d9e4711ef356dc842886968112162bc73002645139c39c",
strip_prefix = "glog-0.4.0",
urls = ["https://github.com/google/glog/archive/v0.4.0.tar.gz"],
)
http_archive(
name = "com_google_ukey2",
strip_prefix = "ukey2-master",
urls = ["https://github.com/google/ukey2/archive/master.zip"],
)
http_archive(
name = "aappleby_smhasher",
strip_prefix = "smhasher-master",
build_file_content = """
package(default_visibility = ["//visibility:public"])
cc_library(
name = "libmurmur3",
srcs = ["src/MurmurHash3.cpp"],
hdrs = ["src/MurmurHash3.h"],
copts = ["-Wno-implicit-fallthrough"],
licenses = ["unencumbered"], # MurmurHash is explicity public-domain
)""",
urls = ["https://github.com/aappleby/smhasher/archive/master.zip"],
)
http_archive(
name = "nlohmann_json",
strip_prefix = "json-3.10.5",
build_file_content = """
cc_library(
name = "json",
hdrs = glob([
"include/nlohmann/**/*.hpp",
]),
includes = ["include"],
visibility = ["//visibility:public"],
alwayslink = True,
)""",
urls = [
"https://github.com/nlohmann/json/archive/refs/tags/v3.10.5.tar.gz",
],
)
load("@com_google_protobuf//:protobuf_deps.bzl", "protobuf_deps")
# Load common dependencies.
protobuf_deps()
http_archive(
name = "com_google_googletest",
strip_prefix = "googletest-main",
urls = ["https://github.com/google/googletest/archive/main.zip"],
)
http_archive(
name = "com_google_webrtc",
build_file_content = """
package(default_visibility = ["//visibility:public"])
""",
urls = ["https://webrtc.googlesource.com/src/+archive/main.tar.gz"],
)
# gflags needed by glog
http_archive(
name = "com_github_gflags_gflags",
strip_prefix = "gflags-2.2.2",
sha256 = "19713a36c9f32b33df59d1c79b4958434cb005b5b47dc5400a7a4b078111d9b5",
url = "https://github.com/gflags/gflags/archive/v2.2.2.zip",
)
# ----------------------------------------------
# Nisaba: Script processing library from Google:
# ----------------------------------------------
# We depend on some of core C++ libraries from Nisaba and use the fresh code
# from the HEAD. See
# https://github.com/google-research/nisaba
nisaba_version = "main"
http_archive(
name = "com_google_nisaba",
url = "https://github.com/google-research/nisaba/archive/refs/heads/%s.zip" % nisaba_version,
strip_prefix = "nisaba-%s" % nisaba_version,
)
load("@com_google_nisaba//bazel:workspace.bzl", "nisaba_public_repositories")
nisaba_public_repositories()
http_archive(
name = "boringssl",
sha256 = "5d299325d1db8b2f2db3d927c7bc1f9fcbd05a3f9b5c8239fa527c09bf97f995", # Last updated 2022-10-19
strip_prefix = "boringssl-0acfcff4be10514aacb98eb8ab27bb60136d131b",
urls = ["https://github.com/google/boringssl/archive/0acfcff4be10514aacb98eb8ab27bb60136d131b.tar.gz"],
)
# -------------------------------------------------------------------------
# Protocol buffer matches (should be part of gmock and gtest, but not yet):
# https://github.com/inazarenko/protobuf-matchers
http_archive(
name = "com_github_protobuf_matchers",
urls = ["https://github.com/inazarenko/protobuf-matchers/archive/refs/heads/master.zip"],
strip_prefix = "protobuf-matchers-master",
)
http_archive(
name = "com_googlesource_code_re2",
sha256 = "26155e050b10b5969e986dab35654247a3b1b295e0532880b5a9c13c0a700ceb",
strip_prefix = "re2-2021-06-01",
urls = [
"https://github.com/google/re2/archive/refs/tags/2021-06-01.tar.gz",
],
)
# bazel_pkg_config
http_archive(
name = "bazel_pkg_config",
strip_prefix = "bazel_pkg_config-master",
urls = ["https://github.com/cherrry/bazel_pkg_config/archive/master.zip"],
)
load("@bazel_pkg_config//:pkg_config.bzl", "pkg_config")
pkg_config(
name = "libsystemd",
pkg_name = "libsystemd",
)
pkg_config(
name = "libcurl",
pkg_name = "libcurl",
)
pkg_config(
name = "sdbus_cpp",
pkg_name = "sdbus-c++",
)
# ================================================ #
# All dependencies have been moved to MODULE.Bazel #
# ================================================ #
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,311 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: internal/proto/analytics/experiments_log.proto
#include "internal/proto/analytics/experiments_log.pb.h"
#include <algorithm>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
PROTOBUF_PRAGMA_INIT_SEG
namespace nearby {
namespace experiments {
constexpr ExperimentsLog::ExperimentsLog(
::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized)
: experiment_token_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string)
, zwieback_cookie_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string){}
struct ExperimentsLogDefaultTypeInternal {
constexpr ExperimentsLogDefaultTypeInternal()
: _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {}
~ExperimentsLogDefaultTypeInternal() {}
union {
ExperimentsLog _instance;
};
};
PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT ExperimentsLogDefaultTypeInternal _ExperimentsLog_default_instance_;
} // namespace experiments
} // namespace nearby
namespace nearby {
namespace experiments {
// ===================================================================
class ExperimentsLog::_Internal {
public:
using HasBits = decltype(std::declval<ExperimentsLog>()._has_bits_);
static void set_has_experiment_token(HasBits* has_bits) {
(*has_bits)[0] |= 1u;
}
static void set_has_zwieback_cookie(HasBits* has_bits) {
(*has_bits)[0] |= 2u;
}
};
ExperimentsLog::ExperimentsLog(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned)
: ::PROTOBUF_NAMESPACE_ID::MessageLite(arena, is_message_owned) {
SharedCtor();
if (!is_message_owned) {
RegisterArenaDtor(arena);
}
// @@protoc_insertion_point(arena_constructor:nearby.experiments.ExperimentsLog)
}
ExperimentsLog::ExperimentsLog(const ExperimentsLog& from)
: ::PROTOBUF_NAMESPACE_ID::MessageLite(),
_has_bits_(from._has_bits_) {
_internal_metadata_.MergeFrom<std::string>(from._internal_metadata_);
experiment_token_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
experiment_token_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation());
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
if (from._internal_has_experiment_token()) {
experiment_token_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_experiment_token(),
GetArenaForAllocation());
}
zwieback_cookie_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
zwieback_cookie_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation());
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
if (from._internal_has_zwieback_cookie()) {
zwieback_cookie_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_zwieback_cookie(),
GetArenaForAllocation());
}
// @@protoc_insertion_point(copy_constructor:nearby.experiments.ExperimentsLog)
}
inline void ExperimentsLog::SharedCtor() {
experiment_token_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
experiment_token_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation());
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
zwieback_cookie_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
zwieback_cookie_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation());
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
}
ExperimentsLog::~ExperimentsLog() {
// @@protoc_insertion_point(destructor:nearby.experiments.ExperimentsLog)
if (GetArenaForAllocation() != nullptr) return;
SharedDtor();
_internal_metadata_.Delete<std::string>();
}
inline void ExperimentsLog::SharedDtor() {
GOOGLE_DCHECK(GetArenaForAllocation() == nullptr);
experiment_token_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
zwieback_cookie_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
void ExperimentsLog::ArenaDtor(void* object) {
ExperimentsLog* _this = reinterpret_cast< ExperimentsLog* >(object);
(void)_this;
}
void ExperimentsLog::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void ExperimentsLog::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
void ExperimentsLog::Clear() {
// @@protoc_insertion_point(message_clear_start:nearby.experiments.ExperimentsLog)
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
experiment_token_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000002u) {
zwieback_cookie_.ClearNonDefaultToEmpty();
}
}
_has_bits_.Clear();
_internal_metadata_.Clear<std::string>();
}
const char* ExperimentsLog::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
while (!ctx->Done(&ptr)) {
uint32_t tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
switch (tag >> 3) {
// optional bytes experiment_token = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 10)) {
auto str = _internal_mutable_experiment_token();
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx);
CHK_(ptr);
} else
goto handle_unusual;
continue;
// optional string zwieback_cookie = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 18)) {
auto str = _internal_mutable_zwieback_cookie();
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx);
CHK_(ptr);
} else
goto handle_unusual;
continue;
default:
goto handle_unusual;
} // switch
handle_unusual:
if ((tag == 0) || ((tag & 7) == 4)) {
CHK_(ptr);
ctx->SetLastTag(tag);
goto message_done;
}
ptr = UnknownFieldParse(
tag,
_internal_metadata_.mutable_unknown_fields<std::string>(),
ptr, ctx);
CHK_(ptr != nullptr);
} // while
message_done:
_has_bits_.Or(has_bits);
return ptr;
failure:
ptr = nullptr;
goto message_done;
#undef CHK_
}
uint8_t* ExperimentsLog::_InternalSerialize(
uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:nearby.experiments.ExperimentsLog)
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// optional bytes experiment_token = 1;
if (cached_has_bits & 0x00000001u) {
target = stream->WriteBytesMaybeAliased(
1, this->_internal_experiment_token(), target);
}
// optional string zwieback_cookie = 2;
if (cached_has_bits & 0x00000002u) {
target = stream->WriteStringMaybeAliased(
2, this->_internal_zwieback_cookie(), target);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = stream->WriteRaw(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).data(),
static_cast<int>(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:nearby.experiments.ExperimentsLog)
return target;
}
size_t ExperimentsLog::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:nearby.experiments.ExperimentsLog)
size_t total_size = 0;
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000003u) {
// optional bytes experiment_token = 1;
if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize(
this->_internal_experiment_token());
}
// optional string zwieback_cookie = 2;
if (cached_has_bits & 0x00000002u) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_zwieback_cookie());
}
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
total_size += _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size();
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void ExperimentsLog::CheckTypeAndMergeFrom(
const ::PROTOBUF_NAMESPACE_ID::MessageLite& from) {
MergeFrom(*::PROTOBUF_NAMESPACE_ID::internal::DownCast<const ExperimentsLog*>(
&from));
}
void ExperimentsLog::MergeFrom(const ExperimentsLog& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:nearby.experiments.ExperimentsLog)
GOOGLE_DCHECK_NE(&from, this);
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
_internal_set_experiment_token(from._internal_experiment_token());
}
if (cached_has_bits & 0x00000002u) {
_internal_set_zwieback_cookie(from._internal_zwieback_cookie());
}
}
_internal_metadata_.MergeFrom<std::string>(from._internal_metadata_);
}
void ExperimentsLog::CopyFrom(const ExperimentsLog& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:nearby.experiments.ExperimentsLog)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool ExperimentsLog::IsInitialized() const {
return true;
}
void ExperimentsLog::InternalSwap(ExperimentsLog* other) {
using std::swap;
auto* lhs_arena = GetArenaForAllocation();
auto* rhs_arena = other->GetArenaForAllocation();
_internal_metadata_.InternalSwap(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap(
&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
&experiment_token_, lhs_arena,
&other->experiment_token_, rhs_arena
);
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap(
&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
&zwieback_cookie_, lhs_arena,
&other->zwieback_cookie_, rhs_arena
);
}
std::string ExperimentsLog::GetTypeName() const {
return "nearby.experiments.ExperimentsLog";
}
// @@protoc_insertion_point(namespace_scope)
} // namespace experiments
} // namespace nearby
PROTOBUF_NAMESPACE_OPEN
template<> PROTOBUF_NOINLINE ::nearby::experiments::ExperimentsLog* Arena::CreateMaybeMessage< ::nearby::experiments::ExperimentsLog >(Arena* arena) {
return Arena::CreateMessageInternal< ::nearby::experiments::ExperimentsLog >(arena);
}
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
@@ -0,0 +1,394 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: internal/proto/analytics/experiments_log.proto
#ifndef GOOGLE_PROTOBUF_INCLUDED_internal_2fproto_2fanalytics_2fexperiments_5flog_2eproto
#define GOOGLE_PROTOBUF_INCLUDED_internal_2fproto_2fanalytics_2fexperiments_5flog_2eproto
#include <limits>
#include <string>
#include <google/protobuf/port_def.inc>
#if PROTOBUF_VERSION < 3019000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3019001 < PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
#define PROTOBUF_INTERNAL_EXPORT_internal_2fproto_2fanalytics_2fexperiments_5flog_2eproto
PROTOBUF_NAMESPACE_OPEN
namespace internal {
class AnyMetadata;
} // namespace internal
PROTOBUF_NAMESPACE_CLOSE
// Internal implementation detail -- do not use these members.
struct TableStruct_internal_2fproto_2fanalytics_2fexperiments_5flog_2eproto {
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[];
static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[];
static const uint32_t offsets[];
};
namespace nearby {
namespace experiments {
class ExperimentsLog;
struct ExperimentsLogDefaultTypeInternal;
extern ExperimentsLogDefaultTypeInternal _ExperimentsLog_default_instance_;
} // namespace experiments
} // namespace nearby
PROTOBUF_NAMESPACE_OPEN
template<> ::nearby::experiments::ExperimentsLog* Arena::CreateMaybeMessage<::nearby::experiments::ExperimentsLog>(Arena*);
PROTOBUF_NAMESPACE_CLOSE
namespace nearby {
namespace experiments {
// ===================================================================
class ExperimentsLog final :
public ::PROTOBUF_NAMESPACE_ID::MessageLite /* @@protoc_insertion_point(class_definition:nearby.experiments.ExperimentsLog) */ {
public:
inline ExperimentsLog() : ExperimentsLog(nullptr) {}
~ExperimentsLog() override;
explicit constexpr ExperimentsLog(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
ExperimentsLog(const ExperimentsLog& from);
ExperimentsLog(ExperimentsLog&& from) noexcept
: ExperimentsLog() {
*this = ::std::move(from);
}
inline ExperimentsLog& operator=(const ExperimentsLog& from) {
CopyFrom(from);
return *this;
}
inline ExperimentsLog& operator=(ExperimentsLog&& from) noexcept {
if (this == &from) return *this;
if (GetOwningArena() == from.GetOwningArena()
#ifdef PROTOBUF_FORCE_COPY_IN_MOVE
&& GetOwningArena() != nullptr
#endif // !PROTOBUF_FORCE_COPY_IN_MOVE
) {
InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const std::string& unknown_fields() const {
return _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString);
}
inline std::string* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<std::string>();
}
static const ExperimentsLog& default_instance() {
return *internal_default_instance();
}
static inline const ExperimentsLog* internal_default_instance() {
return reinterpret_cast<const ExperimentsLog*>(
&_ExperimentsLog_default_instance_);
}
static constexpr int kIndexInFileMessages =
0;
friend void swap(ExperimentsLog& a, ExperimentsLog& b) {
a.Swap(&b);
}
inline void Swap(ExperimentsLog* other) {
if (other == this) return;
#ifdef PROTOBUF_FORCE_COPY_IN_SWAP
if (GetOwningArena() != nullptr &&
GetOwningArena() == other->GetOwningArena()) {
#else // PROTOBUF_FORCE_COPY_IN_SWAP
if (GetOwningArena() == other->GetOwningArena()) {
#endif // !PROTOBUF_FORCE_COPY_IN_SWAP
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(ExperimentsLog* other) {
if (other == this) return;
GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
ExperimentsLog* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final {
return CreateMaybeMessage<ExperimentsLog>(arena);
}
void CheckTypeAndMergeFrom(const ::PROTOBUF_NAMESPACE_ID::MessageLite& from) final;
void CopyFrom(const ExperimentsLog& from);
void MergeFrom(const ExperimentsLog& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
uint8_t* _InternalSerialize(
uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(ExperimentsLog* other);
private:
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "nearby.experiments.ExperimentsLog";
}
protected:
explicit ExperimentsLog(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned = false);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
std::string GetTypeName() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kExperimentTokenFieldNumber = 1,
kZwiebackCookieFieldNumber = 2,
};
// optional bytes experiment_token = 1;
bool has_experiment_token() const;
private:
bool _internal_has_experiment_token() const;
public:
void clear_experiment_token();
const std::string& experiment_token() const;
template <typename ArgT0 = const std::string&, typename... ArgT>
void set_experiment_token(ArgT0&& arg0, ArgT... args);
std::string* mutable_experiment_token();
PROTOBUF_NODISCARD std::string* release_experiment_token();
void set_allocated_experiment_token(std::string* experiment_token);
private:
const std::string& _internal_experiment_token() const;
inline PROTOBUF_ALWAYS_INLINE void _internal_set_experiment_token(const std::string& value);
std::string* _internal_mutable_experiment_token();
public:
// optional string zwieback_cookie = 2;
bool has_zwieback_cookie() const;
private:
bool _internal_has_zwieback_cookie() const;
public:
void clear_zwieback_cookie();
const std::string& zwieback_cookie() const;
template <typename ArgT0 = const std::string&, typename... ArgT>
void set_zwieback_cookie(ArgT0&& arg0, ArgT... args);
std::string* mutable_zwieback_cookie();
PROTOBUF_NODISCARD std::string* release_zwieback_cookie();
void set_allocated_zwieback_cookie(std::string* zwieback_cookie);
private:
const std::string& _internal_zwieback_cookie() const;
inline PROTOBUF_ALWAYS_INLINE void _internal_set_zwieback_cookie(const std::string& value);
std::string* _internal_mutable_zwieback_cookie();
public:
// @@protoc_insertion_point(class_scope:nearby.experiments.ExperimentsLog)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr experiment_token_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr zwieback_cookie_;
friend struct ::TableStruct_internal_2fproto_2fanalytics_2fexperiments_5flog_2eproto;
};
// ===================================================================
// ===================================================================
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// ExperimentsLog
// optional bytes experiment_token = 1;
inline bool ExperimentsLog::_internal_has_experiment_token() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
return value;
}
inline bool ExperimentsLog::has_experiment_token() const {
return _internal_has_experiment_token();
}
inline void ExperimentsLog::clear_experiment_token() {
experiment_token_.ClearToEmpty();
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& ExperimentsLog::experiment_token() const {
// @@protoc_insertion_point(field_get:nearby.experiments.ExperimentsLog.experiment_token)
return _internal_experiment_token();
}
template <typename ArgT0, typename... ArgT>
inline PROTOBUF_ALWAYS_INLINE
void ExperimentsLog::set_experiment_token(ArgT0&& arg0, ArgT... args) {
_has_bits_[0] |= 0x00000001u;
experiment_token_.SetBytes(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation());
// @@protoc_insertion_point(field_set:nearby.experiments.ExperimentsLog.experiment_token)
}
inline std::string* ExperimentsLog::mutable_experiment_token() {
std::string* _s = _internal_mutable_experiment_token();
// @@protoc_insertion_point(field_mutable:nearby.experiments.ExperimentsLog.experiment_token)
return _s;
}
inline const std::string& ExperimentsLog::_internal_experiment_token() const {
return experiment_token_.Get();
}
inline void ExperimentsLog::_internal_set_experiment_token(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
experiment_token_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation());
}
inline std::string* ExperimentsLog::_internal_mutable_experiment_token() {
_has_bits_[0] |= 0x00000001u;
return experiment_token_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation());
}
inline std::string* ExperimentsLog::release_experiment_token() {
// @@protoc_insertion_point(field_release:nearby.experiments.ExperimentsLog.experiment_token)
if (!_internal_has_experiment_token()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
auto* p = experiment_token_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation());
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
if (experiment_token_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) {
experiment_token_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation());
}
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
return p;
}
inline void ExperimentsLog::set_allocated_experiment_token(std::string* experiment_token) {
if (experiment_token != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
experiment_token_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), experiment_token,
GetArenaForAllocation());
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
if (experiment_token_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) {
experiment_token_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation());
}
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
// @@protoc_insertion_point(field_set_allocated:nearby.experiments.ExperimentsLog.experiment_token)
}
// optional string zwieback_cookie = 2;
inline bool ExperimentsLog::_internal_has_zwieback_cookie() const {
bool value = (_has_bits_[0] & 0x00000002u) != 0;
return value;
}
inline bool ExperimentsLog::has_zwieback_cookie() const {
return _internal_has_zwieback_cookie();
}
inline void ExperimentsLog::clear_zwieback_cookie() {
zwieback_cookie_.ClearToEmpty();
_has_bits_[0] &= ~0x00000002u;
}
inline const std::string& ExperimentsLog::zwieback_cookie() const {
// @@protoc_insertion_point(field_get:nearby.experiments.ExperimentsLog.zwieback_cookie)
return _internal_zwieback_cookie();
}
template <typename ArgT0, typename... ArgT>
inline PROTOBUF_ALWAYS_INLINE
void ExperimentsLog::set_zwieback_cookie(ArgT0&& arg0, ArgT... args) {
_has_bits_[0] |= 0x00000002u;
zwieback_cookie_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation());
// @@protoc_insertion_point(field_set:nearby.experiments.ExperimentsLog.zwieback_cookie)
}
inline std::string* ExperimentsLog::mutable_zwieback_cookie() {
std::string* _s = _internal_mutable_zwieback_cookie();
// @@protoc_insertion_point(field_mutable:nearby.experiments.ExperimentsLog.zwieback_cookie)
return _s;
}
inline const std::string& ExperimentsLog::_internal_zwieback_cookie() const {
return zwieback_cookie_.Get();
}
inline void ExperimentsLog::_internal_set_zwieback_cookie(const std::string& value) {
_has_bits_[0] |= 0x00000002u;
zwieback_cookie_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation());
}
inline std::string* ExperimentsLog::_internal_mutable_zwieback_cookie() {
_has_bits_[0] |= 0x00000002u;
return zwieback_cookie_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation());
}
inline std::string* ExperimentsLog::release_zwieback_cookie() {
// @@protoc_insertion_point(field_release:nearby.experiments.ExperimentsLog.zwieback_cookie)
if (!_internal_has_zwieback_cookie()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000002u;
auto* p = zwieback_cookie_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation());
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
if (zwieback_cookie_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) {
zwieback_cookie_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation());
}
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
return p;
}
inline void ExperimentsLog::set_allocated_zwieback_cookie(std::string* zwieback_cookie) {
if (zwieback_cookie != nullptr) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
zwieback_cookie_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), zwieback_cookie,
GetArenaForAllocation());
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
if (zwieback_cookie_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) {
zwieback_cookie_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation());
}
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
// @@protoc_insertion_point(field_set_allocated:nearby.experiments.ExperimentsLog.zwieback_cookie)
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// @@protoc_insertion_point(namespace_scope)
} // namespace experiments
} // namespace nearby
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_internal_2fproto_2fanalytics_2fexperiments_5flog_2eproto
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+223 -33
View File
@@ -136,11 +136,12 @@ enum Medium : int {
WIFI_DIRECT = 8,
WEB_RTC = 9,
BLE_L2CAP = 10,
USB = 11
USB = 11,
WEB_RTC_NON_CELLULAR = 12
};
bool Medium_IsValid(int value);
constexpr Medium Medium_MIN = UNKNOWN_MEDIUM;
constexpr Medium Medium_MAX = USB;
constexpr Medium Medium_MAX = WEB_RTC_NON_CELLULAR;
constexpr int Medium_ARRAYSIZE = Medium_MAX + 1;
const std::string& Medium_Name(Medium value);
@@ -207,6 +208,25 @@ inline const std::string& ConnectionBand_Name(T enum_t_value) {
}
bool ConnectionBand_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, ConnectionBand* value);
enum ConnectionMode : int {
LEGACY = 0,
INSTANT = 1
};
bool ConnectionMode_IsValid(int value);
constexpr ConnectionMode ConnectionMode_MIN = LEGACY;
constexpr ConnectionMode ConnectionMode_MAX = INSTANT;
constexpr int ConnectionMode_ARRAYSIZE = ConnectionMode_MAX + 1;
const std::string& ConnectionMode_Name(ConnectionMode value);
template<typename T>
inline const std::string& ConnectionMode_Name(T enum_t_value) {
static_assert(::std::is_same<T, ConnectionMode>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function ConnectionMode_Name.");
return ConnectionMode_Name(static_cast<ConnectionMode>(enum_t_value));
}
bool ConnectionMode_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, ConnectionMode* value);
enum ConnectionRequestResponse : int {
UNKNOWN_CONNECTION_REQUEST_RESPONSE = 0,
ACCEPTED = 1,
@@ -273,11 +293,12 @@ bool ConnectionAttemptDirection_Parse(
enum ConnectionAttemptType : int {
UNKNOWN_CONNECTION_ATTEMPT_TYPE = 0,
INITIAL = 1,
UPGRADE = 2
UPGRADE = 2,
RECONNECT = 3
};
bool ConnectionAttemptType_IsValid(int value);
constexpr ConnectionAttemptType ConnectionAttemptType_MIN = UNKNOWN_CONNECTION_ATTEMPT_TYPE;
constexpr ConnectionAttemptType ConnectionAttemptType_MAX = UPGRADE;
constexpr ConnectionAttemptType ConnectionAttemptType_MAX = RECONNECT;
constexpr int ConnectionAttemptType_ARRAYSIZE = ConnectionAttemptType_MAX + 1;
const std::string& ConnectionAttemptType_Name(ConnectionAttemptType value);
@@ -297,11 +318,13 @@ enum DisconnectionReason : int {
IO_ERROR = 3,
UPGRADED = 4,
SHUTDOWN = 5,
UNFINISHED = 6
UNFINISHED = 6,
PREV_CHANNEL_DISCONNECTION_IN_RECONNECT = 7,
AUTHENTICATION_FAILURE = 8
};
bool DisconnectionReason_IsValid(int value);
constexpr DisconnectionReason DisconnectionReason_MIN = UNKNOWN_DISCONNECTION_REASON;
constexpr DisconnectionReason DisconnectionReason_MAX = UNFINISHED;
constexpr DisconnectionReason DisconnectionReason_MAX = AUTHENTICATION_FAILURE;
constexpr int DisconnectionReason_ARRAYSIZE = DisconnectionReason_MAX + 1;
const std::string& DisconnectionReason_Name(DisconnectionReason value);
@@ -478,11 +501,15 @@ enum LogSource : int {
INTERNAL_DEVICES = 2,
BETA_TESTER_DEVICES = 3,
OEM_DEVICES = 4,
DEBUG_DEVICES = 5
DEBUG_DEVICES = 5,
NEARBY_MODULE_FOOD_DEVICES = 6,
BETO_DOGFOOD_DEVICES = 7,
NEARBY_DOGFOOD_DEVICES = 8,
NEARBY_TEAMFOOD_DEVICES = 9
};
bool LogSource_IsValid(int value);
constexpr LogSource LogSource_MIN = UNSPECIFIED_SOURCE;
constexpr LogSource LogSource_MAX = DEBUG_DEVICES;
constexpr LogSource LogSource_MAX = NEARBY_TEAMFOOD_DEVICES;
constexpr int LogSource_ARRAYSIZE = LogSource_MAX + 1;
const std::string& LogSource_Name(LogSource value);
@@ -544,7 +571,7 @@ inline const std::string& OperationResultCategory_Name(T enum_t_value) {
}
bool OperationResultCategory_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, OperationResultCategory* value);
enum OperationResultDetail : int {
enum OperationResultCode : int {
DETAIL_UNKNOWN = 0,
DETAIL_SUCCESS = 1,
CLIENT_CANCELLATION_REMOTE_IN_CANCELED_STATE = 500,
@@ -615,6 +642,14 @@ enum OperationResultDetail : int {
MEDIUM_UNAVAILABLE_REJECT_L2CAP_ON_GATT_MULTIPLEX_CONNECTION = 1536,
MEDIUM_UNAVAILABLE_UPGRADE_ON_SAME_MEDIUM = 1537,
MEDIUM_UNAVAILABLE_WEB_RTC_NO_INTERNET = 1538,
MEDIUM_UNAVAILABLE_STA_DISRUPTIVE_FALSE = 1539,
MEDIUM_UNAVAILABLE_STA_USER_NOT_ALLOW = 1540,
MEDIUM_UNAVAILABLE_DUPLICATE_FAST_ADVERTISING = 1541,
MEDIUM_UNAVAILABLE_NSD_NOT_AVAILABLE = 1542,
MEDIUM_UNAVAILABLE_MDNS_NOT_AVAILABLE = 1543,
MEDIUM_UNAVAILABLE_LAN_BLOCKED = 1544,
MEDIUM_UNAVAILABLE_POOR_SIGNAL = 1545,
MEDIUM_UNAVAILABLE_BT_MULTIPLEX_DISABLED = 1546,
CLIENT_WIFI_DIRECT_ALREADY_HOSTING_DIRECT_GROUP_FOR_THIS_CLIENT = 2000,
CLIENT_WIFI_HOTSPOT_ALREADY_HOSTING_HOTSPOT_FOR_THIS_CLIENT = 2001,
CLIENT_DUPLICATE_ACCEPTING_BLE_CONNECTION_REQUEST = 2002,
@@ -632,6 +667,25 @@ enum OperationResultDetail : int {
CLIENT_DUPLICATE_WIFI_HOTSPOT_CONNECTION_REQUEST = 2014,
CLIENT_DUPLICATE_WIFI_AWARE_SUBSCRIBING_REQUEST = 2015,
CLIENT_UNSUPPORTED_USB_TO_BE_UPGRADE_MEDIUM = 2016,
CLIENT_PROCESS_TIE_BREAK_LOSS = 2017,
CLIENT_BLE_DUPLICATE_ADVERTISING = 2018,
CLIENT_BLUETOOTH_DUPLICATE_ADVERTISING = 2019,
CLIENT_NFC_DUPLICATE_ADVERTISING = 2020,
CLIENT_WIFI_LAN_DUPLICATE_ADVERTISING = 2021,
CLIENT_USB_DUPLICATE_ADVERTISING = 2022,
CLIENT_BLE_DUPLICATE_DISCOVERING = 2023,
CLIENT_BLUETOOTH_DUPLICATE_DISCOVERING = 2024,
CLIENT_NFC_DUPLICATE_DISCOVERING = 2025,
CLIENT_WIFI_LAN_DUPLICATE_DISCOVERING = 2026,
CLIENT_USB_DUPLICATE_DISCOVERING = 2027,
CLIENT_PERMISSION_FAILURE = 2028,
CLIENT_BLE_NO_LISTENING = 2029,
CLIENT_ALREADY_CONNECTED_TO_TARGET = 2030,
CLIENT_FAILED_INCOMING_CONNECTION_DUE_TO_TOPOLOGICAL_LIMIT = 2031,
CLIENT_OUT_OF_ORDER_API_CALL = 2032,
CLIENT_WRONG_CONNECTING_PERMISSIONS = 2033,
CLIENT_ALREADY_CONNECTED_TO_ENDPOINT = 2034,
CLIENT_CONNECT_TO_UNKNOWN_ENDPOINT = 2035,
MISCELLEANEOUS_BLUETOOTH_MAC_ADDRESS_NULL = 2500,
MISCELLEANEOUS_MOVE_TO_NEW_MEDIUM = 2501,
MISCELLEANEOUS_WIFI_HOTSPOT_SOFT_AP_BLOCKED_BY_PROVISION = 2502,
@@ -645,21 +699,25 @@ enum OperationResultDetail : int {
MISCELLEANEOUS_BT_NOT_ACCEPTING_CONNECTION_FOR_WORK_PROFILE = 2510,
MISCELLEANEOUS_WEB_RTC_GET_DROIDGUARD_RESULT_FAILURE = 2511,
MISCELLEANEOUS_WEB_RTC_TACHYON_SIGNALING_MESSENGER_NULL = 2512,
MISCELLEANEOUS_WEB_RTC_FAILED_TO_RECEIVE_MESSAGE = 2513,
MISCELLEANEOUS_BLUETOOTH_CHANGE_DEVICE_NAME_FAILURE = 2514,
MISCELLEANEOUS_WEB_RTC_ICE_SERVER_NULL = 2515,
MISCELLEANEOUS_WORK_SOURCE_NULL = 2516,
IO_FILE_OPENING_ERROR = 3000,
IO_FILE_READING_ERROR = 3001,
IO_FILE_WRITING_ERROR = 3002,
IO_FOLDER_CREATION_ERROR = 3003,
IO_STREAM_CREATE_PIPE_FAILURE = 3004,
IO_ENDPOINT_IO_ERROR_ON_BLE = 3005,
IO_ENDPOINT_IO_ERROR_ON_L2CAP = 3006,
IO_ENDPOINT_IO_ERROR_ON_BT = 3007,
IO_ENDPOINT_IO_ERROR_ON_WEB_RTC = 3008,
IO_ENDPOINT_IO_ERROR_ON_LAN = 3009,
IO_ENDPOINT_IO_ERROR_ON_WIFI_DIRECT = 3010,
IO_ENDPOINT_IO_ERROR_ON_WIFI_HOTSPOT = 3011,
IO_ENDPOINT_IO_ERROR_ON_WIFI_AWARE = 3012,
IO_ENDPOINT_IO_ERROR_ON_NFC = 3013,
IO_ENDPOINT_IO_ERROR_ON_USB = 3014,
IO_ENDPOINT_IO_ERROR_ON_BLE PROTOBUF_DEPRECATED_ENUM = 3005,
IO_ENDPOINT_IO_ERROR_ON_BLE_L2CAP PROTOBUF_DEPRECATED_ENUM = 3006,
IO_ENDPOINT_IO_ERROR_ON_BT PROTOBUF_DEPRECATED_ENUM = 3007,
IO_ENDPOINT_IO_ERROR_ON_WEB_RTC PROTOBUF_DEPRECATED_ENUM = 3008,
IO_ENDPOINT_IO_ERROR_ON_LAN PROTOBUF_DEPRECATED_ENUM = 3009,
IO_ENDPOINT_IO_ERROR_ON_WIFI_DIRECT PROTOBUF_DEPRECATED_ENUM = 3010,
IO_ENDPOINT_IO_ERROR_ON_WIFI_HOTSPOT PROTOBUF_DEPRECATED_ENUM = 3011,
IO_ENDPOINT_IO_ERROR_ON_WIFI_AWARE PROTOBUF_DEPRECATED_ENUM = 3012,
IO_ENDPOINT_IO_ERROR_ON_NFC PROTOBUF_DEPRECATED_ENUM = 3013,
IO_ENDPOINT_IO_ERROR_ON_USB PROTOBUF_DEPRECATED_ENUM = 3014,
CONNECTIVITY_WIFI_AWARE_ATTACH_FAILURE = 3500,
CONNECTIVITY_BLUETOOTH_DEVICE_OBTAIN_FAILURE = 3501,
CONNECTIVITY_BLE_CLIENT_SOCKET_CREATION_FAILURE = 3502,
@@ -716,6 +774,52 @@ enum OperationResultDetail : int {
CONNECTIVITY_GENERIC_PAYLOAD_SENT_ERROR = 3553,
CONNECTIVITY_L2CAP_SERVER_SOCKET_CREATION_SECURITY_EXCEPTION_FAILURE = 3554,
CONNECTIVITY_BT_SERVER_SOCKET_CREATION_SECURITY_EXCEPTION_FAILURE = 3555,
CONNECTIVITY_L2CAP_CLIENT_SOCKET_CREATION_TIMEOUT_FAILURE = 3556,
CONNECTIVITY_WEB_RTC_UNSATISFIED_LINK_ERROR = 3557,
CONNECTIVITY_DIRECT_GROUP_MCC_FAILURE = 3558,
CONNECTIVITY_CHANNEL_IO_ERROR_ON_BLE = 3559,
CONNECTIVITY_CHANNEL_IO_ERROR_ON_BLE_L2CAP = 3560,
CONNECTIVITY_CHANNEL_IO_ERROR_ON_BT = 3561,
CONNECTIVITY_CHANNEL_IO_ERROR_ON_WEB_RTC = 3562,
CONNECTIVITY_CHANNEL_IO_ERROR_ON_LAN = 3563,
CONNECTIVITY_CHANNEL_IO_ERROR_ON_WIFI_DIRECT = 3564,
CONNECTIVITY_CHANNEL_IO_ERROR_ON_WIFI_HOTSPOT = 3565,
CONNECTIVITY_CHANNEL_IO_ERROR_ON_WIFI_AWARE = 3566,
CONNECTIVITY_CHANNEL_IO_ERROR_ON_NFC = 3567,
CONNECTIVITY_CHANNEL_IO_ERROR_ON_USB = 3568,
CONNECTIVITY_CHANNEL_IO_ERROR_ON_UNKNOWN_MEDIUM = 3569,
CONNECTIVITY_BT_SOCKET_CREATION_IO_EXCEPTION = 3570,
CONNECTIVITY_BT_SOCKET_CONNECT_IO_EXCEPTION = 3571,
CONNECTIVITY_BT_CONNECTION_INTERRUPTED_EXCEPTION = 3572,
CONNECTIVITY_BT_CONNECTION_EXECUTION_EXCEPTION = 3573,
CONNECTIVITY_BT_CONNECTION_TIMEOUT_EXCEPTION = 3574,
CONNECTIVITY_WIFI_DIRECT_P2P_CONNECTION_FAILURE = 3575,
CONNECTIVITY_WFD_CONNECTION_INTERRUPTED_EXCEPTION = 3576,
CONNECTIVITY_WFD_CONNECTION_EXECUTION_EXCEPTION = 3577,
CONNECTIVITY_WFD_CONNECTION_TIMEOUT_EXCEPTION = 3578,
CONNECTIVITY_WFD_CONNECTION_HOSTED_ADDRESS_NULL = 3579,
CONNECTIVITY_WIFI_HOTSPOT_SPECIFIER_FAILURE = 3580,
CONNECTIVITY_WIFI_HOTSPOT_LEGACY_STA_CONNECTION_FAILURE = 3581,
CONNECTIVITY_WIFI_LAN_SOCKET_CONNECT_TIMEOUT = 3582,
CONNECTIVITY_WIFI_LAN_SOCKET_CONNECT_IO_EXCEPTION = 3583,
CONNECTIVITY_BLE_START_GATT_SERVER_FAILURE = 3584,
CONNECTIVITY_BLE_ADD_GATT_ADVERTISEMENT_FAILURE = 3585,
CONNECTIVITY_BLE_START_ADVERTISING_FAILURE = 3586,
CONNECTIVITY_BLUETOOTH_START_ADVERTISING_FAILURE = 3587,
CONNECTIVITY_WIFI_LAN_START_ADVERTISING_FAILURE = 3588,
CONNECTIVITY_WIFI_AWARE_START_ADVERTISING_FAILURE = 3589,
CONNECTIVITY_BLUETOOTH_SCAN_FAILURE = 3590,
CONNECTIVITY_BLE_SCAN_FAILURE = 3591,
CONNECTIVITY_MDNS_SCAN_FAILURE = 3592,
CONNECTIVITY_NFC_START_DISCOVERY_FAILURE = 3593,
CONNECTIVITY_WIFI_LAN_START_DISCOVERY_FAILURE = 3594,
CONNECTIVITY_WIFI_AWARE_START_DISCOVERY_FAILURE = 3595,
CONNECTIVITY_UWB_START_DISCOVERY_FAILURE = 3596,
CONNECTIVITY_LAN_MDNS_REGISTER_FAILURE = 3597,
CONNECTIVITY_BLUETOOTH_CHANGE_SCAN_MODE_FAILURE = 3598,
CONNECTIVITY_AUTO_RESUME_FAILURE = 3599,
CONNECTIVITY_INSTANT_CONNECTION_LISTENING_TIMEOUT = 3600,
CONNECTIVITY_MEDIUM_INVALID_CREDENTIAL = 3601,
NEARBY_BLE_ADVERTISEMENT_MAPPING_TO_MAC_ERROR = 4500,
NEARBY_BLUETOOTH_MAC_ADDRESS_INVALID_FOR_CONNECT = 4501,
NEARBY_WEB_RTC_CONNECTION_FLOW_NULL = 4502,
@@ -746,7 +850,7 @@ enum OperationResultDetail : int {
NEARBY_WIFI_DIRECT_NULL_CALLBACK = 4527,
NEARBY_WIFI_DIRECT_NULL_SSID = 4528,
NEARBY_WIFI_DIRECT_NULL_PASSWORD = 4529,
NEARBY_BT_MULTIPLEX_SOCKET_DISABLED = 4530,
NEARBY_BT_MULTIPLEX_SOCKET_DISABLED PROTOBUF_DEPRECATED_ENUM = 4530,
NEARBY_LAN_MULTIPLEX_SOCKET_DISABLED = 4531,
NEARBY_GENERIC_NEW_ENDPOINT_CHANNEL_NULL = 4532,
NEARBY_WIFI_DIRECT_NO_GROUP_FOR_LISTENING = 4533,
@@ -782,23 +886,106 @@ enum OperationResultDetail : int {
NEARBY_BT_VIRTUAL_SOCKET_CREATION_FAILURE = 4563,
NEARBY_LAN_VIRTUAL_SOCKET_CREATION_FAILURE = 4564,
NEARBY_WIFI_LAN_IP_ADDRESS_ERROR = 4565,
NEARBY_L2CAP_PSM_NOT_POSITIVE = 4566
NEARBY_L2CAP_PSM_NOT_POSITIVE = 4566,
NEARBY_ENCRYPTION_FAILURE = 4567,
NEARBY_AUTHENTICATION_FAILURE = 4568,
NEARBY_LAN_VIRTUAL_SOCKET_NULL = 4569,
NEARBY_BLUETOOTH_ADVERTISE_TO_BYTES_FAILURE = 4570,
NEARBY_BLE_ADVERTISE_TO_BYTES_FAILURE = 4571,
NEARBY_BLE_FAST_ADVERTISE_TO_BYTES_FAILURE = 4572,
NEARBY_NFC_ADVERTISE_TO_BYTES_FAILURE = 4573,
NEARBY_WIFI_LAN_ADVERTISE_TO_BYTES_FAILURE = 4574,
NEARBY_WIFI_AWARE_ADVERTISE_TO_BYTES_FAILURE = 4575,
NEARBY_USB_ADVERTISE_TO_BYTES_FAILURE = 4576,
NEARBY_NFC_INVALID_PCP_OPTIONS = 4577,
NEARBY_BLUETOOTH_INVALID_PCP_OPTIONS = 4578,
NEARBY_BLE_INVALID_PCP_OPTIONS = 4579,
NEARBY_WIFI_LAN_INVALID_PCP_OPTIONS = 4580,
NEARBY_WIFI_AWARE_INVALID_PCP_OPTIONS = 4581,
NEARBY_USB_INVALID_PCP_OPTIONS = 4582,
NEARBY_UWB_INVALID_PCP_OPTIONS = 4583,
NEARBY_WEB_RTC_INVALID_PCP_OPTIONS = 4584,
NEARBY_BLUETOOTH_NO_CLIENT_REGISTER_FOR_SCAN = 4585,
NEARBY_INSTANT_CONNECTION_WRONG_CONNECTIVITY_INFO = 4586,
NEARBY_NEED_METHOD_OVERRIDE = 4587,
NEARBY_GENERIC_INCOMING_PAYLOAD_CREATION_FAILURE = 4588,
NEARBY_WEB_RTC_NO_LISTENING_PEER_FOUND = 4589,
NEARBY_UPGRADE_PATH_ON_WRONG_MEDIUM = 4590,
NEARBY_CONNECT_TO_ALL_MEDIUMS_FAILURE = 4591,
NEARBY_BLUETOOTH_RECONNECT_MAC_NULL = 4592,
NEARBY_LAN_RECONNECT_CONNECTION_INFO_NULL = 4593,
NEARBY_LAN_RECONNECT_IP_NULL = 4594,
NEARBY_WIFI_DIRECT_RECONNECT_META_DATA_NULL = 4595,
NEARBY_WIFI_DIRECT_RECONNECT_CONNECT_META_DATA_NULL = 4596,
NEARBY_WIFI_HOTSPOT_RECONNECT_META_DATA_NULL = 4597,
NEARBY_WIFI_HOTSPOT_RECONNECT_CONNECT_META_DATA_NULL = 4598,
NEARBY_WEB_RTC_RECONNECT_PEER_ID_NULL = 4599,
NEARBY_WIFI_AWARE_RECONNECT_META_DATA_NULL = 4600,
NEARBY_NOT_ADVERTISING_OR_LISTENING = 4601,
NEARBY_CAN_NOT_OBTAIN_DEVICE_PROVIDER = 4602,
NEARBY_SETUP_STRATEGY_FAILURE = 4603,
NEARBY_TX_ADVERTISEMENT_NULL = 4604,
NEARBY_ENDPOINT_ID_MISMATCH = 4605,
NEARBY_CONNECTIVITY_INFO_NULL_OR_WRONG = 4606,
NEARBY_LOCAL_CLIENT_STATE_WRONG = 4607,
NEARBY_REMOTE_EXCEPTION_WHEN_PROCESSING_RECEIVED_PAYLOAD = 4608,
NEARBY_BAD_FILE_DESCRIPTION_WHEN_PROCESSING_RECEIVED_PAYLOAD = 4609
};
bool OperationResultDetail_IsValid(int value);
constexpr OperationResultDetail OperationResultDetail_MIN = DETAIL_UNKNOWN;
constexpr OperationResultDetail OperationResultDetail_MAX = NEARBY_L2CAP_PSM_NOT_POSITIVE;
constexpr int OperationResultDetail_ARRAYSIZE = OperationResultDetail_MAX + 1;
bool OperationResultCode_IsValid(int value);
constexpr OperationResultCode OperationResultCode_MIN = DETAIL_UNKNOWN;
constexpr OperationResultCode OperationResultCode_MAX = NEARBY_BAD_FILE_DESCRIPTION_WHEN_PROCESSING_RECEIVED_PAYLOAD;
constexpr int OperationResultCode_ARRAYSIZE = OperationResultCode_MAX + 1;
const std::string& OperationResultDetail_Name(OperationResultDetail value);
const std::string& OperationResultCode_Name(OperationResultCode value);
template<typename T>
inline const std::string& OperationResultDetail_Name(T enum_t_value) {
static_assert(::std::is_same<T, OperationResultDetail>::value ||
inline const std::string& OperationResultCode_Name(T enum_t_value) {
static_assert(::std::is_same<T, OperationResultCode>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function OperationResultDetail_Name.");
return OperationResultDetail_Name(static_cast<OperationResultDetail>(enum_t_value));
"Incorrect type passed to function OperationResultCode_Name.");
return OperationResultCode_Name(static_cast<OperationResultCode>(enum_t_value));
}
bool OperationResultDetail_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, OperationResultDetail* value);
bool OperationResultCode_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, OperationResultCode* value);
enum StopAdvertisingReason : int {
STOP_ADVERTISING_REASON_UNKNOWN = 0,
CLIENT_STOP_ADVERTISING = 1,
FINISH_SESSION_STOP_ADVERTISING = 2
};
bool StopAdvertisingReason_IsValid(int value);
constexpr StopAdvertisingReason StopAdvertisingReason_MIN = STOP_ADVERTISING_REASON_UNKNOWN;
constexpr StopAdvertisingReason StopAdvertisingReason_MAX = FINISH_SESSION_STOP_ADVERTISING;
constexpr int StopAdvertisingReason_ARRAYSIZE = StopAdvertisingReason_MAX + 1;
const std::string& StopAdvertisingReason_Name(StopAdvertisingReason value);
template<typename T>
inline const std::string& StopAdvertisingReason_Name(T enum_t_value) {
static_assert(::std::is_same<T, StopAdvertisingReason>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function StopAdvertisingReason_Name.");
return StopAdvertisingReason_Name(static_cast<StopAdvertisingReason>(enum_t_value));
}
bool StopAdvertisingReason_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, StopAdvertisingReason* value);
enum StopDiscoveringReason : int {
STOP_DISCOVERING_REASON_UNKNOWN = 0,
CLIENT_STOP_DISCOVERING = 1,
FINISH_SESSION_STOP_DISCOVERING = 2
};
bool StopDiscoveringReason_IsValid(int value);
constexpr StopDiscoveringReason StopDiscoveringReason_MIN = STOP_DISCOVERING_REASON_UNKNOWN;
constexpr StopDiscoveringReason StopDiscoveringReason_MAX = FINISH_SESSION_STOP_DISCOVERING;
constexpr int StopDiscoveringReason_ARRAYSIZE = StopDiscoveringReason_MAX + 1;
const std::string& StopDiscoveringReason_Name(StopDiscoveringReason value);
template<typename T>
inline const std::string& StopDiscoveringReason_Name(T enum_t_value) {
static_assert(::std::is_same<T, StopDiscoveringReason>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function StopDiscoveringReason_Name.");
return StopDiscoveringReason_Name(static_cast<StopDiscoveringReason>(enum_t_value));
}
bool StopDiscoveringReason_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, StopDiscoveringReason* value);
// ===================================================================
@@ -830,6 +1017,7 @@ template <> struct is_proto_enum< ::location::nearby::proto::connections::Sessio
template <> struct is_proto_enum< ::location::nearby::proto::connections::Medium> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::connections::ConnectionTechnology> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::connections::ConnectionBand> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::connections::ConnectionMode> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::connections::ConnectionRequestResponse> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::connections::ConnectionAttemptResult> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::connections::ConnectionAttemptDirection> : ::std::true_type {};
@@ -843,7 +1031,9 @@ template <> struct is_proto_enum< ::location::nearby::proto::connections::Bandwi
template <> struct is_proto_enum< ::location::nearby::proto::connections::LogSource> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::connections::PowerLevel> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::connections::OperationResultCategory> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::connections::OperationResultDetail> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::connections::OperationResultCode> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::connections::StopAdvertisingReason> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::connections::StopDiscoveringReason> : ::std::true_type {};
PROTOBUF_NAMESPACE_CLOSE
+748
View File
@@ -0,0 +1,748 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: proto/fast_pair_enums.proto
#include "proto/fast_pair_enums.pb.h"
#include <algorithm>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
PROTOBUF_PRAGMA_INIT_SEG
namespace nearby {
namespace proto {
namespace fastpair {
constexpr FastPairEvent::FastPairEvent(
::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized){}
struct FastPairEventDefaultTypeInternal {
constexpr FastPairEventDefaultTypeInternal()
: _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {}
~FastPairEventDefaultTypeInternal() {}
union {
FastPairEvent _instance;
};
};
PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT FastPairEventDefaultTypeInternal _FastPairEvent_default_instance_;
} // namespace fastpair
} // namespace proto
} // namespace nearby
namespace nearby {
namespace proto {
namespace fastpair {
bool FastPairEvent_BondState_IsValid(int value) {
switch (value) {
case 0:
case 10:
case 11:
case 12:
return true;
default:
return false;
}
}
static ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<std::string> FastPairEvent_BondState_strings[4] = {};
static const char FastPairEvent_BondState_names[] =
"BONDED"
"BONDING"
"NONE"
"UNKNOWN_BOND_STATE";
static const ::PROTOBUF_NAMESPACE_ID::internal::EnumEntry FastPairEvent_BondState_entries[] = {
{ {FastPairEvent_BondState_names + 0, 6}, 12 },
{ {FastPairEvent_BondState_names + 6, 7}, 11 },
{ {FastPairEvent_BondState_names + 13, 4}, 10 },
{ {FastPairEvent_BondState_names + 17, 18}, 0 },
};
static const int FastPairEvent_BondState_entries_by_number[] = {
3, // 0 -> UNKNOWN_BOND_STATE
2, // 10 -> NONE
1, // 11 -> BONDING
0, // 12 -> BONDED
};
const std::string& FastPairEvent_BondState_Name(
FastPairEvent_BondState value) {
static const bool dummy =
::PROTOBUF_NAMESPACE_ID::internal::InitializeEnumStrings(
FastPairEvent_BondState_entries,
FastPairEvent_BondState_entries_by_number,
4, FastPairEvent_BondState_strings);
(void) dummy;
int idx = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumName(
FastPairEvent_BondState_entries,
FastPairEvent_BondState_entries_by_number,
4, value);
return idx == -1 ? ::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString() :
FastPairEvent_BondState_strings[idx].get();
}
bool FastPairEvent_BondState_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, FastPairEvent_BondState* value) {
int int_value;
bool success = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumValue(
FastPairEvent_BondState_entries, 4, name, &int_value);
if (success) {
*value = static_cast<FastPairEvent_BondState>(int_value);
}
return success;
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || (_MSC_VER >= 1900 && _MSC_VER < 1912))
constexpr FastPairEvent_BondState FastPairEvent::UNKNOWN_BOND_STATE;
constexpr FastPairEvent_BondState FastPairEvent::NONE;
constexpr FastPairEvent_BondState FastPairEvent::BONDING;
constexpr FastPairEvent_BondState FastPairEvent::BONDED;
constexpr FastPairEvent_BondState FastPairEvent::BondState_MIN;
constexpr FastPairEvent_BondState FastPairEvent::BondState_MAX;
constexpr int FastPairEvent::BondState_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || (_MSC_VER >= 1900 && _MSC_VER < 1912))
bool FastPairEvent_ErrorCode_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
return true;
default:
return false;
}
}
static ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<std::string> FastPairEvent_ErrorCode_strings[17] = {};
static const char FastPairEvent_ErrorCode_names[] =
"DEVICE_NOT_BONDED_DURING_RETROACTIVE_PAIR"
"DEVICE_NOT_IN_PAIRED_HISTORY_EXCEPTION"
"EXECUTION_EXCEPTION"
"INTERRUPTED"
"MDH_REMOTE_EXCEPTION"
"OTHER_ERROR"
"PARSE_EXCEPTION"
"REFLECTIVE_OPERATION_EXCEPTION"
"SUCCESS_ADDRESS_ROTATE"
"SUCCESS_RETRY_GATT_ERROR"
"SUCCESS_RETRY_GATT_TIMEOUT"
"SUCCESS_RETRY_SECRET_HANDSHAKE_ERROR"
"SUCCESS_RETRY_SECRET_HANDSHAKE_TIMEOUT"
"SUCCESS_SECRET_HANDSHAKE_RECONNECT"
"SUCCESS_SIGNAL_LOST"
"TIMEOUT"
"UNKNOWN_ERROR_CODE";
static const ::PROTOBUF_NAMESPACE_ID::internal::EnumEntry FastPairEvent_ErrorCode_entries[] = {
{ {FastPairEvent_ErrorCode_names + 0, 41}, 16 },
{ {FastPairEvent_ErrorCode_names + 41, 38}, 15 },
{ {FastPairEvent_ErrorCode_names + 79, 19}, 5 },
{ {FastPairEvent_ErrorCode_names + 98, 11}, 3 },
{ {FastPairEvent_ErrorCode_names + 109, 20}, 7 },
{ {FastPairEvent_ErrorCode_names + 129, 11}, 1 },
{ {FastPairEvent_ErrorCode_names + 140, 15}, 6 },
{ {FastPairEvent_ErrorCode_names + 155, 30}, 4 },
{ {FastPairEvent_ErrorCode_names + 185, 22}, 13 },
{ {FastPairEvent_ErrorCode_names + 207, 24}, 8 },
{ {FastPairEvent_ErrorCode_names + 231, 26}, 9 },
{ {FastPairEvent_ErrorCode_names + 257, 36}, 10 },
{ {FastPairEvent_ErrorCode_names + 293, 38}, 11 },
{ {FastPairEvent_ErrorCode_names + 331, 34}, 12 },
{ {FastPairEvent_ErrorCode_names + 365, 19}, 14 },
{ {FastPairEvent_ErrorCode_names + 384, 7}, 2 },
{ {FastPairEvent_ErrorCode_names + 391, 18}, 0 },
};
static const int FastPairEvent_ErrorCode_entries_by_number[] = {
16, // 0 -> UNKNOWN_ERROR_CODE
5, // 1 -> OTHER_ERROR
15, // 2 -> TIMEOUT
3, // 3 -> INTERRUPTED
7, // 4 -> REFLECTIVE_OPERATION_EXCEPTION
2, // 5 -> EXECUTION_EXCEPTION
6, // 6 -> PARSE_EXCEPTION
4, // 7 -> MDH_REMOTE_EXCEPTION
9, // 8 -> SUCCESS_RETRY_GATT_ERROR
10, // 9 -> SUCCESS_RETRY_GATT_TIMEOUT
11, // 10 -> SUCCESS_RETRY_SECRET_HANDSHAKE_ERROR
12, // 11 -> SUCCESS_RETRY_SECRET_HANDSHAKE_TIMEOUT
13, // 12 -> SUCCESS_SECRET_HANDSHAKE_RECONNECT
8, // 13 -> SUCCESS_ADDRESS_ROTATE
14, // 14 -> SUCCESS_SIGNAL_LOST
1, // 15 -> DEVICE_NOT_IN_PAIRED_HISTORY_EXCEPTION
0, // 16 -> DEVICE_NOT_BONDED_DURING_RETROACTIVE_PAIR
};
const std::string& FastPairEvent_ErrorCode_Name(
FastPairEvent_ErrorCode value) {
static const bool dummy =
::PROTOBUF_NAMESPACE_ID::internal::InitializeEnumStrings(
FastPairEvent_ErrorCode_entries,
FastPairEvent_ErrorCode_entries_by_number,
17, FastPairEvent_ErrorCode_strings);
(void) dummy;
int idx = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumName(
FastPairEvent_ErrorCode_entries,
FastPairEvent_ErrorCode_entries_by_number,
17, value);
return idx == -1 ? ::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString() :
FastPairEvent_ErrorCode_strings[idx].get();
}
bool FastPairEvent_ErrorCode_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, FastPairEvent_ErrorCode* value) {
int int_value;
bool success = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumValue(
FastPairEvent_ErrorCode_entries, 17, name, &int_value);
if (success) {
*value = static_cast<FastPairEvent_ErrorCode>(int_value);
}
return success;
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || (_MSC_VER >= 1900 && _MSC_VER < 1912))
constexpr FastPairEvent_ErrorCode FastPairEvent::UNKNOWN_ERROR_CODE;
constexpr FastPairEvent_ErrorCode FastPairEvent::OTHER_ERROR;
constexpr FastPairEvent_ErrorCode FastPairEvent::TIMEOUT;
constexpr FastPairEvent_ErrorCode FastPairEvent::INTERRUPTED;
constexpr FastPairEvent_ErrorCode FastPairEvent::REFLECTIVE_OPERATION_EXCEPTION;
constexpr FastPairEvent_ErrorCode FastPairEvent::EXECUTION_EXCEPTION;
constexpr FastPairEvent_ErrorCode FastPairEvent::PARSE_EXCEPTION;
constexpr FastPairEvent_ErrorCode FastPairEvent::MDH_REMOTE_EXCEPTION;
constexpr FastPairEvent_ErrorCode FastPairEvent::SUCCESS_RETRY_GATT_ERROR;
constexpr FastPairEvent_ErrorCode FastPairEvent::SUCCESS_RETRY_GATT_TIMEOUT;
constexpr FastPairEvent_ErrorCode FastPairEvent::SUCCESS_RETRY_SECRET_HANDSHAKE_ERROR;
constexpr FastPairEvent_ErrorCode FastPairEvent::SUCCESS_RETRY_SECRET_HANDSHAKE_TIMEOUT;
constexpr FastPairEvent_ErrorCode FastPairEvent::SUCCESS_SECRET_HANDSHAKE_RECONNECT;
constexpr FastPairEvent_ErrorCode FastPairEvent::SUCCESS_ADDRESS_ROTATE;
constexpr FastPairEvent_ErrorCode FastPairEvent::SUCCESS_SIGNAL_LOST;
constexpr FastPairEvent_ErrorCode FastPairEvent::DEVICE_NOT_IN_PAIRED_HISTORY_EXCEPTION;
constexpr FastPairEvent_ErrorCode FastPairEvent::DEVICE_NOT_BONDED_DURING_RETROACTIVE_PAIR;
constexpr FastPairEvent_ErrorCode FastPairEvent::ErrorCode_MIN;
constexpr FastPairEvent_ErrorCode FastPairEvent::ErrorCode_MAX;
constexpr int FastPairEvent::ErrorCode_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || (_MSC_VER >= 1900 && _MSC_VER < 1912))
bool FastPairEvent_BrEdrHandoverErrorCode_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
return true;
default:
return false;
}
}
static ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<std::string> FastPairEvent_BrEdrHandoverErrorCode_strings[4] = {};
static const char FastPairEvent_BrEdrHandoverErrorCode_names[] =
"BLUETOOTH_MAC_INVALID"
"CONTROL_POINT_RESULT_CODE_NOT_SUCCESS"
"TRANSPORT_BLOCK_INVALID"
"UNKNOWN_BR_EDR_HANDOVER_ERROR_CODE";
static const ::PROTOBUF_NAMESPACE_ID::internal::EnumEntry FastPairEvent_BrEdrHandoverErrorCode_entries[] = {
{ {FastPairEvent_BrEdrHandoverErrorCode_names + 0, 21}, 2 },
{ {FastPairEvent_BrEdrHandoverErrorCode_names + 21, 37}, 1 },
{ {FastPairEvent_BrEdrHandoverErrorCode_names + 58, 23}, 3 },
{ {FastPairEvent_BrEdrHandoverErrorCode_names + 81, 34}, 0 },
};
static const int FastPairEvent_BrEdrHandoverErrorCode_entries_by_number[] = {
3, // 0 -> UNKNOWN_BR_EDR_HANDOVER_ERROR_CODE
1, // 1 -> CONTROL_POINT_RESULT_CODE_NOT_SUCCESS
0, // 2 -> BLUETOOTH_MAC_INVALID
2, // 3 -> TRANSPORT_BLOCK_INVALID
};
const std::string& FastPairEvent_BrEdrHandoverErrorCode_Name(
FastPairEvent_BrEdrHandoverErrorCode value) {
static const bool dummy =
::PROTOBUF_NAMESPACE_ID::internal::InitializeEnumStrings(
FastPairEvent_BrEdrHandoverErrorCode_entries,
FastPairEvent_BrEdrHandoverErrorCode_entries_by_number,
4, FastPairEvent_BrEdrHandoverErrorCode_strings);
(void) dummy;
int idx = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumName(
FastPairEvent_BrEdrHandoverErrorCode_entries,
FastPairEvent_BrEdrHandoverErrorCode_entries_by_number,
4, value);
return idx == -1 ? ::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString() :
FastPairEvent_BrEdrHandoverErrorCode_strings[idx].get();
}
bool FastPairEvent_BrEdrHandoverErrorCode_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, FastPairEvent_BrEdrHandoverErrorCode* value) {
int int_value;
bool success = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumValue(
FastPairEvent_BrEdrHandoverErrorCode_entries, 4, name, &int_value);
if (success) {
*value = static_cast<FastPairEvent_BrEdrHandoverErrorCode>(int_value);
}
return success;
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || (_MSC_VER >= 1900 && _MSC_VER < 1912))
constexpr FastPairEvent_BrEdrHandoverErrorCode FastPairEvent::UNKNOWN_BR_EDR_HANDOVER_ERROR_CODE;
constexpr FastPairEvent_BrEdrHandoverErrorCode FastPairEvent::CONTROL_POINT_RESULT_CODE_NOT_SUCCESS;
constexpr FastPairEvent_BrEdrHandoverErrorCode FastPairEvent::BLUETOOTH_MAC_INVALID;
constexpr FastPairEvent_BrEdrHandoverErrorCode FastPairEvent::TRANSPORT_BLOCK_INVALID;
constexpr FastPairEvent_BrEdrHandoverErrorCode FastPairEvent::BrEdrHandoverErrorCode_MIN;
constexpr FastPairEvent_BrEdrHandoverErrorCode FastPairEvent::BrEdrHandoverErrorCode_MAX;
constexpr int FastPairEvent::BrEdrHandoverErrorCode_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || (_MSC_VER >= 1900 && _MSC_VER < 1912))
bool FastPairEvent_CreateBondErrorCode_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
return true;
default:
return false;
}
}
static ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<std::string> FastPairEvent_CreateBondErrorCode_strings[6] = {};
static const char FastPairEvent_CreateBondErrorCode_names[] =
"BOND_BROKEN"
"FAILED_BUT_ALREADY_RECEIVE_PASS_KEY"
"INCORRECT_VARIANT"
"NO_PERMISSION"
"POSSIBLE_MITM"
"UNKNOWN_BOND_ERROR_CODE";
static const ::PROTOBUF_NAMESPACE_ID::internal::EnumEntry FastPairEvent_CreateBondErrorCode_entries[] = {
{ {FastPairEvent_CreateBondErrorCode_names + 0, 11}, 1 },
{ {FastPairEvent_CreateBondErrorCode_names + 11, 35}, 5 },
{ {FastPairEvent_CreateBondErrorCode_names + 46, 17}, 4 },
{ {FastPairEvent_CreateBondErrorCode_names + 63, 13}, 3 },
{ {FastPairEvent_CreateBondErrorCode_names + 76, 13}, 2 },
{ {FastPairEvent_CreateBondErrorCode_names + 89, 23}, 0 },
};
static const int FastPairEvent_CreateBondErrorCode_entries_by_number[] = {
5, // 0 -> UNKNOWN_BOND_ERROR_CODE
0, // 1 -> BOND_BROKEN
4, // 2 -> POSSIBLE_MITM
3, // 3 -> NO_PERMISSION
2, // 4 -> INCORRECT_VARIANT
1, // 5 -> FAILED_BUT_ALREADY_RECEIVE_PASS_KEY
};
const std::string& FastPairEvent_CreateBondErrorCode_Name(
FastPairEvent_CreateBondErrorCode value) {
static const bool dummy =
::PROTOBUF_NAMESPACE_ID::internal::InitializeEnumStrings(
FastPairEvent_CreateBondErrorCode_entries,
FastPairEvent_CreateBondErrorCode_entries_by_number,
6, FastPairEvent_CreateBondErrorCode_strings);
(void) dummy;
int idx = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumName(
FastPairEvent_CreateBondErrorCode_entries,
FastPairEvent_CreateBondErrorCode_entries_by_number,
6, value);
return idx == -1 ? ::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString() :
FastPairEvent_CreateBondErrorCode_strings[idx].get();
}
bool FastPairEvent_CreateBondErrorCode_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, FastPairEvent_CreateBondErrorCode* value) {
int int_value;
bool success = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumValue(
FastPairEvent_CreateBondErrorCode_entries, 6, name, &int_value);
if (success) {
*value = static_cast<FastPairEvent_CreateBondErrorCode>(int_value);
}
return success;
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || (_MSC_VER >= 1900 && _MSC_VER < 1912))
constexpr FastPairEvent_CreateBondErrorCode FastPairEvent::UNKNOWN_BOND_ERROR_CODE;
constexpr FastPairEvent_CreateBondErrorCode FastPairEvent::BOND_BROKEN;
constexpr FastPairEvent_CreateBondErrorCode FastPairEvent::POSSIBLE_MITM;
constexpr FastPairEvent_CreateBondErrorCode FastPairEvent::NO_PERMISSION;
constexpr FastPairEvent_CreateBondErrorCode FastPairEvent::INCORRECT_VARIANT;
constexpr FastPairEvent_CreateBondErrorCode FastPairEvent::FAILED_BUT_ALREADY_RECEIVE_PASS_KEY;
constexpr FastPairEvent_CreateBondErrorCode FastPairEvent::CreateBondErrorCode_MIN;
constexpr FastPairEvent_CreateBondErrorCode FastPairEvent::CreateBondErrorCode_MAX;
constexpr int FastPairEvent::CreateBondErrorCode_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || (_MSC_VER >= 1900 && _MSC_VER < 1912))
bool FastPairEvent_ConnectErrorCode_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
return true;
default:
return false;
}
}
static ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<std::string> FastPairEvent_ConnectErrorCode_strings[7] = {};
static const char FastPairEvent_ConnectErrorCode_names[] =
"DISCONNECTED"
"DISCOVERY_NOT_FINISHED"
"FAIL_TO_DISCOVERY"
"GET_PROFILE_PROXY_FAILED"
"LINK_KEY_CLEARED"
"UNKNOWN_CONNECT_ERROR_CODE"
"UNSUPPORTED_PROFILE";
static const ::PROTOBUF_NAMESPACE_ID::internal::EnumEntry FastPairEvent_ConnectErrorCode_entries[] = {
{ {FastPairEvent_ConnectErrorCode_names + 0, 12}, 3 },
{ {FastPairEvent_ConnectErrorCode_names + 12, 22}, 6 },
{ {FastPairEvent_ConnectErrorCode_names + 34, 17}, 5 },
{ {FastPairEvent_ConnectErrorCode_names + 51, 24}, 2 },
{ {FastPairEvent_ConnectErrorCode_names + 75, 16}, 4 },
{ {FastPairEvent_ConnectErrorCode_names + 91, 26}, 0 },
{ {FastPairEvent_ConnectErrorCode_names + 117, 19}, 1 },
};
static const int FastPairEvent_ConnectErrorCode_entries_by_number[] = {
5, // 0 -> UNKNOWN_CONNECT_ERROR_CODE
6, // 1 -> UNSUPPORTED_PROFILE
3, // 2 -> GET_PROFILE_PROXY_FAILED
0, // 3 -> DISCONNECTED
4, // 4 -> LINK_KEY_CLEARED
2, // 5 -> FAIL_TO_DISCOVERY
1, // 6 -> DISCOVERY_NOT_FINISHED
};
const std::string& FastPairEvent_ConnectErrorCode_Name(
FastPairEvent_ConnectErrorCode value) {
static const bool dummy =
::PROTOBUF_NAMESPACE_ID::internal::InitializeEnumStrings(
FastPairEvent_ConnectErrorCode_entries,
FastPairEvent_ConnectErrorCode_entries_by_number,
7, FastPairEvent_ConnectErrorCode_strings);
(void) dummy;
int idx = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumName(
FastPairEvent_ConnectErrorCode_entries,
FastPairEvent_ConnectErrorCode_entries_by_number,
7, value);
return idx == -1 ? ::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString() :
FastPairEvent_ConnectErrorCode_strings[idx].get();
}
bool FastPairEvent_ConnectErrorCode_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, FastPairEvent_ConnectErrorCode* value) {
int int_value;
bool success = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumValue(
FastPairEvent_ConnectErrorCode_entries, 7, name, &int_value);
if (success) {
*value = static_cast<FastPairEvent_ConnectErrorCode>(int_value);
}
return success;
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || (_MSC_VER >= 1900 && _MSC_VER < 1912))
constexpr FastPairEvent_ConnectErrorCode FastPairEvent::UNKNOWN_CONNECT_ERROR_CODE;
constexpr FastPairEvent_ConnectErrorCode FastPairEvent::UNSUPPORTED_PROFILE;
constexpr FastPairEvent_ConnectErrorCode FastPairEvent::GET_PROFILE_PROXY_FAILED;
constexpr FastPairEvent_ConnectErrorCode FastPairEvent::DISCONNECTED;
constexpr FastPairEvent_ConnectErrorCode FastPairEvent::LINK_KEY_CLEARED;
constexpr FastPairEvent_ConnectErrorCode FastPairEvent::FAIL_TO_DISCOVERY;
constexpr FastPairEvent_ConnectErrorCode FastPairEvent::DISCOVERY_NOT_FINISHED;
constexpr FastPairEvent_ConnectErrorCode FastPairEvent::ConnectErrorCode_MIN;
constexpr FastPairEvent_ConnectErrorCode FastPairEvent::ConnectErrorCode_MAX;
constexpr int FastPairEvent::ConnectErrorCode_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || (_MSC_VER >= 1900 && _MSC_VER < 1912))
bool DeviceType_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
return true;
default:
return false;
}
}
static ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<std::string> DeviceType_strings[7] = {};
static const char DeviceType_names[] =
"AUTO"
"PC"
"PHONE"
"TABLET"
"TV"
"UNKNOWN_DEVICE_TYPE"
"WEARABLE";
static const ::PROTOBUF_NAMESPACE_ID::internal::EnumEntry DeviceType_entries[] = {
{ {DeviceType_names + 0, 4}, 3 },
{ {DeviceType_names + 4, 2}, 4 },
{ {DeviceType_names + 6, 5}, 1 },
{ {DeviceType_names + 11, 6}, 6 },
{ {DeviceType_names + 17, 2}, 5 },
{ {DeviceType_names + 19, 19}, 0 },
{ {DeviceType_names + 38, 8}, 2 },
};
static const int DeviceType_entries_by_number[] = {
5, // 0 -> UNKNOWN_DEVICE_TYPE
2, // 1 -> PHONE
6, // 2 -> WEARABLE
0, // 3 -> AUTO
1, // 4 -> PC
4, // 5 -> TV
3, // 6 -> TABLET
};
const std::string& DeviceType_Name(
DeviceType value) {
static const bool dummy =
::PROTOBUF_NAMESPACE_ID::internal::InitializeEnumStrings(
DeviceType_entries,
DeviceType_entries_by_number,
7, DeviceType_strings);
(void) dummy;
int idx = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumName(
DeviceType_entries,
DeviceType_entries_by_number,
7, value);
return idx == -1 ? ::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString() :
DeviceType_strings[idx].get();
}
bool DeviceType_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, DeviceType* value) {
int int_value;
bool success = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumValue(
DeviceType_entries, 7, name, &int_value);
if (success) {
*value = static_cast<DeviceType>(int_value);
}
return success;
}
bool OsType_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
return true;
default:
return false;
}
}
static ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<std::string> OsType_strings[3] = {};
static const char OsType_names[] =
"ANDROID"
"CHROME_OS"
"UNKNOWN_OS_TYPE";
static const ::PROTOBUF_NAMESPACE_ID::internal::EnumEntry OsType_entries[] = {
{ {OsType_names + 0, 7}, 1 },
{ {OsType_names + 7, 9}, 2 },
{ {OsType_names + 16, 15}, 0 },
};
static const int OsType_entries_by_number[] = {
2, // 0 -> UNKNOWN_OS_TYPE
0, // 1 -> ANDROID
1, // 2 -> CHROME_OS
};
const std::string& OsType_Name(
OsType value) {
static const bool dummy =
::PROTOBUF_NAMESPACE_ID::internal::InitializeEnumStrings(
OsType_entries,
OsType_entries_by_number,
3, OsType_strings);
(void) dummy;
int idx = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumName(
OsType_entries,
OsType_entries_by_number,
3, value);
return idx == -1 ? ::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString() :
OsType_strings[idx].get();
}
bool OsType_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, OsType* value) {
int int_value;
bool success = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumValue(
OsType_entries, 3, name, &int_value);
if (success) {
*value = static_cast<OsType>(int_value);
}
return success;
}
// ===================================================================
class FastPairEvent::_Internal {
public:
};
FastPairEvent::FastPairEvent(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned)
: ::PROTOBUF_NAMESPACE_ID::MessageLite(arena, is_message_owned) {
SharedCtor();
if (!is_message_owned) {
RegisterArenaDtor(arena);
}
// @@protoc_insertion_point(arena_constructor:nearby.proto.fastpair.FastPairEvent)
}
FastPairEvent::FastPairEvent(const FastPairEvent& from)
: ::PROTOBUF_NAMESPACE_ID::MessageLite() {
_internal_metadata_.MergeFrom<std::string>(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:nearby.proto.fastpair.FastPairEvent)
}
inline void FastPairEvent::SharedCtor() {
}
FastPairEvent::~FastPairEvent() {
// @@protoc_insertion_point(destructor:nearby.proto.fastpair.FastPairEvent)
if (GetArenaForAllocation() != nullptr) return;
SharedDtor();
_internal_metadata_.Delete<std::string>();
}
inline void FastPairEvent::SharedDtor() {
GOOGLE_DCHECK(GetArenaForAllocation() == nullptr);
}
void FastPairEvent::ArenaDtor(void* object) {
FastPairEvent* _this = reinterpret_cast< FastPairEvent* >(object);
(void)_this;
}
void FastPairEvent::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void FastPairEvent::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
void FastPairEvent::Clear() {
// @@protoc_insertion_point(message_clear_start:nearby.proto.fastpair.FastPairEvent)
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
_internal_metadata_.Clear<std::string>();
}
const char* FastPairEvent::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
uint32_t tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
if ((tag == 0) || ((tag & 7) == 4)) {
CHK_(ptr);
ctx->SetLastTag(tag);
goto message_done;
}
ptr = UnknownFieldParse(
tag,
_internal_metadata_.mutable_unknown_fields<std::string>(),
ptr, ctx);
CHK_(ptr != nullptr);
} // while
message_done:
return ptr;
failure:
ptr = nullptr;
goto message_done;
#undef CHK_
}
uint8_t* FastPairEvent::_InternalSerialize(
uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:nearby.proto.fastpair.FastPairEvent)
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = stream->WriteRaw(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).data(),
static_cast<int>(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:nearby.proto.fastpair.FastPairEvent)
return target;
}
size_t FastPairEvent::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:nearby.proto.fastpair.FastPairEvent)
size_t total_size = 0;
uint32_t cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
total_size += _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size();
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void FastPairEvent::CheckTypeAndMergeFrom(
const ::PROTOBUF_NAMESPACE_ID::MessageLite& from) {
MergeFrom(*::PROTOBUF_NAMESPACE_ID::internal::DownCast<const FastPairEvent*>(
&from));
}
void FastPairEvent::MergeFrom(const FastPairEvent& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:nearby.proto.fastpair.FastPairEvent)
GOOGLE_DCHECK_NE(&from, this);
uint32_t cached_has_bits = 0;
(void) cached_has_bits;
_internal_metadata_.MergeFrom<std::string>(from._internal_metadata_);
}
void FastPairEvent::CopyFrom(const FastPairEvent& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:nearby.proto.fastpair.FastPairEvent)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool FastPairEvent::IsInitialized() const {
return true;
}
void FastPairEvent::InternalSwap(FastPairEvent* other) {
using std::swap;
_internal_metadata_.InternalSwap(&other->_internal_metadata_);
}
std::string FastPairEvent::GetTypeName() const {
return "nearby.proto.fastpair.FastPairEvent";
}
// @@protoc_insertion_point(namespace_scope)
} // namespace fastpair
} // namespace proto
} // namespace nearby
PROTOBUF_NAMESPACE_OPEN
template<> PROTOBUF_NOINLINE ::nearby::proto::fastpair::FastPairEvent* Arena::CreateMaybeMessage< ::nearby::proto::fastpair::FastPairEvent >(Arena* arena) {
return Arena::CreateMessageInternal< ::nearby::proto::fastpair::FastPairEvent >(arena);
}
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
+583
View File
@@ -0,0 +1,583 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: proto/fast_pair_enums.proto
#ifndef GOOGLE_PROTOBUF_INCLUDED_proto_2ffast_5fpair_5fenums_2eproto
#define GOOGLE_PROTOBUF_INCLUDED_proto_2ffast_5fpair_5fenums_2eproto
#include <limits>
#include <string>
#include <google/protobuf/port_def.inc>
#if PROTOBUF_VERSION < 3019000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3019001 < PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/generated_enum_util.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
#define PROTOBUF_INTERNAL_EXPORT_proto_2ffast_5fpair_5fenums_2eproto
PROTOBUF_NAMESPACE_OPEN
namespace internal {
class AnyMetadata;
} // namespace internal
PROTOBUF_NAMESPACE_CLOSE
// Internal implementation detail -- do not use these members.
struct TableStruct_proto_2ffast_5fpair_5fenums_2eproto {
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[];
static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[];
static const uint32_t offsets[];
};
namespace nearby {
namespace proto {
namespace fastpair {
class FastPairEvent;
struct FastPairEventDefaultTypeInternal;
extern FastPairEventDefaultTypeInternal _FastPairEvent_default_instance_;
} // namespace fastpair
} // namespace proto
} // namespace nearby
PROTOBUF_NAMESPACE_OPEN
template<> ::nearby::proto::fastpair::FastPairEvent* Arena::CreateMaybeMessage<::nearby::proto::fastpair::FastPairEvent>(Arena*);
PROTOBUF_NAMESPACE_CLOSE
namespace nearby {
namespace proto {
namespace fastpair {
enum FastPairEvent_BondState : int {
FastPairEvent_BondState_UNKNOWN_BOND_STATE = 0,
FastPairEvent_BondState_NONE = 10,
FastPairEvent_BondState_BONDING = 11,
FastPairEvent_BondState_BONDED = 12
};
bool FastPairEvent_BondState_IsValid(int value);
constexpr FastPairEvent_BondState FastPairEvent_BondState_BondState_MIN = FastPairEvent_BondState_UNKNOWN_BOND_STATE;
constexpr FastPairEvent_BondState FastPairEvent_BondState_BondState_MAX = FastPairEvent_BondState_BONDED;
constexpr int FastPairEvent_BondState_BondState_ARRAYSIZE = FastPairEvent_BondState_BondState_MAX + 1;
const std::string& FastPairEvent_BondState_Name(FastPairEvent_BondState value);
template<typename T>
inline const std::string& FastPairEvent_BondState_Name(T enum_t_value) {
static_assert(::std::is_same<T, FastPairEvent_BondState>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function FastPairEvent_BondState_Name.");
return FastPairEvent_BondState_Name(static_cast<FastPairEvent_BondState>(enum_t_value));
}
bool FastPairEvent_BondState_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, FastPairEvent_BondState* value);
enum FastPairEvent_ErrorCode : int {
FastPairEvent_ErrorCode_UNKNOWN_ERROR_CODE = 0,
FastPairEvent_ErrorCode_OTHER_ERROR = 1,
FastPairEvent_ErrorCode_TIMEOUT = 2,
FastPairEvent_ErrorCode_INTERRUPTED = 3,
FastPairEvent_ErrorCode_REFLECTIVE_OPERATION_EXCEPTION = 4,
FastPairEvent_ErrorCode_EXECUTION_EXCEPTION = 5,
FastPairEvent_ErrorCode_PARSE_EXCEPTION = 6,
FastPairEvent_ErrorCode_MDH_REMOTE_EXCEPTION = 7,
FastPairEvent_ErrorCode_SUCCESS_RETRY_GATT_ERROR = 8,
FastPairEvent_ErrorCode_SUCCESS_RETRY_GATT_TIMEOUT = 9,
FastPairEvent_ErrorCode_SUCCESS_RETRY_SECRET_HANDSHAKE_ERROR = 10,
FastPairEvent_ErrorCode_SUCCESS_RETRY_SECRET_HANDSHAKE_TIMEOUT = 11,
FastPairEvent_ErrorCode_SUCCESS_SECRET_HANDSHAKE_RECONNECT = 12,
FastPairEvent_ErrorCode_SUCCESS_ADDRESS_ROTATE = 13,
FastPairEvent_ErrorCode_SUCCESS_SIGNAL_LOST = 14,
FastPairEvent_ErrorCode_DEVICE_NOT_IN_PAIRED_HISTORY_EXCEPTION = 15,
FastPairEvent_ErrorCode_DEVICE_NOT_BONDED_DURING_RETROACTIVE_PAIR = 16
};
bool FastPairEvent_ErrorCode_IsValid(int value);
constexpr FastPairEvent_ErrorCode FastPairEvent_ErrorCode_ErrorCode_MIN = FastPairEvent_ErrorCode_UNKNOWN_ERROR_CODE;
constexpr FastPairEvent_ErrorCode FastPairEvent_ErrorCode_ErrorCode_MAX = FastPairEvent_ErrorCode_DEVICE_NOT_BONDED_DURING_RETROACTIVE_PAIR;
constexpr int FastPairEvent_ErrorCode_ErrorCode_ARRAYSIZE = FastPairEvent_ErrorCode_ErrorCode_MAX + 1;
const std::string& FastPairEvent_ErrorCode_Name(FastPairEvent_ErrorCode value);
template<typename T>
inline const std::string& FastPairEvent_ErrorCode_Name(T enum_t_value) {
static_assert(::std::is_same<T, FastPairEvent_ErrorCode>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function FastPairEvent_ErrorCode_Name.");
return FastPairEvent_ErrorCode_Name(static_cast<FastPairEvent_ErrorCode>(enum_t_value));
}
bool FastPairEvent_ErrorCode_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, FastPairEvent_ErrorCode* value);
enum FastPairEvent_BrEdrHandoverErrorCode : int {
FastPairEvent_BrEdrHandoverErrorCode_UNKNOWN_BR_EDR_HANDOVER_ERROR_CODE = 0,
FastPairEvent_BrEdrHandoverErrorCode_CONTROL_POINT_RESULT_CODE_NOT_SUCCESS = 1,
FastPairEvent_BrEdrHandoverErrorCode_BLUETOOTH_MAC_INVALID = 2,
FastPairEvent_BrEdrHandoverErrorCode_TRANSPORT_BLOCK_INVALID = 3
};
bool FastPairEvent_BrEdrHandoverErrorCode_IsValid(int value);
constexpr FastPairEvent_BrEdrHandoverErrorCode FastPairEvent_BrEdrHandoverErrorCode_BrEdrHandoverErrorCode_MIN = FastPairEvent_BrEdrHandoverErrorCode_UNKNOWN_BR_EDR_HANDOVER_ERROR_CODE;
constexpr FastPairEvent_BrEdrHandoverErrorCode FastPairEvent_BrEdrHandoverErrorCode_BrEdrHandoverErrorCode_MAX = FastPairEvent_BrEdrHandoverErrorCode_TRANSPORT_BLOCK_INVALID;
constexpr int FastPairEvent_BrEdrHandoverErrorCode_BrEdrHandoverErrorCode_ARRAYSIZE = FastPairEvent_BrEdrHandoverErrorCode_BrEdrHandoverErrorCode_MAX + 1;
const std::string& FastPairEvent_BrEdrHandoverErrorCode_Name(FastPairEvent_BrEdrHandoverErrorCode value);
template<typename T>
inline const std::string& FastPairEvent_BrEdrHandoverErrorCode_Name(T enum_t_value) {
static_assert(::std::is_same<T, FastPairEvent_BrEdrHandoverErrorCode>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function FastPairEvent_BrEdrHandoverErrorCode_Name.");
return FastPairEvent_BrEdrHandoverErrorCode_Name(static_cast<FastPairEvent_BrEdrHandoverErrorCode>(enum_t_value));
}
bool FastPairEvent_BrEdrHandoverErrorCode_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, FastPairEvent_BrEdrHandoverErrorCode* value);
enum FastPairEvent_CreateBondErrorCode : int {
FastPairEvent_CreateBondErrorCode_UNKNOWN_BOND_ERROR_CODE = 0,
FastPairEvent_CreateBondErrorCode_BOND_BROKEN = 1,
FastPairEvent_CreateBondErrorCode_POSSIBLE_MITM = 2,
FastPairEvent_CreateBondErrorCode_NO_PERMISSION = 3,
FastPairEvent_CreateBondErrorCode_INCORRECT_VARIANT = 4,
FastPairEvent_CreateBondErrorCode_FAILED_BUT_ALREADY_RECEIVE_PASS_KEY = 5
};
bool FastPairEvent_CreateBondErrorCode_IsValid(int value);
constexpr FastPairEvent_CreateBondErrorCode FastPairEvent_CreateBondErrorCode_CreateBondErrorCode_MIN = FastPairEvent_CreateBondErrorCode_UNKNOWN_BOND_ERROR_CODE;
constexpr FastPairEvent_CreateBondErrorCode FastPairEvent_CreateBondErrorCode_CreateBondErrorCode_MAX = FastPairEvent_CreateBondErrorCode_FAILED_BUT_ALREADY_RECEIVE_PASS_KEY;
constexpr int FastPairEvent_CreateBondErrorCode_CreateBondErrorCode_ARRAYSIZE = FastPairEvent_CreateBondErrorCode_CreateBondErrorCode_MAX + 1;
const std::string& FastPairEvent_CreateBondErrorCode_Name(FastPairEvent_CreateBondErrorCode value);
template<typename T>
inline const std::string& FastPairEvent_CreateBondErrorCode_Name(T enum_t_value) {
static_assert(::std::is_same<T, FastPairEvent_CreateBondErrorCode>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function FastPairEvent_CreateBondErrorCode_Name.");
return FastPairEvent_CreateBondErrorCode_Name(static_cast<FastPairEvent_CreateBondErrorCode>(enum_t_value));
}
bool FastPairEvent_CreateBondErrorCode_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, FastPairEvent_CreateBondErrorCode* value);
enum FastPairEvent_ConnectErrorCode : int {
FastPairEvent_ConnectErrorCode_UNKNOWN_CONNECT_ERROR_CODE = 0,
FastPairEvent_ConnectErrorCode_UNSUPPORTED_PROFILE = 1,
FastPairEvent_ConnectErrorCode_GET_PROFILE_PROXY_FAILED = 2,
FastPairEvent_ConnectErrorCode_DISCONNECTED = 3,
FastPairEvent_ConnectErrorCode_LINK_KEY_CLEARED = 4,
FastPairEvent_ConnectErrorCode_FAIL_TO_DISCOVERY = 5,
FastPairEvent_ConnectErrorCode_DISCOVERY_NOT_FINISHED = 6
};
bool FastPairEvent_ConnectErrorCode_IsValid(int value);
constexpr FastPairEvent_ConnectErrorCode FastPairEvent_ConnectErrorCode_ConnectErrorCode_MIN = FastPairEvent_ConnectErrorCode_UNKNOWN_CONNECT_ERROR_CODE;
constexpr FastPairEvent_ConnectErrorCode FastPairEvent_ConnectErrorCode_ConnectErrorCode_MAX = FastPairEvent_ConnectErrorCode_DISCOVERY_NOT_FINISHED;
constexpr int FastPairEvent_ConnectErrorCode_ConnectErrorCode_ARRAYSIZE = FastPairEvent_ConnectErrorCode_ConnectErrorCode_MAX + 1;
const std::string& FastPairEvent_ConnectErrorCode_Name(FastPairEvent_ConnectErrorCode value);
template<typename T>
inline const std::string& FastPairEvent_ConnectErrorCode_Name(T enum_t_value) {
static_assert(::std::is_same<T, FastPairEvent_ConnectErrorCode>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function FastPairEvent_ConnectErrorCode_Name.");
return FastPairEvent_ConnectErrorCode_Name(static_cast<FastPairEvent_ConnectErrorCode>(enum_t_value));
}
bool FastPairEvent_ConnectErrorCode_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, FastPairEvent_ConnectErrorCode* value);
enum DeviceType : int {
UNKNOWN_DEVICE_TYPE = 0,
PHONE = 1,
WEARABLE = 2,
AUTO = 3,
PC = 4,
TV = 5,
TABLET = 6
};
bool DeviceType_IsValid(int value);
constexpr DeviceType DeviceType_MIN = UNKNOWN_DEVICE_TYPE;
constexpr DeviceType DeviceType_MAX = TABLET;
constexpr int DeviceType_ARRAYSIZE = DeviceType_MAX + 1;
const std::string& DeviceType_Name(DeviceType value);
template<typename T>
inline const std::string& DeviceType_Name(T enum_t_value) {
static_assert(::std::is_same<T, DeviceType>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function DeviceType_Name.");
return DeviceType_Name(static_cast<DeviceType>(enum_t_value));
}
bool DeviceType_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, DeviceType* value);
enum OsType : int {
UNKNOWN_OS_TYPE = 0,
ANDROID = 1,
CHROME_OS = 2
};
bool OsType_IsValid(int value);
constexpr OsType OsType_MIN = UNKNOWN_OS_TYPE;
constexpr OsType OsType_MAX = CHROME_OS;
constexpr int OsType_ARRAYSIZE = OsType_MAX + 1;
const std::string& OsType_Name(OsType value);
template<typename T>
inline const std::string& OsType_Name(T enum_t_value) {
static_assert(::std::is_same<T, OsType>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function OsType_Name.");
return OsType_Name(static_cast<OsType>(enum_t_value));
}
bool OsType_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, OsType* value);
// ===================================================================
class FastPairEvent final :
public ::PROTOBUF_NAMESPACE_ID::MessageLite /* @@protoc_insertion_point(class_definition:nearby.proto.fastpair.FastPairEvent) */ {
public:
inline FastPairEvent() : FastPairEvent(nullptr) {}
~FastPairEvent() override;
explicit constexpr FastPairEvent(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
FastPairEvent(const FastPairEvent& from);
FastPairEvent(FastPairEvent&& from) noexcept
: FastPairEvent() {
*this = ::std::move(from);
}
inline FastPairEvent& operator=(const FastPairEvent& from) {
CopyFrom(from);
return *this;
}
inline FastPairEvent& operator=(FastPairEvent&& from) noexcept {
if (this == &from) return *this;
if (GetOwningArena() == from.GetOwningArena()
#ifdef PROTOBUF_FORCE_COPY_IN_MOVE
&& GetOwningArena() != nullptr
#endif // !PROTOBUF_FORCE_COPY_IN_MOVE
) {
InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const std::string& unknown_fields() const {
return _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString);
}
inline std::string* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<std::string>();
}
static const FastPairEvent& default_instance() {
return *internal_default_instance();
}
static inline const FastPairEvent* internal_default_instance() {
return reinterpret_cast<const FastPairEvent*>(
&_FastPairEvent_default_instance_);
}
static constexpr int kIndexInFileMessages =
0;
friend void swap(FastPairEvent& a, FastPairEvent& b) {
a.Swap(&b);
}
inline void Swap(FastPairEvent* other) {
if (other == this) return;
#ifdef PROTOBUF_FORCE_COPY_IN_SWAP
if (GetOwningArena() != nullptr &&
GetOwningArena() == other->GetOwningArena()) {
#else // PROTOBUF_FORCE_COPY_IN_SWAP
if (GetOwningArena() == other->GetOwningArena()) {
#endif // !PROTOBUF_FORCE_COPY_IN_SWAP
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(FastPairEvent* other) {
if (other == this) return;
GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
FastPairEvent* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final {
return CreateMaybeMessage<FastPairEvent>(arena);
}
void CheckTypeAndMergeFrom(const ::PROTOBUF_NAMESPACE_ID::MessageLite& from) final;
void CopyFrom(const FastPairEvent& from);
void MergeFrom(const FastPairEvent& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
uint8_t* _InternalSerialize(
uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(FastPairEvent* other);
private:
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "nearby.proto.fastpair.FastPairEvent";
}
protected:
explicit FastPairEvent(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned = false);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
std::string GetTypeName() const final;
// nested types ----------------------------------------------------
typedef FastPairEvent_BondState BondState;
static constexpr BondState UNKNOWN_BOND_STATE =
FastPairEvent_BondState_UNKNOWN_BOND_STATE;
static constexpr BondState NONE =
FastPairEvent_BondState_NONE;
static constexpr BondState BONDING =
FastPairEvent_BondState_BONDING;
static constexpr BondState BONDED =
FastPairEvent_BondState_BONDED;
static inline bool BondState_IsValid(int value) {
return FastPairEvent_BondState_IsValid(value);
}
static constexpr BondState BondState_MIN =
FastPairEvent_BondState_BondState_MIN;
static constexpr BondState BondState_MAX =
FastPairEvent_BondState_BondState_MAX;
static constexpr int BondState_ARRAYSIZE =
FastPairEvent_BondState_BondState_ARRAYSIZE;
template<typename T>
static inline const std::string& BondState_Name(T enum_t_value) {
static_assert(::std::is_same<T, BondState>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function BondState_Name.");
return FastPairEvent_BondState_Name(enum_t_value);
}
static inline bool BondState_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name,
BondState* value) {
return FastPairEvent_BondState_Parse(name, value);
}
typedef FastPairEvent_ErrorCode ErrorCode;
static constexpr ErrorCode UNKNOWN_ERROR_CODE =
FastPairEvent_ErrorCode_UNKNOWN_ERROR_CODE;
static constexpr ErrorCode OTHER_ERROR =
FastPairEvent_ErrorCode_OTHER_ERROR;
static constexpr ErrorCode TIMEOUT =
FastPairEvent_ErrorCode_TIMEOUT;
static constexpr ErrorCode INTERRUPTED =
FastPairEvent_ErrorCode_INTERRUPTED;
static constexpr ErrorCode REFLECTIVE_OPERATION_EXCEPTION =
FastPairEvent_ErrorCode_REFLECTIVE_OPERATION_EXCEPTION;
static constexpr ErrorCode EXECUTION_EXCEPTION =
FastPairEvent_ErrorCode_EXECUTION_EXCEPTION;
static constexpr ErrorCode PARSE_EXCEPTION =
FastPairEvent_ErrorCode_PARSE_EXCEPTION;
static constexpr ErrorCode MDH_REMOTE_EXCEPTION =
FastPairEvent_ErrorCode_MDH_REMOTE_EXCEPTION;
static constexpr ErrorCode SUCCESS_RETRY_GATT_ERROR =
FastPairEvent_ErrorCode_SUCCESS_RETRY_GATT_ERROR;
static constexpr ErrorCode SUCCESS_RETRY_GATT_TIMEOUT =
FastPairEvent_ErrorCode_SUCCESS_RETRY_GATT_TIMEOUT;
static constexpr ErrorCode SUCCESS_RETRY_SECRET_HANDSHAKE_ERROR =
FastPairEvent_ErrorCode_SUCCESS_RETRY_SECRET_HANDSHAKE_ERROR;
static constexpr ErrorCode SUCCESS_RETRY_SECRET_HANDSHAKE_TIMEOUT =
FastPairEvent_ErrorCode_SUCCESS_RETRY_SECRET_HANDSHAKE_TIMEOUT;
static constexpr ErrorCode SUCCESS_SECRET_HANDSHAKE_RECONNECT =
FastPairEvent_ErrorCode_SUCCESS_SECRET_HANDSHAKE_RECONNECT;
static constexpr ErrorCode SUCCESS_ADDRESS_ROTATE =
FastPairEvent_ErrorCode_SUCCESS_ADDRESS_ROTATE;
static constexpr ErrorCode SUCCESS_SIGNAL_LOST =
FastPairEvent_ErrorCode_SUCCESS_SIGNAL_LOST;
static constexpr ErrorCode DEVICE_NOT_IN_PAIRED_HISTORY_EXCEPTION =
FastPairEvent_ErrorCode_DEVICE_NOT_IN_PAIRED_HISTORY_EXCEPTION;
static constexpr ErrorCode DEVICE_NOT_BONDED_DURING_RETROACTIVE_PAIR =
FastPairEvent_ErrorCode_DEVICE_NOT_BONDED_DURING_RETROACTIVE_PAIR;
static inline bool ErrorCode_IsValid(int value) {
return FastPairEvent_ErrorCode_IsValid(value);
}
static constexpr ErrorCode ErrorCode_MIN =
FastPairEvent_ErrorCode_ErrorCode_MIN;
static constexpr ErrorCode ErrorCode_MAX =
FastPairEvent_ErrorCode_ErrorCode_MAX;
static constexpr int ErrorCode_ARRAYSIZE =
FastPairEvent_ErrorCode_ErrorCode_ARRAYSIZE;
template<typename T>
static inline const std::string& ErrorCode_Name(T enum_t_value) {
static_assert(::std::is_same<T, ErrorCode>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function ErrorCode_Name.");
return FastPairEvent_ErrorCode_Name(enum_t_value);
}
static inline bool ErrorCode_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name,
ErrorCode* value) {
return FastPairEvent_ErrorCode_Parse(name, value);
}
typedef FastPairEvent_BrEdrHandoverErrorCode BrEdrHandoverErrorCode;
static constexpr BrEdrHandoverErrorCode UNKNOWN_BR_EDR_HANDOVER_ERROR_CODE =
FastPairEvent_BrEdrHandoverErrorCode_UNKNOWN_BR_EDR_HANDOVER_ERROR_CODE;
static constexpr BrEdrHandoverErrorCode CONTROL_POINT_RESULT_CODE_NOT_SUCCESS =
FastPairEvent_BrEdrHandoverErrorCode_CONTROL_POINT_RESULT_CODE_NOT_SUCCESS;
static constexpr BrEdrHandoverErrorCode BLUETOOTH_MAC_INVALID =
FastPairEvent_BrEdrHandoverErrorCode_BLUETOOTH_MAC_INVALID;
static constexpr BrEdrHandoverErrorCode TRANSPORT_BLOCK_INVALID =
FastPairEvent_BrEdrHandoverErrorCode_TRANSPORT_BLOCK_INVALID;
static inline bool BrEdrHandoverErrorCode_IsValid(int value) {
return FastPairEvent_BrEdrHandoverErrorCode_IsValid(value);
}
static constexpr BrEdrHandoverErrorCode BrEdrHandoverErrorCode_MIN =
FastPairEvent_BrEdrHandoverErrorCode_BrEdrHandoverErrorCode_MIN;
static constexpr BrEdrHandoverErrorCode BrEdrHandoverErrorCode_MAX =
FastPairEvent_BrEdrHandoverErrorCode_BrEdrHandoverErrorCode_MAX;
static constexpr int BrEdrHandoverErrorCode_ARRAYSIZE =
FastPairEvent_BrEdrHandoverErrorCode_BrEdrHandoverErrorCode_ARRAYSIZE;
template<typename T>
static inline const std::string& BrEdrHandoverErrorCode_Name(T enum_t_value) {
static_assert(::std::is_same<T, BrEdrHandoverErrorCode>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function BrEdrHandoverErrorCode_Name.");
return FastPairEvent_BrEdrHandoverErrorCode_Name(enum_t_value);
}
static inline bool BrEdrHandoverErrorCode_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name,
BrEdrHandoverErrorCode* value) {
return FastPairEvent_BrEdrHandoverErrorCode_Parse(name, value);
}
typedef FastPairEvent_CreateBondErrorCode CreateBondErrorCode;
static constexpr CreateBondErrorCode UNKNOWN_BOND_ERROR_CODE =
FastPairEvent_CreateBondErrorCode_UNKNOWN_BOND_ERROR_CODE;
static constexpr CreateBondErrorCode BOND_BROKEN =
FastPairEvent_CreateBondErrorCode_BOND_BROKEN;
static constexpr CreateBondErrorCode POSSIBLE_MITM =
FastPairEvent_CreateBondErrorCode_POSSIBLE_MITM;
static constexpr CreateBondErrorCode NO_PERMISSION =
FastPairEvent_CreateBondErrorCode_NO_PERMISSION;
static constexpr CreateBondErrorCode INCORRECT_VARIANT =
FastPairEvent_CreateBondErrorCode_INCORRECT_VARIANT;
static constexpr CreateBondErrorCode FAILED_BUT_ALREADY_RECEIVE_PASS_KEY =
FastPairEvent_CreateBondErrorCode_FAILED_BUT_ALREADY_RECEIVE_PASS_KEY;
static inline bool CreateBondErrorCode_IsValid(int value) {
return FastPairEvent_CreateBondErrorCode_IsValid(value);
}
static constexpr CreateBondErrorCode CreateBondErrorCode_MIN =
FastPairEvent_CreateBondErrorCode_CreateBondErrorCode_MIN;
static constexpr CreateBondErrorCode CreateBondErrorCode_MAX =
FastPairEvent_CreateBondErrorCode_CreateBondErrorCode_MAX;
static constexpr int CreateBondErrorCode_ARRAYSIZE =
FastPairEvent_CreateBondErrorCode_CreateBondErrorCode_ARRAYSIZE;
template<typename T>
static inline const std::string& CreateBondErrorCode_Name(T enum_t_value) {
static_assert(::std::is_same<T, CreateBondErrorCode>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function CreateBondErrorCode_Name.");
return FastPairEvent_CreateBondErrorCode_Name(enum_t_value);
}
static inline bool CreateBondErrorCode_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name,
CreateBondErrorCode* value) {
return FastPairEvent_CreateBondErrorCode_Parse(name, value);
}
typedef FastPairEvent_ConnectErrorCode ConnectErrorCode;
static constexpr ConnectErrorCode UNKNOWN_CONNECT_ERROR_CODE =
FastPairEvent_ConnectErrorCode_UNKNOWN_CONNECT_ERROR_CODE;
static constexpr ConnectErrorCode UNSUPPORTED_PROFILE =
FastPairEvent_ConnectErrorCode_UNSUPPORTED_PROFILE;
static constexpr ConnectErrorCode GET_PROFILE_PROXY_FAILED =
FastPairEvent_ConnectErrorCode_GET_PROFILE_PROXY_FAILED;
static constexpr ConnectErrorCode DISCONNECTED =
FastPairEvent_ConnectErrorCode_DISCONNECTED;
static constexpr ConnectErrorCode LINK_KEY_CLEARED =
FastPairEvent_ConnectErrorCode_LINK_KEY_CLEARED;
static constexpr ConnectErrorCode FAIL_TO_DISCOVERY =
FastPairEvent_ConnectErrorCode_FAIL_TO_DISCOVERY;
static constexpr ConnectErrorCode DISCOVERY_NOT_FINISHED =
FastPairEvent_ConnectErrorCode_DISCOVERY_NOT_FINISHED;
static inline bool ConnectErrorCode_IsValid(int value) {
return FastPairEvent_ConnectErrorCode_IsValid(value);
}
static constexpr ConnectErrorCode ConnectErrorCode_MIN =
FastPairEvent_ConnectErrorCode_ConnectErrorCode_MIN;
static constexpr ConnectErrorCode ConnectErrorCode_MAX =
FastPairEvent_ConnectErrorCode_ConnectErrorCode_MAX;
static constexpr int ConnectErrorCode_ARRAYSIZE =
FastPairEvent_ConnectErrorCode_ConnectErrorCode_ARRAYSIZE;
template<typename T>
static inline const std::string& ConnectErrorCode_Name(T enum_t_value) {
static_assert(::std::is_same<T, ConnectErrorCode>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function ConnectErrorCode_Name.");
return FastPairEvent_ConnectErrorCode_Name(enum_t_value);
}
static inline bool ConnectErrorCode_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name,
ConnectErrorCode* value) {
return FastPairEvent_ConnectErrorCode_Parse(name, value);
}
// accessors -------------------------------------------------------
// @@protoc_insertion_point(class_scope:nearby.proto.fastpair.FastPairEvent)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_proto_2ffast_5fpair_5fenums_2eproto;
};
// ===================================================================
// ===================================================================
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// FastPairEvent
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// @@protoc_insertion_point(namespace_scope)
} // namespace fastpair
} // namespace proto
} // namespace nearby
PROTOBUF_NAMESPACE_OPEN
template <> struct is_proto_enum< ::nearby::proto::fastpair::FastPairEvent_BondState> : ::std::true_type {};
template <> struct is_proto_enum< ::nearby::proto::fastpair::FastPairEvent_ErrorCode> : ::std::true_type {};
template <> struct is_proto_enum< ::nearby::proto::fastpair::FastPairEvent_BrEdrHandoverErrorCode> : ::std::true_type {};
template <> struct is_proto_enum< ::nearby::proto::fastpair::FastPairEvent_CreateBondErrorCode> : ::std::true_type {};
template <> struct is_proto_enum< ::nearby::proto::fastpair::FastPairEvent_ConnectErrorCode> : ::std::true_type {};
template <> struct is_proto_enum< ::nearby::proto::fastpair::DeviceType> : ::std::true_type {};
template <> struct is_proto_enum< ::nearby::proto::fastpair::OsType> : ::std::true_type {};
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_proto_2ffast_5fpair_5fenums_2eproto
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+54 -4
View File
@@ -19,7 +19,8 @@ namespace mediums {
constexpr AdvertisementData::AdvertisementData(
::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized)
: tag_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string)
, public_key_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string){}
, public_key_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string)
, rx_advertisement_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string){}
struct AdvertisementDataDefaultTypeInternal {
constexpr AdvertisementDataDefaultTypeInternal()
: _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {}
@@ -61,6 +62,9 @@ class AdvertisementData::_Internal {
static void set_has_public_key(HasBits* has_bits) {
(*has_bits)[0] |= 2u;
}
static void set_has_rx_advertisement(HasBits* has_bits) {
(*has_bits)[0] |= 4u;
}
};
AdvertisementData::AdvertisementData(::PROTOBUF_NAMESPACE_ID::Arena* arena,
@@ -92,6 +96,14 @@ AdvertisementData::AdvertisementData(const AdvertisementData& from)
public_key_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_public_key(),
GetArenaForAllocation());
}
rx_advertisement_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
rx_advertisement_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation());
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
if (from._internal_has_rx_advertisement()) {
rx_advertisement_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_rx_advertisement(),
GetArenaForAllocation());
}
// @@protoc_insertion_point(copy_constructor:location.nearby.mediums.AdvertisementData)
}
@@ -104,6 +116,10 @@ public_key_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringA
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
public_key_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation());
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
rx_advertisement_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
rx_advertisement_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation());
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
}
AdvertisementData::~AdvertisementData() {
@@ -117,6 +133,7 @@ inline void AdvertisementData::SharedDtor() {
GOOGLE_DCHECK(GetArenaForAllocation() == nullptr);
tag_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
public_key_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
rx_advertisement_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
void AdvertisementData::ArenaDtor(void* object) {
@@ -136,13 +153,16 @@ void AdvertisementData::Clear() {
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000007u) {
if (cached_has_bits & 0x00000001u) {
tag_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000002u) {
public_key_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000004u) {
rx_advertisement_.ClearNonDefaultToEmpty();
}
}
_has_bits_.Clear();
_internal_metadata_.Clear<std::string>();
@@ -173,6 +193,15 @@ const char* AdvertisementData::_InternalParse(const char* ptr, ::PROTOBUF_NAMESP
} else
goto handle_unusual;
continue;
// optional bytes rx_advertisement = 3;
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 26)) {
auto str = _internal_mutable_rx_advertisement();
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx);
CHK_(ptr);
} else
goto handle_unusual;
continue;
default:
goto handle_unusual;
} // switch
@@ -216,6 +245,12 @@ uint8_t* AdvertisementData::_InternalSerialize(
2, this->_internal_public_key(), target);
}
// optional bytes rx_advertisement = 3;
if (cached_has_bits & 0x00000004u) {
target = stream->WriteBytesMaybeAliased(
3, this->_internal_rx_advertisement(), target);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = stream->WriteRaw(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).data(),
static_cast<int>(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size()), target);
@@ -233,7 +268,7 @@ size_t AdvertisementData::ByteSizeLong() const {
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000007u) {
// optional bytes tag = 1;
if (cached_has_bits & 0x00000001u) {
total_size += 1 +
@@ -248,6 +283,13 @@ size_t AdvertisementData::ByteSizeLong() const {
this->_internal_public_key());
}
// optional bytes rx_advertisement = 3;
if (cached_has_bits & 0x00000004u) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize(
this->_internal_rx_advertisement());
}
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
total_size += _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size();
@@ -270,13 +312,16 @@ void AdvertisementData::MergeFrom(const AdvertisementData& from) {
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000007u) {
if (cached_has_bits & 0x00000001u) {
_internal_set_tag(from._internal_tag());
}
if (cached_has_bits & 0x00000002u) {
_internal_set_public_key(from._internal_public_key());
}
if (cached_has_bits & 0x00000004u) {
_internal_set_rx_advertisement(from._internal_rx_advertisement());
}
}
_internal_metadata_.MergeFrom<std::string>(from._internal_metadata_);
}
@@ -308,6 +353,11 @@ void AdvertisementData::InternalSwap(AdvertisementData* other) {
&public_key_, lhs_arena,
&other->public_key_, rhs_arena
);
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap(
&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
&rx_advertisement_, lhs_arena,
&other->rx_advertisement_, rhs_arena
);
}
std::string AdvertisementData::GetTypeName() const {
@@ -187,6 +187,7 @@ class AdvertisementData final :
enum : int {
kTagFieldNumber = 1,
kPublicKeyFieldNumber = 2,
kRxAdvertisementFieldNumber = 3,
};
// optional bytes tag = 1;
bool has_tag() const;
@@ -224,6 +225,24 @@ class AdvertisementData final :
std::string* _internal_mutable_public_key();
public:
// optional bytes rx_advertisement = 3;
bool has_rx_advertisement() const;
private:
bool _internal_has_rx_advertisement() const;
public:
void clear_rx_advertisement();
const std::string& rx_advertisement() const;
template <typename ArgT0 = const std::string&, typename... ArgT>
void set_rx_advertisement(ArgT0&& arg0, ArgT... args);
std::string* mutable_rx_advertisement();
PROTOBUF_NODISCARD std::string* release_rx_advertisement();
void set_allocated_rx_advertisement(std::string* rx_advertisement);
private:
const std::string& _internal_rx_advertisement() const;
inline PROTOBUF_ALWAYS_INLINE void _internal_set_rx_advertisement(const std::string& value);
std::string* _internal_mutable_rx_advertisement();
public:
// @@protoc_insertion_point(class_scope:location.nearby.mediums.AdvertisementData)
private:
class _Internal;
@@ -235,6 +254,7 @@ class AdvertisementData final :
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr tag_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr public_key_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr rx_advertisement_;
friend struct ::TableStruct_proto_2fmediums_2fnfc_5fframes_2eproto;
};
// -------------------------------------------------------------------
@@ -573,6 +593,75 @@ inline void AdvertisementData::set_allocated_public_key(std::string* public_key)
// @@protoc_insertion_point(field_set_allocated:location.nearby.mediums.AdvertisementData.public_key)
}
// optional bytes rx_advertisement = 3;
inline bool AdvertisementData::_internal_has_rx_advertisement() const {
bool value = (_has_bits_[0] & 0x00000004u) != 0;
return value;
}
inline bool AdvertisementData::has_rx_advertisement() const {
return _internal_has_rx_advertisement();
}
inline void AdvertisementData::clear_rx_advertisement() {
rx_advertisement_.ClearToEmpty();
_has_bits_[0] &= ~0x00000004u;
}
inline const std::string& AdvertisementData::rx_advertisement() const {
// @@protoc_insertion_point(field_get:location.nearby.mediums.AdvertisementData.rx_advertisement)
return _internal_rx_advertisement();
}
template <typename ArgT0, typename... ArgT>
inline PROTOBUF_ALWAYS_INLINE
void AdvertisementData::set_rx_advertisement(ArgT0&& arg0, ArgT... args) {
_has_bits_[0] |= 0x00000004u;
rx_advertisement_.SetBytes(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation());
// @@protoc_insertion_point(field_set:location.nearby.mediums.AdvertisementData.rx_advertisement)
}
inline std::string* AdvertisementData::mutable_rx_advertisement() {
std::string* _s = _internal_mutable_rx_advertisement();
// @@protoc_insertion_point(field_mutable:location.nearby.mediums.AdvertisementData.rx_advertisement)
return _s;
}
inline const std::string& AdvertisementData::_internal_rx_advertisement() const {
return rx_advertisement_.Get();
}
inline void AdvertisementData::_internal_set_rx_advertisement(const std::string& value) {
_has_bits_[0] |= 0x00000004u;
rx_advertisement_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation());
}
inline std::string* AdvertisementData::_internal_mutable_rx_advertisement() {
_has_bits_[0] |= 0x00000004u;
return rx_advertisement_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation());
}
inline std::string* AdvertisementData::release_rx_advertisement() {
// @@protoc_insertion_point(field_release:location.nearby.mediums.AdvertisementData.rx_advertisement)
if (!_internal_has_rx_advertisement()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000004u;
auto* p = rx_advertisement_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation());
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
if (rx_advertisement_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) {
rx_advertisement_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation());
}
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
return p;
}
inline void AdvertisementData::set_allocated_rx_advertisement(std::string* rx_advertisement) {
if (rx_advertisement != nullptr) {
_has_bits_[0] |= 0x00000004u;
} else {
_has_bits_[0] &= ~0x00000004u;
}
rx_advertisement_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), rx_advertisement,
GetArenaForAllocation());
#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING
if (rx_advertisement_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) {
rx_advertisement_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation());
}
#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING
// @@protoc_insertion_point(field_set_allocated:location.nearby.mediums.AdvertisementData.rx_advertisement)
}
// -------------------------------------------------------------------
// AdvertisementRequest
File diff suppressed because it is too large Load Diff
+147 -30
View File
@@ -122,11 +122,14 @@ enum EventType : int {
FAST_INIT_DISCOVER_DEVICE = 61,
SEND_DESKTOP_NOTIFICATION = 62,
SET_ACCOUNT = 63,
DECRYPT_CERTIFICATE_FAILURE = 64
DECRYPT_CERTIFICATE_FAILURE = 64,
SHOW_ALLOW_PERMISSION_AUTO_ACCESS = 65,
SEND_DESKTOP_TRANSFER_EVENT = 66,
WAITING_FOR_ACCEPT = 67
};
bool EventType_IsValid(int value);
constexpr EventType EventType_MIN = UNKNOWN_EVENT_TYPE;
constexpr EventType EventType_MAX = DECRYPT_CERTIFICATE_FAILURE;
constexpr EventType EventType_MAX = WAITING_FOR_ACCEPT;
constexpr int EventType_ARRAYSIZE = EventType_MAX + 1;
const std::string& EventType_Name(EventType value);
@@ -228,11 +231,18 @@ enum EstablishConnectionStatus : int {
CONNECTION_STATUS_UNKNOWN = 0,
CONNECTION_STATUS_SUCCESS = 1,
CONNECTION_STATUS_FAILURE = 2,
CONNECTION_STATUS_CANCELLATION = 3
CONNECTION_STATUS_CANCELLATION = 3,
CONNECTION_STATUS_MEDIA_UNAVAILABLE_ATTACHMENT = 4,
CONNECTION_STATUS_FAILED_PAIRED_KEYHANDSHAKE = 5,
CONNECTION_STATUS_FAILED_WRITE_INTRODUCTION = 6,
CONNECTION_STATUS_FAILED_NULL_CONNECTION = 7,
CONNECTION_STATUS_FAILED_NO_TRANSFER_UPDATE_CALLBACK = 8,
CONNECTION_STATUS_LOST_CONNECTIVITY = 9,
CONNECTION_STATUS_INVALID_ADVERTISEMENT = 10
};
bool EstablishConnectionStatus_IsValid(int value);
constexpr EstablishConnectionStatus EstablishConnectionStatus_MIN = CONNECTION_STATUS_UNKNOWN;
constexpr EstablishConnectionStatus EstablishConnectionStatus_MAX = CONNECTION_STATUS_CANCELLATION;
constexpr EstablishConnectionStatus EstablishConnectionStatus_MAX = CONNECTION_STATUS_INVALID_ADVERTISEMENT;
constexpr int EstablishConnectionStatus_ARRAYSIZE = EstablishConnectionStatus_MAX + 1;
const std::string& EstablishConnectionStatus_Name(EstablishConnectionStatus value);
@@ -250,28 +260,36 @@ enum AttachmentTransmissionStatus : int {
COMPLETE_ATTACHMENT_TRANSMISSION_STATUS = 1,
CANCELED_ATTACHMENT_TRANSMISSION_STATUS = 2,
FAILED_ATTACHMENT_TRANSMISSION_STATUS = 3,
REJECTED_ATTACHMENT = 4,
TIMED_OUT_ATTACHMENT = 5,
REJECTED_ATTACHMENT PROTOBUF_DEPRECATED_ENUM = 4,
TIMED_OUT_ATTACHMENT PROTOBUF_DEPRECATED_ENUM = 5,
AWAITING_REMOTE_ACCEPTANCE_FAILED_ATTACHMENT PROTOBUF_DEPRECATED_ENUM = 6,
NOT_ENOUGH_SPACE_ATTACHMENT = 7,
FAILED_NO_TRANSFER_UPDATE_CALLBACK = 8,
MEDIA_UNAVAILABLE_ATTACHMENT = 9,
UNSUPPORTED_ATTACHMENT_TYPE_ATTACHMENT = 10,
NO_ATTACHMENT_FOUND = 11,
FAILED_NO_SHARE_TARGET_ENDPOINT = 12,
FAILED_PAIRED_KEYHANDSHAKE = 13,
FAILED_NULL_CONNECTION = 14,
FAILED_NO_PAYLOAD = 15,
FAILED_WRITE_INTRODUCTION = 16,
FAILED_UNKNOWN_REMOTE_RESPONSE = 17,
NOT_ENOUGH_SPACE_ATTACHMENT PROTOBUF_DEPRECATED_ENUM = 7,
FAILED_NO_TRANSFER_UPDATE_CALLBACK PROTOBUF_DEPRECATED_ENUM = 8,
MEDIA_UNAVAILABLE_ATTACHMENT PROTOBUF_DEPRECATED_ENUM = 9,
UNSUPPORTED_ATTACHMENT_TYPE_ATTACHMENT PROTOBUF_DEPRECATED_ENUM = 10,
NO_ATTACHMENT_FOUND PROTOBUF_DEPRECATED_ENUM = 11,
FAILED_NO_SHARE_TARGET_ENDPOINT PROTOBUF_DEPRECATED_ENUM = 12,
FAILED_PAIRED_KEYHANDSHAKE PROTOBUF_DEPRECATED_ENUM = 13,
FAILED_NULL_CONNECTION PROTOBUF_DEPRECATED_ENUM = 14,
FAILED_NO_PAYLOAD PROTOBUF_DEPRECATED_ENUM = 15,
FAILED_WRITE_INTRODUCTION PROTOBUF_DEPRECATED_ENUM = 16,
FAILED_UNKNOWN_REMOTE_RESPONSE PROTOBUF_DEPRECATED_ENUM = 17,
FAILED_NULL_CONNECTION_INIT_OUTGOING = 18,
FAILED_NULL_CONNECTION_DISCONNECTED = 19,
FAILED_NULL_CONNECTION_LOST_CONNECTIVITY = 20,
FAILED_NULL_CONNECTION_FAILURE = 21
FAILED_NULL_CONNECTION_LOST_CONNECTIVITY PROTOBUF_DEPRECATED_ENUM = 20,
FAILED_NULL_CONNECTION_FAILURE PROTOBUF_DEPRECATED_ENUM = 21,
REJECTED_ATTACHMENT_TRANSMISSION_STATUS = 22,
TIMED_OUT_ATTACHMENT_TRANSMISSION_STATUS = 23,
NOT_ENOUGH_SPACE_ATTACHMENT_TRANSMISSION_STATUS = 24,
UNSUPPORTED_ATTACHMENT_TYPE_ATTACHMENT_TRANSMISSION_STATUS = 25,
FAILED_UNKNOWN_REMOTE_RESPONSE_TRANSMISSION_STATUS = 26,
NO_RESPONSE_FRAME_CONNECTION_CLOSED_LOST_CONNECTIVITY_TRANSMISSION_STATUS PROTOBUF_DEPRECATED_ENUM = 27,
NO_RESPONSE_FRAME_CONNECTION_CLOSED_TRANSMISSION_STATUS = 28,
LOST_CONNECTIVITY_TRANSMISSION_STATUS = 29
};
bool AttachmentTransmissionStatus_IsValid(int value);
constexpr AttachmentTransmissionStatus AttachmentTransmissionStatus_MIN = UNKNOWN_ATTACHMENT_TRANSMISSION_STATUS;
constexpr AttachmentTransmissionStatus AttachmentTransmissionStatus_MAX = FAILED_NULL_CONNECTION_FAILURE;
constexpr AttachmentTransmissionStatus AttachmentTransmissionStatus_MAX = LOST_CONNECTIVITY_TRANSMISSION_STATUS;
constexpr int AttachmentTransmissionStatus_ARRAYSIZE = AttachmentTransmissionStatus_MAX + 1;
const std::string& AttachmentTransmissionStatus_Name(AttachmentTransmissionStatus value);
@@ -388,11 +406,12 @@ enum DeviceType : int {
UNKNOWN_DEVICE_TYPE = 0,
PHONE = 1,
TABLET = 2,
LAPTOP = 3
LAPTOP = 3,
CAR = 4
};
bool DeviceType_IsValid(int value);
constexpr DeviceType DeviceType_MIN = UNKNOWN_DEVICE_TYPE;
constexpr DeviceType DeviceType_MAX = LAPTOP;
constexpr DeviceType DeviceType_MAX = CAR;
constexpr int DeviceType_ARRAYSIZE = DeviceType_MAX + 1;
const std::string& DeviceType_Name(DeviceType value);
@@ -410,11 +429,12 @@ enum OSType : int {
ANDROID = 1,
CHROME_OS = 2,
IOS = 3,
WINDOWS = 4
WINDOWS = 4,
MACOS = 5
};
bool OSType_IsValid(int value);
constexpr OSType OSType_MIN = UNKNOWN_OS_TYPE;
constexpr OSType OSType_MAX = WINDOWS;
constexpr OSType OSType_MAX = MACOS;
constexpr int OSType_ARRAYSIZE = OSType_MAX + 1;
const std::string& OSType_Name(OSType value);
@@ -455,11 +475,14 @@ enum LogSource : int {
BETA_TESTER_DEVICES = 3,
OEM_DEVICES = 4,
DEBUG_DEVICES = 5,
NEARBY_MODULE_FOOD_DEVICES = 6
NEARBY_MODULE_FOOD_DEVICES = 6,
BETO_DOGFOOD_DEVICES = 7,
NEARBY_DOGFOOD_DEVICES = 8,
NEARBY_TEAMFOOD_DEVICES = 9
};
bool LogSource_IsValid(int value);
constexpr LogSource LogSource_MIN = UNSPECIFIED_SOURCE;
constexpr LogSource LogSource_MAX = NEARBY_MODULE_FOOD_DEVICES;
constexpr LogSource LogSource_MAX = NEARBY_TEAMFOOD_DEVICES;
constexpr int LogSource_ARRAYSIZE = LogSource_MAX + 1;
const std::string& LogSource_Name(LogSource value);
@@ -483,11 +506,13 @@ enum ServerActionName : int {
DOWNLOAD_SENDER_CERTIFICATES = 7,
UPLOAD_CONTACTS_AND_CERTIFICATES = 8,
LIST_REACHABLE_PHONE_NUMBERS = 9,
LIST_MY_DEVICES = 10
LIST_MY_DEVICES = 10,
LIST_CONTACT_PEOPLE = 11,
DOWNLOAD_CERTIFICATES_INFO = 12
};
bool ServerActionName_IsValid(int value);
constexpr ServerActionName ServerActionName_MIN = UNKNOWN_SERVER_ACTION;
constexpr ServerActionName ServerActionName_MAX = LIST_MY_DEVICES;
constexpr ServerActionName ServerActionName_MAX = DOWNLOAD_CERTIFICATES_INFO;
constexpr int ServerActionName_ARRAYSIZE = ServerActionName_MAX + 1;
const std::string& ServerActionName_Name(ServerActionName value);
@@ -544,11 +569,13 @@ enum SyncPurpose : int {
SYNC_PURPOSE_SHOW_C11N_VIEW = 12,
SYNC_PURPOSE_REGULAR_CHECK_CONTACT_REACHABILITY = 13,
SYNC_PURPOSE_VISIBILITY_SELECTED_CONTACT_CHANGE = 14,
SYNC_PURPOSE_ACCOUNT_CHANGE = 15
SYNC_PURPOSE_ACCOUNT_CHANGE = 15,
SYNC_PURPOSE_REGENERATE_CERTIFICATES = 16,
SYNC_PURPOSE_DEVICE_CONTACTS_CONSENT_CHANGE = 17
};
bool SyncPurpose_IsValid(int value);
constexpr SyncPurpose SyncPurpose_MIN = SYNC_PURPOSE_UNKNOWN;
constexpr SyncPurpose SyncPurpose_MAX = SYNC_PURPOSE_ACCOUNT_CHANGE;
constexpr SyncPurpose SyncPurpose_MAX = SYNC_PURPOSE_DEVICE_CONTACTS_CONSENT_CHANGE;
constexpr int SyncPurpose_ARRAYSIZE = SyncPurpose_MAX + 1;
const std::string& SyncPurpose_Name(SyncPurpose value);
@@ -645,6 +672,28 @@ inline const std::string& AdvertisingMode_Name(T enum_t_value) {
}
bool AdvertisingMode_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, AdvertisingMode* value);
enum DiscoveryMode : int {
UNKNOWN_DISCOVERY_MODE = 0,
SCREEN_OFF_DISCOVERY_MODE = 1,
BACKGROUND_DISCOVERY_MODE = 2,
MIDGROUND_DISCOVERY_MODE = 3,
FOREGROUND_DISCOVERY_MODE = 4
};
bool DiscoveryMode_IsValid(int value);
constexpr DiscoveryMode DiscoveryMode_MIN = UNKNOWN_DISCOVERY_MODE;
constexpr DiscoveryMode DiscoveryMode_MAX = FOREGROUND_DISCOVERY_MODE;
constexpr int DiscoveryMode_ARRAYSIZE = DiscoveryMode_MAX + 1;
const std::string& DiscoveryMode_Name(DiscoveryMode value);
template<typename T>
inline const std::string& DiscoveryMode_Name(T enum_t_value) {
static_assert(::std::is_same<T, DiscoveryMode>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function DiscoveryMode_Name.");
return DiscoveryMode_Name(static_cast<DiscoveryMode>(enum_t_value));
}
bool DiscoveryMode_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, DiscoveryMode* value);
enum ActivityName : int {
UNKNOWN_ACTIVITY = 0,
SHARE_SHEET_ACTIVITY = 1,
@@ -1071,6 +1120,70 @@ inline const std::string& DecryptCertificateFailureStatus_Name(T enum_t_value) {
}
bool DecryptCertificateFailureStatus_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, DecryptCertificateFailureStatus* value);
enum ContactAccess : int {
CONTACT_ACCESS_UNKNOWN = 0,
CONTACT_ACCESS_NO_CONTACT_UPLOADED = 1,
CONTACT_ACCESS_ONLY_UPLOAD_GOOGLE_CONTACT = 2,
CONTACT_ACCESS_UPLOAD_CONTACT_FOR_DEVICE_CONTACT_CONSENT = 3,
CONTACT_ACCESS_UPLOAD_CONTACT_FOR_QUICK_SHARE_CONSENT = 4
};
bool ContactAccess_IsValid(int value);
constexpr ContactAccess ContactAccess_MIN = CONTACT_ACCESS_UNKNOWN;
constexpr ContactAccess ContactAccess_MAX = CONTACT_ACCESS_UPLOAD_CONTACT_FOR_QUICK_SHARE_CONSENT;
constexpr int ContactAccess_ARRAYSIZE = ContactAccess_MAX + 1;
const std::string& ContactAccess_Name(ContactAccess value);
template<typename T>
inline const std::string& ContactAccess_Name(T enum_t_value) {
static_assert(::std::is_same<T, ContactAccess>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function ContactAccess_Name.");
return ContactAccess_Name(static_cast<ContactAccess>(enum_t_value));
}
bool ContactAccess_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, ContactAccess* value);
enum IdentityVerification : int {
IDENTITY_VERIFICATION_UNKNOWN = 0,
IDENTITY_VERIFICATION_NO_PHONE_NUMBER_VERIFIED = 1,
IDENTITY_VERIFICATION_PHONE_NUMBER_VERIFIED_NOT_LINKED_TO_GAIA = 2,
IDENTITY_VERIFICATION_PHONE_NUMBER_VERIFIED_LINKED_TO_QS_GAIA = 3
};
bool IdentityVerification_IsValid(int value);
constexpr IdentityVerification IdentityVerification_MIN = IDENTITY_VERIFICATION_UNKNOWN;
constexpr IdentityVerification IdentityVerification_MAX = IDENTITY_VERIFICATION_PHONE_NUMBER_VERIFIED_LINKED_TO_QS_GAIA;
constexpr int IdentityVerification_ARRAYSIZE = IdentityVerification_MAX + 1;
const std::string& IdentityVerification_Name(IdentityVerification value);
template<typename T>
inline const std::string& IdentityVerification_Name(T enum_t_value) {
static_assert(::std::is_same<T, IdentityVerification>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function IdentityVerification_Name.");
return IdentityVerification_Name(static_cast<IdentityVerification>(enum_t_value));
}
bool IdentityVerification_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, IdentityVerification* value);
enum ButtonStatus : int {
BUTTON_STATUS_UNKNOWN = 0,
BUTTON_STATUS_CLICK_ACCEPT = 1,
BUTTON_STATUS_CLICK_REJECT = 2,
BUTTON_STATUS_IGNORE = 3
};
bool ButtonStatus_IsValid(int value);
constexpr ButtonStatus ButtonStatus_MIN = BUTTON_STATUS_UNKNOWN;
constexpr ButtonStatus ButtonStatus_MAX = BUTTON_STATUS_IGNORE;
constexpr int ButtonStatus_ARRAYSIZE = ButtonStatus_MAX + 1;
const std::string& ButtonStatus_Name(ButtonStatus value);
template<typename T>
inline const std::string& ButtonStatus_Name(T enum_t_value) {
static_assert(::std::is_same<T, ButtonStatus>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function ButtonStatus_Name.");
return ButtonStatus_Name(static_cast<ButtonStatus>(enum_t_value));
}
bool ButtonStatus_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, ButtonStatus* value);
// ===================================================================
@@ -1118,6 +1231,7 @@ template <> struct is_proto_enum< ::location::nearby::proto::sharing::ClientRole
template <> struct is_proto_enum< ::location::nearby::proto::sharing::ScanType> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::sharing::ParsingFailedType> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::sharing::AdvertisingMode> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::sharing::DiscoveryMode> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::sharing::ActivityName> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::sharing::ConsentType> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::sharing::ConsentAcceptanceStatus> : ::std::true_type {};
@@ -1137,6 +1251,9 @@ template <> struct is_proto_enum< ::location::nearby::proto::sharing::FastInitTy
template <> struct is_proto_enum< ::location::nearby::proto::sharing::DesktopNotification> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::sharing::DesktopTransferEventType> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::sharing::DecryptCertificateFailureStatus> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::sharing::ContactAccess> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::sharing::IdentityVerification> : ::std::true_type {};
template <> struct is_proto_enum< ::location::nearby::proto::sharing::ButtonStatus> : ::std::true_type {};
PROTOBUF_NAMESPACE_CLOSE
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+6 -4
View File
@@ -23,10 +23,10 @@ cc_library(
],
copts = ["-DCORE_ADAPTER_DLL"],
visibility = [
"//chrome/chromeos/assistant/data_migration/lib:__pkg__",
"//connections:__subpackages__",
"//location/nearby/cpp/sharing:__subpackages__",
"//location/nearby/testing:__subpackages__",
"//third_party/nearby/sharing:__subpackages__",
"//sharing:__subpackages__",
],
deps = [
":core_types",
@@ -69,17 +69,19 @@ cc_library(
],
copts = ["-DCORE_ADAPTER_DLL"],
visibility = [
"//chrome/chromeos/assistant/data_migration/lib:__pkg__",
"//connections:__subpackages__",
"//location/nearby/cpp/sharing:__subpackages__",
"//location/nearby/testing:__subpackages__",
"//third_party/nearby/sharing:__subpackages__",
"//sharing:__subpackages__",
],
deps = [
"//internal/interop:authentication_status",
"//internal/platform:base",
"//internal/platform:types",
"//internal/platform:util",
"//proto:connections_enums_cc_proto",
"@com_google_absl//absl/functional:any_invocable",
"@com_google_absl//absl/random",
"@com_google_absl//absl/types:variant",
],
)
+96 -3
View File
@@ -1,10 +1,10 @@
# Nearby Connection
Nearby Connections is a high level protocol on top of Bluetooth/WiFi that acts
Nearby Connections is a high level protocol on top of Bluetooth/Wi-Fi that acts
as a medium-agnostic socket. Devices are able to advertise, scan, and connect
with one another over any shared medium (eg. BT <-> BT).
Once connected, the two devices share a list of all supported mediums and
attempt to upgrade to the one with the highest bandwidth (eg. BT -> WiFi).
attempt to upgrade to the one with the highest bandwidth (eg. BT -> Wi-Fi).
The connection is encrypted, reliable, and fully duplex. BYTE, FILE, and STREAM
payloads are all supported and will be chunked & transferred internally and
recombined on the receiving device.
@@ -27,7 +27,7 @@ We support multiple platforms including Linux, iOS & Windows.
> **NOTE:** Linux has no mediums implemented.
Currently we support building from source using [bazel] (https://bazel.build). Other BUILD system such as cmake may be added later.
Currently we support building from source using [bazel](https://bazel.build). Other BUILD system such as cmake may be added later.
### Prerequisites:
@@ -59,3 +59,96 @@ To build the Nearby Connection library:
```shell
swift build
```
# Supported Mediums
<table>
<thead>
<tr>
<th align="left" colspan="2">Legend</th>
</tr>
</thead>
<tbody>
<tr>
<td><ul><li>[x] </li></ul></td>
<td>Supported.</td>
</tr>
<tr>
<td><ul><li>[ ] </li></ul></td>
<td>Support is possible, but not implemented.</td>
</tr>
<tr>
<td></td>
<td>Support is not possible or does not make sense.</td>
</tr>
</tbody>
</table>
## Android
| Mediums | Advertising | Scanning | Data |
| :---------------- | :--------------------: | :--------------------: | :--------------------: |
| Bluetooth Classic | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> |
| BLE (Fast) | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> | |
| BLE (GATT) | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> |
| BLE (Extended) | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> | |
| BLE (L2CAP) | | | <ul><li>[x] </li></ul> |
| Wi-Fi LAN | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> |
| Wi-Fi Hotspot | | | <ul><li>[x] </li></ul> |
| Wi-Fi Direct | | | <ul><li>[x] </li></ul> |
| Wi-Fi Aware | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> |
| WebRTC | | | <ul><li>[x] </li></ul> |
| NFC | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> |
| USB | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> |
| AWDL | | | |
## ChromeOS
| Mediums | Advertising | Scanning | Data |
| :---------------- | :--------------------: | :--------------------: | :--------------------: |
| Bluetooth Classic | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> |
| BLE (Fast) | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> | |
| BLE (GATT) | <ul><li>[ ] </li></ul> | <ul><li>[ ] </li></ul> | <ul><li>[ ] </li></ul> |
| BLE (Extended) | <ul><li>[ ] </li></ul> | <ul><li>[ ] </li></ul> | |
| BLE (L2CAP) | | | |
| Wi-Fi LAN | <ul><li>[ ] </li></ul> | <ul><li>[ ] </li></ul> | <ul><li>[x] </li></ul> |
| Wi-Fi Hotspot | | | <ul><li>[ ] </li></ul> |
| Wi-Fi Direct | | | <ul><li>[ ] </li></ul> |
| Wi-Fi Aware | | | |
| WebRTC | | | <ul><li>[x] </li></ul> |
| NFC | | | |
| USB | <ul><li>[ ] </li></ul> | <ul><li>[ ] </li></ul> | <ul><li>[ ] </li></ul> |
| AWDL | | | |
## Windows
| Mediums | Advertising | Scanning | Data |
| :---------------- | :--------------------: | :--------------------: | :--------------------: |
| Bluetooth Classic | | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> |
| BLE (Fast) | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> | |
| BLE (GATT) | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> | <ul><li>[ ] </li></ul> |
| BLE (Extended) | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> | |
| BLE (L2CAP) | | | |
| Wi-Fi LAN | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> |
| Wi-Fi Hotspot | | | <ul><li>[x] </li></ul> |
| Wi-Fi Direct | | | <ul><li>[ ] </li></ul> |
| Wi-Fi Aware | | | |
| WebRTC | | | <ul><li>[ ] </li></ul> |
| NFC | | | |
| USB | <ul><li>[ ] </li></ul> | <ul><li>[ ] </li></ul> | <ul><li>[ ] </li></ul> |
| AWDL | | | |
## iOS/macOS
| Mediums | Advertising | Scanning | Data |
| :---------------- | :--------------------: | :--------------------: | :--------------------: |
| Bluetooth Classic | | <ul><li>[ ] </li></ul> | <ul><li>[ ] </li></ul> |
| BLE (Fast) | <ul><li>[ ] </li></ul> | <ul><li>[ ] </li></ul> | |
| BLE (GATT) | <ul><li>[ ] </li></ul> | <ul><li>[ ] </li></ul> | <ul><li>[ ] </li></ul> |
| BLE (Extended) | | <ul><li>[ ] </li></ul> | |
| BLE (L2CAP) | | | <ul><li>[ ] </li></ul> |
| Wi-Fi LAN | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> | <ul><li>[x] </li></ul> |
| Wi-Fi Hotspot | | | <ul><li>[ ] </li></ul> |
| Wi-Fi Direct | | | |
| Wi-Fi Aware | | | |
| WebRTC | | | <ul><li>[ ] </li></ul> |
| NFC | | <ul><li>[ ] </li></ul> | |
| USB | | | |
| AWDL | <ul><li>[ ] </li></ul> | <ul><li>[ ] </li></ul> | <ul><li>[ ] </li></ul> |
+2
View File
@@ -33,6 +33,8 @@ struct AdvertisingOptions : public OptionsBase {
bool low_power;
bool enable_bluetooth_listening;
bool enable_webrtc_listening;
// Indicates whether the endpoint id should be stable.
bool use_stable_endpoint_id = false;
// Whether this is intended to be used in conjunction with InjectEndpoint().
bool is_out_of_band_connection = false;
+21 -79
View File
@@ -12,9 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
load("//third_party/lexan/build_defs:lexan.bzl", "lexan")
load("expand_version_template.bzl", "expand_version_template")
load("@bazel_skylib//:bzl_library.bzl", "bzl_library")
load("//third_party/cpptoolchains/windows_llvm/build_defs:windows.bzl", "windows")
package(default_visibility = [
"//connections:__subpackages__",
@@ -24,104 +22,48 @@ package(default_visibility = [
licenses(["notice"])
cc_library(
name = "types",
name = "nc_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"),
)
lexan.resource_files(
name = "resources",
rc_files = [
":version_expanded",
"nc.h",
"nc_def.h",
"nc_types.h",
],
compatible_with = ["//buildenv/target:non_prod"],
)
cc_library(
name = "c",
name = "nc",
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",
"nc.cc",
],
compatible_with = ["//buildenv/target:non_prod"],
copts = ["-DNC_DLL"],
deps = [
":types",
":nc_types",
"//connections:core",
"//connections:core_types",
"//connections/implementation/flags:connections_flags",
"//internal/flags:nearby_flags",
"//internal/platform:base",
"//internal/platform:types",
"//proto:connections_enums_cc_proto",
"@com_google_absl//absl/base:no_destructor",
"@com_google_absl//absl/container:flat_hash_map",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/strings:str_format",
"@com_google_absl//absl/types:span",
],
)
# Build with --config=lexan
lexan.cc_windows_dll(
name = "nearby_connections",
windows.cc_windows_dll(
name = "nc_windows",
srcs = [],
compatible_with = ["//buildenv/target:non_prod"],
copts = ["-DNC_DLL"],
tags = ["windows-dll"],
deps = [
":c",
":types",
":nc",
"//internal/platform/implementation/windows",
"@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_
-293
View File
@@ -1,293 +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)
NEARBY_LOG_SET_SEVERITY(VERBOSE);
#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);
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::DiscoveryListener discoveryListener =
std::move(*listener.GetImpl());
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, discoveryListener,
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_
-44
View File
@@ -1,44 +0,0 @@
"""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
-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_
+671
View File
@@ -0,0 +1,671 @@
// Copyright 2024 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/nc.h"
#include <stddef.h>
#include <sys/stat.h>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/no_destructor.h"
#include "absl/container/flat_hash_map.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "connections/advertising_options.h"
#include "connections/c/nc_types.h"
#include "connections/connection_options.h"
#include "connections/core.h"
#include "connections/discovery_options.h"
#include "connections/implementation/flags/nearby_connections_feature_flags.h"
#include "connections/listeners.h"
#include "connections/medium_selector.h"
#include "connections/out_of_band_connection_metadata.h"
#include "connections/params.h"
#include "connections/payload.h"
#include "connections/status.h"
#include "connections/strategy.h"
#include "internal/flags/nearby_flags.h"
#include "internal/platform/bluetooth_utils.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/file.h"
#include "internal/platform/logging.h"
namespace nearby::connections {
class Core;
class ServiceController;
class ServiceControllerRouter;
class OfflineServiceController;
} // namespace nearby::connections
typedef struct NcContext {
::nearby::connections::ServiceControllerRouter* router = nullptr;
::nearby::connections::Core* core = nullptr;
} NcContext;
absl::NoDestructor<absl::flat_hash_map<NC_INSTANCE, NcContext>> kNcContextMap;
int64_t getFileSize(const char* filename) {
struct stat file_status;
if (stat(filename, &file_status) < 0) {
return -1;
}
return file_status.st_size;
}
int convertStringToInt(absl::string_view data) {
if (data.size() != 4) {
return 0;
}
return (data[0]) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
}
std::string convertIntToString(int input) {
std::string result;
result.resize(4);
result[0] = input & 0xff;
result[1] = (input >> 8) & 0xff;
result[2] = (input >> 16) & 0xff;
result[3] = (input >> 24) & 0xff;
return result;
}
NcContext* GetContext(NC_INSTANCE instance) {
auto it = kNcContextMap->find(instance);
if (it == kNcContextMap->end()) {
return nullptr;
}
return &it->second;
}
::nearby::connections::ConnectionRequestInfo GetCppConnectionRequestInfo(
NC_INSTANCE instance,
const NC_CONNECTION_REQUEST_INFO& connection_request_info) {
::nearby::connections::ConnectionRequestInfo cpp_connection_request_info;
cpp_connection_request_info.endpoint_info =
nearby::ByteArray(connection_request_info.endpoint_info.data,
connection_request_info.endpoint_info.size);
::nearby::connections::ConnectionListener cpp_connection_listener;
cpp_connection_listener.accepted_cb = [=](const std::string& endpoint_id) {
connection_request_info.accepted_callback(instance,
convertStringToInt(endpoint_id));
};
cpp_connection_listener.bandwidth_changed_cb =
[=](const std::string& endpoint_id,
::nearby::connections::Medium medium) {
connection_request_info.bandwidth_changed_callback(
instance, convertStringToInt(endpoint_id),
static_cast<NC_MEDIUM>(medium));
};
cpp_connection_listener.disconnected_cb =
[=](const std::string& endpoint_id) {
connection_request_info.disconnected_callback(
instance, convertStringToInt(endpoint_id));
};
cpp_connection_listener.initiated_cb =
[=](const std::string& endpoint_id,
const ::nearby::connections::ConnectionResponseInfo& info) {
NC_CONNECTION_RESPONSE_INFO connection_response_info;
connection_response_info.is_connection_verified =
info.is_connection_verified;
connection_response_info.is_incoming_connection =
info.is_incoming_connection;
connection_response_info.remote_endpoint_info.data =
(char*)info.remote_endpoint_info.data();
connection_response_info.remote_endpoint_info.size =
info.remote_endpoint_info.size();
connection_response_info.authentication_token.data =
(char*)info.authentication_token.data();
connection_response_info.authentication_token.size =
info.authentication_token.size();
connection_response_info.raw_authentication_token.data =
(char*)info.raw_authentication_token.data();
connection_response_info.raw_authentication_token.size =
info.raw_authentication_token.size();
connection_request_info.initiated_callback(
instance, convertStringToInt(endpoint_id),
&connection_response_info);
};
cpp_connection_listener.rejected_cb =
[=](const std::string& endpoint_id,
::nearby::connections::Status status) {
connection_request_info.rejected_callback(
instance, convertStringToInt(endpoint_id),
static_cast<NC_STATUS>(status.value));
};
cpp_connection_request_info.listener = std::move(cpp_connection_listener);
return cpp_connection_request_info;
}
NC_INSTANCE NcCreateService() {
NcContext nc_context;
nc_context.router = new ::nearby::connections::ServiceControllerRouter();
nc_context.core = new ::nearby::connections::Core(nc_context.router);
kNcContextMap->insert({nc_context.core, nc_context});
return nc_context.core;
}
void NcCloseService(NC_INSTANCE instance) {
NcContext* nc_context = GetContext(instance);
if (nc_context == nullptr) {
NEARBY_LOGS(WARNING) << "Trying to close not existent service " << instance;
return;
}
nc_context->core->StopAllEndpoints([](::nearby::connections::Status status) {
NEARBY_LOGS(INFO) << "Stopping all endpoints with status "
<< status.ToString();
});
kNcContextMap->erase(nc_context->core);
delete nc_context->router;
delete nc_context->core;
}
void NcStartAdvertising(
NC_INSTANCE instance, const NC_DATA* service_id,
const NC_ADVERTISING_OPTIONS* advertising_options,
const NC_CONNECTION_REQUEST_INFO* connection_request_info,
NcCallbackResult result_callback) {
NcContext* nc_context = GetContext(instance);
if (nc_context == nullptr) {
result_callback(NC_STATUS_ERROR);
return;
}
::nearby::connections::ConnectionRequestInfo cpp_connection_request_info =
GetCppConnectionRequestInfo(instance, *connection_request_info);
::nearby::connections::AdvertisingOptions cpp_advertising_options;
cpp_advertising_options.allowed.ble =
advertising_options->common_options.allowed_mediums[NC_MEDIUM_BLE];
cpp_advertising_options.allowed.bluetooth =
advertising_options->common_options.allowed_mediums[NC_MEDIUM_BLUETOOTH];
cpp_advertising_options.allowed.wifi_lan =
advertising_options->common_options.allowed_mediums[NC_MEDIUM_WIFI_LAN];
cpp_advertising_options.allowed.wifi_direct =
advertising_options->common_options
.allowed_mediums[NC_MEDIUM_WIFI_DIRECT];
cpp_advertising_options.allowed.wifi_hotspot =
advertising_options->common_options
.allowed_mediums[NC_MEDIUM_WIFI_HOTSPOT];
cpp_advertising_options.allowed.web_rtc =
advertising_options->common_options.allowed_mediums[NC_MEDIUM_WEB_RTC];
cpp_advertising_options.enable_bluetooth_listening =
advertising_options->enable_bluetooth_listening;
cpp_advertising_options.enable_webrtc_listening =
advertising_options->enable_webrtc_listening;
cpp_advertising_options.auto_upgrade_bandwidth =
advertising_options->auto_upgrade_bandwidth;
cpp_advertising_options.enforce_topology_constraints =
advertising_options->enforce_topology_constraints;
if (advertising_options->fast_advertisement_service_uuid.size > 0) {
cpp_advertising_options.fast_advertisement_service_uuid =
std::string(advertising_options->fast_advertisement_service_uuid.data,
advertising_options->fast_advertisement_service_uuid.size);
}
cpp_advertising_options.is_out_of_band_connection =
advertising_options->is_out_of_band_connection;
cpp_advertising_options.low_power = advertising_options->low_power;
if (advertising_options->common_options.strategy.type ==
NC_STRATEGY_TYPE_NONE) {
cpp_advertising_options.strategy = ::nearby::connections::Strategy::kNone;
}
if (advertising_options->common_options.strategy.type ==
NC_STRATEGY_TYPE_P2P_CLUSTER)
cpp_advertising_options.strategy =
::nearby::connections::Strategy::kP2pCluster;
if (advertising_options->common_options.strategy.type ==
NC_STRATEGY_TYPE_P2P_POINT_TO_POINT)
cpp_advertising_options.strategy =
::nearby::connections::Strategy::kP2pPointToPoint;
if (advertising_options->common_options.strategy.type ==
NC_STRATEGY_TYPE_P2P_STAR)
cpp_advertising_options.strategy =
::nearby::connections::Strategy::kP2pStar;
nc_context->core->StartAdvertising(
std::string(service_id->data, service_id->size),
std::move(cpp_advertising_options),
std::move(cpp_connection_request_info),
[=](::nearby::connections::Status status) {
result_callback(static_cast<NC_STATUS>(status.value));
});
}
void NcStopAdvertising(NC_INSTANCE instance, NcCallbackResult result_callback) {
NcContext* nc_context = GetContext(instance);
if (nc_context == nullptr) {
result_callback(NC_STATUS_ERROR);
return;
}
nc_context->core->StopAdvertising([=](::nearby::connections::Status status) {
result_callback(static_cast<NC_STATUS>(status.value));
});
}
void NcStartDiscovery(NC_INSTANCE instance, const NC_DATA* service_id,
const NC_DISCOVERY_OPTIONS* discovery_options,
const NC_DISCOVERY_LISTENER* discovery_listener,
NcCallbackResult result_callback) {
NcContext* nc_context = GetContext(instance);
if (nc_context == nullptr) {
result_callback(NC_STATUS_ERROR);
return;
}
::nearby::connections::DiscoveryOptions cpp_discovery_options;
if (discovery_options->common_options.strategy.type == NC_STRATEGY_TYPE_NONE)
cpp_discovery_options.strategy = ::nearby::connections::Strategy::kNone;
if (discovery_options->common_options.strategy.type ==
NC_STRATEGY_TYPE_P2P_CLUSTER)
cpp_discovery_options.strategy =
::nearby::connections::Strategy::kP2pCluster;
if (discovery_options->common_options.strategy.type ==
NC_STRATEGY_TYPE_P2P_POINT_TO_POINT)
cpp_discovery_options.strategy =
::nearby::connections::Strategy::kP2pPointToPoint;
if (discovery_options->common_options.strategy.type ==
NC_STRATEGY_TYPE_P2P_STAR)
cpp_discovery_options.strategy = ::nearby::connections::Strategy::kP2pStar;
cpp_discovery_options.auto_upgrade_bandwidth =
discovery_options->auto_upgrade_bandwidth;
cpp_discovery_options.enforce_topology_constraints =
discovery_options->enforce_topology_constraints;
cpp_discovery_options.is_out_of_band_connection =
discovery_options->is_out_of_band_connection;
if (discovery_options->fast_advertisement_service_uuid.size > 0) {
cpp_discovery_options.fast_advertisement_service_uuid =
std::string(discovery_options->fast_advertisement_service_uuid.data,
discovery_options->fast_advertisement_service_uuid.size);
}
cpp_discovery_options.low_power = discovery_options->low_power;
cpp_discovery_options.allowed.bluetooth =
discovery_options->common_options.allowed_mediums[NC_MEDIUM_BLUETOOTH];
cpp_discovery_options.allowed.ble =
discovery_options->common_options.allowed_mediums[NC_MEDIUM_BLE];
cpp_discovery_options.allowed.wifi_lan =
discovery_options->common_options.allowed_mediums[NC_MEDIUM_WIFI_LAN];
cpp_discovery_options.allowed.wifi_hotspot =
discovery_options->common_options.allowed_mediums[NC_MEDIUM_WIFI_HOTSPOT];
cpp_discovery_options.allowed.web_rtc =
discovery_options->common_options.allowed_mediums[NC_MEDIUM_WEB_RTC];
NC_DISCOVERY_LISTENER discovery_listener_copy = *discovery_listener;
::nearby::connections::DiscoveryListener listener;
listener.endpoint_distance_changed_cb =
[=](const std::string& endpoint_id,
::nearby::connections::DistanceInfo info) {
discovery_listener_copy.endpoint_distance_changed_callback(
instance, convertStringToInt(endpoint_id),
static_cast<NC_DISTANCE_INFO>(info));
};
listener.endpoint_found_cb = [=](const std::string& endpoint_id,
const nearby::ByteArray& endpoint_info,
const std::string& service_id) {
NC_DATA endpoint_info_data = {
.size = static_cast<int64_t>(endpoint_info.size()),
.data = (char*)endpoint_info.data()};
NC_DATA service_id_data = {.size = static_cast<int64_t>(service_id.size()),
.data = (char*)service_id.data()};
discovery_listener_copy.endpoint_found_callback(
instance, convertStringToInt(endpoint_id), &endpoint_info_data,
&service_id_data);
};
listener.endpoint_lost_cb = [=](const std::string& endpoint_id) {
discovery_listener_copy.endpoint_lost_callback(
instance, convertStringToInt(endpoint_id));
};
nc_context->core->StartDiscovery(
std::string(service_id->data, service_id->size),
std::move(cpp_discovery_options), std::move(listener),
[result_callback =
std::move(result_callback)](::nearby::connections::Status status) {
result_callback(static_cast<NC_STATUS>(status.value));
});
}
void NcStopDiscovery(NC_INSTANCE instance, NcCallbackResult result_callback) {
NcContext* nc_context = GetContext(instance);
if (nc_context == nullptr) {
result_callback(NC_STATUS_ERROR);
return;
}
nc_context->core->StopDiscovery([=](::nearby::connections::Status status) {
result_callback(static_cast<NC_STATUS>(status.value));
});
}
void NcInjectEndpoint(NC_INSTANCE instance, const NC_DATA* service_id,
const NC_OUT_OF_BAND_CONNECTION_METADATA* metadata,
NcCallbackResult result_callback) {
NcContext* nc_context = GetContext(instance);
if (nc_context == nullptr) {
result_callback(NC_STATUS_ERROR);
return;
}
::nearby::connections::OutOfBandConnectionMetadata
cpp_out_of_band_connection_metadata;
cpp_out_of_band_connection_metadata.endpoint_id = metadata->endpoint_id;
cpp_out_of_band_connection_metadata.endpoint_info = {
metadata->endpoint_info.data,
static_cast<size_t>(metadata->endpoint_info.size)};
cpp_out_of_band_connection_metadata.medium =
static_cast<::nearby::connections::Medium>(metadata->medium);
cpp_out_of_band_connection_metadata.remote_bluetooth_mac_address = {
metadata->remote_bluetooth_mac_address.data,
static_cast<size_t>(metadata->remote_bluetooth_mac_address.size)};
nc_context->core->InjectEndpoint(
std::string(service_id->data, service_id->size),
cpp_out_of_band_connection_metadata,
[=](::nearby::connections::Status status) {
result_callback(static_cast<NC_STATUS>(status.value));
});
}
void NcRequestConnection(
NC_INSTANCE instance, int endpoint_id,
const NC_CONNECTION_REQUEST_INFO* connection_request_info,
const NC_CONNECTION_OPTIONS* connection_options,
NcCallbackResult result_callback) {
NcContext* nc_context = GetContext(instance);
if (nc_context == nullptr) {
result_callback(NC_STATUS_ERROR);
return;
}
::nearby::connections::ConnectionRequestInfo cpp_connection_request_info =
GetCppConnectionRequestInfo(instance, *connection_request_info);
::nearby::connections::ConnectionOptions cpp_connection_options;
cpp_connection_options.allowed.ble =
connection_options->common_options.allowed_mediums[NC_MEDIUM_BLE];
cpp_connection_options.allowed.bluetooth =
connection_options->common_options.allowed_mediums[NC_MEDIUM_BLUETOOTH];
cpp_connection_options.allowed.web_rtc =
connection_options->common_options.allowed_mediums[NC_MEDIUM_WEB_RTC];
cpp_connection_options.allowed.wifi_lan =
connection_options->common_options.allowed_mediums[NC_MEDIUM_WIFI_LAN];
cpp_connection_options.auto_upgrade_bandwidth =
connection_options->auto_upgrade_bandwidth;
cpp_connection_options.enforce_topology_constraints =
connection_options->enforce_topology_constraints;
if (connection_options->fast_advertisement_service_uuid.size > 0) {
cpp_connection_options.fast_advertisement_service_uuid =
std::string(connection_options->fast_advertisement_service_uuid.data,
connection_options->fast_advertisement_service_uuid.size);
}
cpp_connection_options.is_out_of_band_connection =
connection_options->is_out_of_band_connection;
cpp_connection_options.keep_alive_interval_millis =
connection_options->keep_alive_interval_millis;
cpp_connection_options.keep_alive_timeout_millis =
connection_options->keep_alive_timeout_millis;
cpp_connection_options.low_power = connection_options->low_power;
if (connection_options->remote_bluetooth_mac_address.size > 0) {
cpp_connection_options.remote_bluetooth_mac_address =
nearby::BluetoothUtils::FromString(
std::string(connection_options->remote_bluetooth_mac_address.data,
connection_options->remote_bluetooth_mac_address.size));
}
if (connection_options->common_options.strategy.type == NC_STRATEGY_TYPE_NONE)
cpp_connection_options.strategy = ::nearby::connections::Strategy::kNone;
if (connection_options->common_options.strategy.type ==
NC_STRATEGY_TYPE_P2P_CLUSTER)
cpp_connection_options.strategy =
::nearby::connections::Strategy::kP2pCluster;
if (connection_options->common_options.strategy.type ==
NC_STRATEGY_TYPE_P2P_POINT_TO_POINT)
cpp_connection_options.strategy =
::nearby::connections::Strategy::kP2pPointToPoint;
if (connection_options->common_options.strategy.type ==
NC_STRATEGY_TYPE_P2P_STAR)
cpp_connection_options.strategy = ::nearby::connections::Strategy::kP2pStar;
nc_context->core->RequestConnection(
convertIntToString(endpoint_id), std::move(cpp_connection_request_info),
std::move(cpp_connection_options),
[=](::nearby::connections::Status status) {
result_callback(static_cast<NC_STATUS>(status.value));
});
}
void NcAcceptConnection(NC_INSTANCE instance, int endpoint_id,
NC_PAYLOAD_LISTENER payload_listener,
NcCallbackResult result_callback) {
NcContext* nc_context = GetContext(instance);
if (nc_context == nullptr) {
result_callback(NC_STATUS_ERROR);
return;
}
::nearby::connections::PayloadListener cpp_payload_listener;
cpp_payload_listener.payload_cb =
[=](absl::string_view endpoint_id,
::nearby::connections::Payload payload) {
NC_PAYLOAD nc_payload;
nc_payload.id = payload.GetId();
nc_payload.direction = NC_PAYLOAD_DIRECTION_INCOMING;
nc_payload.type = static_cast<NC_PAYLOAD_TYPE>(payload.GetType());
if (nc_payload.type == NC_PAYLOAD_TYPE_BYTES) {
nearby::ByteArray bytes = payload.AsBytes();
nc_payload.content.bytes.content.data = bytes.data();
nc_payload.content.bytes.content.size = bytes.size();
} else if (nc_payload.type == NC_PAYLOAD_TYPE_FILE) {
nc_payload.content.file.file_name =
(char*)payload.GetFileName().c_str();
nc_payload.content.file.parent_folder =
(char*)payload.GetParentFolder().c_str();
nc_payload.content.file.offset = payload.GetOffset();
} else if (nc_payload.type == NC_PAYLOAD_TYPE_STREAM) {
// TODO(guogang): support stream later.
}
payload_listener.received_callback(
instance, convertStringToInt(endpoint_id), &nc_payload);
};
cpp_payload_listener.payload_progress_cb =
[=](absl::string_view endpoint_id,
const ::nearby::connections::PayloadProgressInfo& progress) {
NC_PAYLOAD_PROGRESS_INFO nc_payload_progress_info;
nc_payload_progress_info.id = progress.payload_id;
nc_payload_progress_info.bytes_transferred = progress.bytes_transferred;
nc_payload_progress_info.total_bytes = progress.total_bytes;
nc_payload_progress_info.status =
static_cast<NC_PAYLOAD_PROGRESS_INFO_STATUS>(progress.status);
payload_listener.progress_updated_callback(
instance, convertStringToInt(endpoint_id),
&nc_payload_progress_info);
};
nc_context->core->AcceptConnection(
convertIntToString(endpoint_id), std::move(cpp_payload_listener),
[=](::nearby::connections::Status status) {
result_callback(static_cast<NC_STATUS>(status.value));
});
}
void NcRejectConnection(NC_INSTANCE instance, int endpoint_id,
NcCallbackResult result_callback) {
NcContext* nc_context = GetContext(instance);
if (nc_context == nullptr) {
result_callback(NC_STATUS_ERROR);
return;
}
nc_context->core->RejectConnection(
convertIntToString(endpoint_id),
[=](::nearby::connections::Status status) {
result_callback(static_cast<NC_STATUS>(status.value));
});
}
void NcSendPayload(NC_INSTANCE instance, size_t endpoint_ids_size,
const int* endpoint_ids, const NC_PAYLOAD* payload,
NcCallbackResult result_callback) {
NcContext* nc_context = GetContext(instance);
if (nc_context == nullptr) {
result_callback(NC_STATUS_ERROR);
return;
}
std::vector<std::string> endpoint_ids_vector;
for (size_t i = 0; i < endpoint_ids_size; ++i) {
endpoint_ids_vector.push_back(convertIntToString(endpoint_ids[i]));
}
absl::Span<const std::string> endpoint_ids_span(endpoint_ids_vector.data(),
endpoint_ids_size);
::nearby::connections::Payload cpp_payload;
if (payload->type == NC_PAYLOAD_TYPE_BYTES) {
cpp_payload = ::nearby::connections::Payload(
payload->id, nearby::ByteArray(payload->content.bytes.content.data,
payload->content.bytes.content.size));
} else if (payload->type == NC_PAYLOAD_TYPE_FILE) {
// get file size
std::string full_file_name = "";
if (payload->content.file.parent_folder == nullptr) {
full_file_name = payload->content.file.file_name;
} else {
full_file_name = absl::StrCat(payload->content.file.parent_folder, "/",
payload->content.file.file_name);
}
nearby::InputFile input_file(full_file_name,
getFileSize(full_file_name.c_str()));
cpp_payload =
::nearby::connections::Payload(payload->id, std::move(input_file));
} else if (payload->type == NC_PAYLOAD_TYPE_STREAM) {
// TODO(guogang): support stream later.
}
nc_context->core->SendPayload(
endpoint_ids_span, std::move(cpp_payload),
[=](::nearby::connections::Status status) {
result_callback(static_cast<NC_STATUS>(status.value));
});
}
void NcCancelPayload(NC_INSTANCE instance, NC_PAYLOAD_ID payload_id,
NcCallbackResult result_callback) {
NcContext* nc_context = GetContext(instance);
if (nc_context == nullptr) {
result_callback(NC_STATUS_ERROR);
return;
}
nc_context->core->CancelPayload(
payload_id, [=](::nearby::connections::Status status) {
result_callback(static_cast<NC_STATUS>(status.value));
});
}
void NcDisconnectFromEndpoint(NC_INSTANCE instance, int endpoint_id,
NcCallbackResult result_callback) {
NcContext* nc_context = GetContext(instance);
if (nc_context == nullptr) {
result_callback(NC_STATUS_ERROR);
return;
}
nc_context->core->DisconnectFromEndpoint(
convertIntToString(endpoint_id),
[=](::nearby::connections::Status status) {
result_callback(static_cast<NC_STATUS>(status.value));
});
}
void NcStopAllEndpoints(NC_INSTANCE instance,
NcCallbackResult result_callback) {
NcContext* nc_context = GetContext(instance);
if (nc_context == nullptr) {
result_callback(NC_STATUS_ERROR);
return;
}
nc_context->core->StopAllEndpoints([=](::nearby::connections::Status status) {
result_callback(static_cast<NC_STATUS>(status.value));
});
}
void NcInitiateBandwidthUpgrade(NC_INSTANCE instance, int endpoint_id,
NcCallbackResult result_callback) {
NcContext* nc_context = GetContext(instance);
if (nc_context == nullptr) {
result_callback(NC_STATUS_ERROR);
return;
}
nc_context->core->InitiateBandwidthUpgrade(
convertIntToString(endpoint_id),
[=](::nearby::connections::Status status) {
result_callback(static_cast<NC_STATUS>(status.value));
});
}
int NcGetLocalEndpointId(NC_INSTANCE instance) {
NcContext* nc_context = GetContext(instance);
if (nc_context == nullptr) {
return 0;
}
std::string endpoint_id = nc_context->core->GetLocalEndpointId();
return convertStringToInt(endpoint_id);
}
void NcEnableBleV2(NC_INSTANCE instance, bool enable,
NcCallbackResult result_callback) {
nearby::NearbyFlags::GetInstance().OverrideBoolFlagValue(
::nearby::connections::config_package_nearby::nearby_connections_feature::
kEnableBleV2,
enable);
result_callback(NC_STATUS_SUCCESS);
}
void NcSetCustomSavePath(NC_INSTANCE instance, const NC_DATA* save_path,
NcCallbackResult result_callback) {
NcContext* nc_context = GetContext(instance);
if (nc_context == nullptr) {
result_callback(NC_STATUS_ERROR);
return;
}
nc_context->core->SetCustomSavePath(
std::string(save_path->data, save_path->size),
[=](::nearby::connections::Status status) {
result_callback(static_cast<NC_STATUS>(status.value));
});
}
+178
View File
@@ -0,0 +1,178 @@
// Copyright 2024 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_NC_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_C_NC_H_
#include <stddef.h>
#include "connections/c/nc_def.h"
#include "connections/c/nc_types.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
// Creates a new Nearby Connections service.
NC_API NC_INSTANCE NcCreateService();
NC_API void NcCloseService(NC_INSTANCE instance);
// Starts adververtising an endpoint using Nearby Connections.
//
// instance - The returned instance by NcOpenService.
// service_id - The ID for the service to be advertised.
// advertising_options - The options for advertising.
// connection_request_info - Connection parameters, including endpoint info
// and listeners.
// result_callback - The result of the API operation.
NC_API void NcStartAdvertising(
NC_INSTANCE instance, const NC_DATA* service_id,
const NC_ADVERTISING_OPTIONS* advertising_options,
const NC_CONNECTION_REQUEST_INFO* connection_request_info,
NcCallbackResult result_callback);
// Stops advertising a local endpoint. It should be called after calling
// StartAdvertising.
//
// instance - The instance is used to start advertising.
// result_callback - The result of the API operation.
NC_API void NcStopAdvertising(NC_INSTANCE instance,
NcCallbackResult result_callback);
// Starts to discover for remote endpoints with the specified service ID.
//
// instance - The returned instance by NcOpenService.
// service_id - The ID for the service to be discovered.
// discovery_options - The options for discovery.
// discovery_listener - The callbacks notified when a remote endpoint is
// reported.
// result_callback - The result of the API operation.
NC_API void NcStartDiscovery(NC_INSTANCE instance, const NC_DATA* service_id,
const NC_DISCOVERY_OPTIONS* discovery_options,
const NC_DISCOVERY_LISTENER* discovery_listener,
NcCallbackResult result_callback);
// Stops discovering for a running discovery.
//
// instance - The instance is used to start discovery.
// result_callback - The result of the API operation.
NC_API void NcStopDiscovery(NC_INSTANCE instance,
NcCallbackResult result_callback);
// Invokes the discovery callback from a previous call to NcStartDiscovery()
// with the given endpoint info. The previous call to NcStartDiscovery() must
// have been passed ConnectionOptions with is_out_of_band_connection == true.
//
// instance - The instance is used to start discovery.
// service_id - The ID for the service to be discovered, as specified in the
// corresponding call to NcStartDiscovery().
// metadata - Metadata used in order to inject the endpoint.
// result_callback - The result of the API operation.
NC_API void NcInjectEndpoint(NC_INSTANCE instance, const NC_DATA* service_id,
const NC_OUT_OF_BAND_CONNECTION_METADATA* metadata,
NcCallbackResult result_callback);
// Sends a request to connect to a remote endpoint.
//
// instance - The returned instance by NcOpenService.
// endpoint_id - The identifier for the remote endpoint to which a
// connection request will be sent.
// connection_request_info - Connection parameters.
// connection_options - Options to connect.
// result_callback - The result of the API operation.
NC_API void NcRequestConnection(
NC_INSTANCE instance, int endpoint_id,
const NC_CONNECTION_REQUEST_INFO* connection_request_info,
const NC_CONNECTION_OPTIONS* connection_options,
NcCallbackResult result_callback);
// Accepts a connection to a remote endpoint.
//
// instance - The returned instance by NcOpenService.
// endpoint_id - The identifier for the remote endpoint.
// payload_listener - A callback for payloads exchanged with the remote
// endpoint.
// result_callback - The result of the API operation.
NC_API void NcAcceptConnection(NC_INSTANCE instance, int endpoint_id,
NC_PAYLOAD_LISTENER payload_listener,
NcCallbackResult result_callback);
// Rejects a connection from a remote endpoint.
//
// instance - The returned instance by NcOpenService.
// endpoint_id - The identifier for the remote endpoint.
// result_callback - The result of the API operation.
NC_API void NcRejectConnection(NC_INSTANCE instance, int endpoint_id,
NcCallbackResult result_callback);
// Sends a Payload to a remote endpoint.
//
// instance - The returned instance by NcOpenService.
// endpoint_ids_size - The endpoint number to receive the payload.
// endpoint_ids - The endpoint ID array.
// payload - the payload will be sent.
// result_callback - The result of the API operation.
NC_API void NcSendPayload(NC_INSTANCE instance, size_t endpoint_ids_size,
const int* endpoint_ids, const NC_PAYLOAD* payload,
NcCallbackResult result_callback);
// Cancels a Payload currently in-flight to or from remote endpoint(s).
//
// instance - The Nearby Connections instance is called by NcSendPayload.
// payload_id - The payload ID of payload to cancel.
// result_callback - The result of the API operation.
NC_API void NcCancelPayload(NC_INSTANCE instance, NC_PAYLOAD_ID payload_id,
NcCallbackResult result_callback);
// Disconnects from a remote endpoint.
//
// instance - The returned instance by NcOpenService.
// endpoint_id - The endpoint ID of remote device to disconnect.
// result_callback - The result of the API operation.
NC_API void NcDisconnectFromEndpoint(NC_INSTANCE instance, int endpoint_id,
NcCallbackResult result_callback);
// Disconnects from, and removes all traces of, all connected and/or
// discovered endpoints.
//
// instance - The returned instance by NcOpenService.
// result_callback - The result of the API operation.
NC_API void NcStopAllEndpoints(NC_INSTANCE instance,
NcCallbackResult result_callback);
// Sends a request to initiate connection bandwidth upgrade.
//
// instance - The returned instance by NcOpenService.
// endpoint_id - Requested to upgrade on the remote device with the endpoint ID.
// result_callback - The result of the API operation.
NC_API void NcInitiateBandwidthUpgrade(NC_INSTANCE instance, int endpoint_id,
NcCallbackResult result_callback);
// Gets the local endpoint generated by Nearby Connections.
NC_API int NcGetLocalEndpointId(NC_INSTANCE instance);
// Enable/Disable BLE V2 advertising. The method should be deprecated after
// BLE V1 deprecated.
NC_API void NcEnableBleV2(NC_INSTANCE instance, bool enable,
NcCallbackResult result_callback);
// Sets the custom save path for Nearby Connections.
NC_API void NcSetCustomSavePath(NC_INSTANCE instance, const NC_DATA* save_path,
NcCallbackResult result_callback);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_C_NC_H_
+39
View File
@@ -0,0 +1,39 @@
// Copyright 2024 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_NC_DEF_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_C_NC_DEF_H_
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
#ifdef _WIN32 // These storage class specifiers only matter to win32 dll
// builds.
#ifdef NC_DLL
// If we're building the core, we're exporting.
#define NC_API __declspec(dllexport)
#else // !NC_DLL
// If we're not building the core, we're importing.
#define NC_API __declspec(dllimport)
#endif // NC_DLL
#else // !_WIN32
#define NC_API // We're not building a win32 dll, leave the source unchanged.
#endif // _WIN32
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_C_NC_DEF_H_
+307
View File
@@ -0,0 +1,307 @@
// Copyright 2024 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_NC_TYPES_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_C_NC_TYPES_H_
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
typedef void* NC_INSTANCE;
typedef int64_t NC_PAYLOAD_ID;
// NC_DATA is used to define a byte array. Its last byte is not zero.
typedef struct NC_DATA {
int64_t size;
char* data;
} NC_DATA, *PNC_DATA;
// Supported mediums by Nearby Connections.
typedef enum NC_MEDIUM {
NC_MEDIUM_UNKNOWN = 0,
NC_MEDIUM_MDNS = 1, // deprecated
NC_MEDIUM_BLUETOOTH = 2,
NC_MEDIUM_WIFI_HOTSPOT = 3,
NC_MEDIUM_BLE = 4,
NC_MEDIUM_WIFI_LAN = 5,
NC_MEDIUM_WIFI_AWARE = 6,
NC_MEDIUM_NFC = 7,
NC_MEDIUM_WIFI_DIRECT = 8,
NC_MEDIUM_WEB_RTC = 9,
NC_MEDIUM_BLE_L2CAP = 10,
NC_MEDIUM_USB = 11,
NC_MEDIUM_MAX = 12
} NC_MEDIUM;
typedef enum NC_CONNECTION_TYPE {
NC_CONNECTION_TYPE_NONE = 0,
NC_CONNECTION_TYPE_POINT_TO_POINT = 1,
} NC_CONNECTION_TYPE;
typedef enum NC_TOPOLOGY_TYPE {
NC_TOPOLOGY_TYPE_UNKNOWN = 0,
NC_TOPOLOGY_TYPE_ONE_TO_ONE = 1,
NC_TOPOLOGY_TYPE_ONE_TO_MANY = 2,
NC_TOPOLOGY_TYPE_MANY_TO_MANY = 3,
} NC_TOPOLOGY_TYPE;
typedef enum NC_STRATEGY_TYPE {
NC_STRATEGY_TYPE_NONE,
NC_STRATEGY_TYPE_P2P_CLUSTER,
NC_STRATEGY_TYPE_P2P_STAR,
NC_STRATEGY_TYPE_P2P_POINT_TO_POINT
} NC_STRATEGY_TYPE;
typedef enum NC_DISTANCE_INFO {
NC_DISTANCE_INFO_UNKNOWN = 1,
NC_DISTANCE_INFO_VERYCLOSE = 2,
NC_DISTANCE_INFO_CLOSE = 3,
NC_DISTANCE_INFO_FAR = 4,
} NC_DISTANCE_INFO;
typedef enum NC_STATUS {
NC_STATUS_SUCCESS,
NC_STATUS_ERROR,
NC_STATUS_OUTOFORDERAPICALL,
NC_STATUS_ALREADYHAVEACTIVESTRATEGY,
NC_STATUS_ALREADYADVERTISING,
NC_STATUS_ALREADYDISCOVERING,
NC_STATUS_ALREADYLISTENING,
NC_STATUS_ENDPOINTIOERROR,
NC_STATUS_ENDPOINTUNKNOWN,
NC_STATUS_CONNECTIONREJECTED,
NC_STATUS_ALREADYCONNECTEDTOENDPOINT,
NC_STATUS_NOTCONNECTEDTOENDPOINT,
NC_STATUS_BLUETOOTHERROR,
NC_STATUS_BLEERROR,
NC_STATUS_WIFILANERROR,
NC_STATUS_PAYLOADUNKNOWN,
NC_STATUS_RESET,
NC_STATUS_TIMEOUT,
NC_STATUS_UNKNOWN,
NC_STATUS_NEXTVALUE,
} NC_STATUS;
typedef enum NC_PAYLOAD_TYPE {
NC_PAYLOAD_TYPE_UNKNOWN = 0,
NC_PAYLOAD_TYPE_BYTES = 1,
NC_PAYLOAD_TYPE_STREAM = 2,
NC_PAYLOAD_TYPE_FILE = 3
} NC_PAYLOAD_TYPE;
typedef enum NC_PAYLOAD_DIRECTION {
NC_PAYLOAD_DIRECTION_UNKNOWN = 0,
NC_PAYLOAD_DIRECTION_INCOMING = 1,
NC_PAYLOAD_DIRECTION_OUTGOING = 2,
} NC_PAYLOAD_DIRECTION;
typedef enum NC_IO_EXCEPTION {
NC_IO_EXCEPTION_FAILED = -1,
NC_IO_EXCEPTION_SUCCESS = 0,
NC_IO_EXCEPTION_IO = 1,
NC_IO_EXCEPTION_INTERRUPTED = 2,
NC_IO_EXCEPTION_INVALID_PROTOCOL_BUFFER = 3,
NC_IO_EXCEPTION_EXECUTION = 4,
NC_IO_EXCEPTION_TIMEOUT = 5,
NC_IO_EXCEPTION_ILLEGALCHARACTERS = 6,
} NC_IO_EXCEPTION;
// Defines struct types in Nearby connections.
typedef struct NC_STRATEGY {
NC_STRATEGY_TYPE type;
NC_CONNECTION_TYPE connection_type;
NC_TOPOLOGY_TYPE topology_type;
} NC_STRATEGY;
typedef struct NC_COMMON_OPTIONS {
NC_STRATEGY strategy;
bool allowed_mediums[NC_MEDIUM_MAX];
} NC_COMMON_OPTIONS;
typedef struct NC_ADVERTISING_OPTIONS {
NC_COMMON_OPTIONS common_options;
bool auto_upgrade_bandwidth;
bool enforce_topology_constraints;
bool enable_bluetooth_listening;
bool enable_webrtc_listening;
bool low_power;
bool is_out_of_band_connection;
NC_DATA fast_advertisement_service_uuid;
NC_DATA device_info;
} NC_ADVERTISING_OPTIONS, *PNC_ADVERTISING_OPTIONS;
typedef struct NC_CONNECTION_OPTIONS {
NC_COMMON_OPTIONS common_options;
bool auto_upgrade_bandwidth;
bool enforce_topology_constraints;
bool low_power;
bool is_out_of_band_connection;
NC_DATA remote_bluetooth_mac_address;
NC_DATA fast_advertisement_service_uuid;
int keep_alive_interval_millis;
int keep_alive_timeout_millis;
} NC_CONNECTION_OPTIONS, *PNC_CONNECTION_OPTIONS;
typedef struct NC_DISCOVERY_OPTIONS {
NC_COMMON_OPTIONS common_options;
bool auto_upgrade_bandwidth;
bool enforce_topology_constraints;
// Whether this is intended to be used in conjunction with InjectEndpoint().
bool is_out_of_band_connection;
NC_DATA fast_advertisement_service_uuid;
bool low_power;
} NC_DISCOVERY_OPTIONS, *PNC_DISCOVERY_OPTIONS;
typedef struct NC_CONNECTION_RESPONSE_INFO {
NC_DATA remote_endpoint_info;
NC_DATA authentication_token;
NC_DATA raw_authentication_token;
bool is_incoming_connection;
bool is_connection_verified;
} NC_CONNECTION_RESPONSE_INFO, *PNC_CONNECTION_RESPONSE_INFO;
// Defines callbacks in Nearby Connections.
typedef void (*NcCallbackResult)(NC_STATUS status);
typedef void (*NcCallbackConnectionInitiated)(
NC_INSTANCE instance, int endpoint_id,
const NC_CONNECTION_RESPONSE_INFO* info);
typedef void (*NcCallbackConnectionAccepted)(NC_INSTANCE instance,
int endpoint_id);
typedef void (*NcCallbackConnectionRejected)(NC_INSTANCE instance,
int endpoint_id, NC_STATUS status);
typedef void (*NcCallbackConnectionDisconnected)(NC_INSTANCE instance,
int endpoint_id);
typedef void (*NcCallbackConnectionBandwidthChanged)(NC_INSTANCE instance,
int endpoint_id,
NC_MEDIUM medium);
typedef struct NC_CONNECTION_REQUEST_INFO {
NC_DATA endpoint_info;
NcCallbackConnectionInitiated initiated_callback;
NcCallbackConnectionAccepted accepted_callback;
NcCallbackConnectionRejected rejected_callback;
NcCallbackConnectionDisconnected disconnected_callback;
NcCallbackConnectionBandwidthChanged bandwidth_changed_callback;
} NC_CONNECTION_REQUEST_INFO;
typedef void (*NcCallbackDiscoveryEndpointFound)(NC_INSTANCE instance,
int endpoint_id,
const NC_DATA* endpoint_info,
const NC_DATA* service_id);
typedef void (*NcCallbackDiscoveryEndpointLost)(NC_INSTANCE instance,
int endpoint_id);
typedef void (*NcCallbackDiscoveryEndpointDistanceChanged)(
NC_INSTANCE instance, int endpoint_id, NC_DISTANCE_INFO info);
typedef struct NC_DISCOVERY_LISTENER {
NcCallbackDiscoveryEndpointFound endpoint_found_callback;
NcCallbackDiscoveryEndpointLost endpoint_lost_callback;
NcCallbackDiscoveryEndpointDistanceChanged endpoint_distance_changed_callback;
} NC_DISCOVERY_LISTENER;
typedef struct NC_BYTES_PAYLOAD {
NC_DATA content;
} NC_BYTES_PAYLOAD;
typedef int (*NcCallbackStreamRead)(NC_INSTANCE stream, char* buffer,
int64_t size);
typedef int (*NcCallbackStreamClose)(NC_INSTANCE stream);
typedef int (*NcCallbackStreamSkip)(NC_INSTANCE stream, int64_t skip);
typedef struct NC_STREAM_PAYLOAD {
NC_INSTANCE stream;
NcCallbackStreamRead read_callback;
NcCallbackStreamSkip skip_callback;
NcCallbackStreamClose close_callback;
} NC_STREAM_PAYLOAD;
typedef struct NC_FILE_PAYLOAD {
int64_t offset;
char* file_name;
char* parent_folder;
} NC_FILE_PAYLOAD;
typedef union NC_PAYLOAD_CONTENT {
NC_BYTES_PAYLOAD bytes;
NC_STREAM_PAYLOAD stream;
NC_FILE_PAYLOAD file;
} NC_PAYLOAD_CONTENT;
typedef struct NC_PAYLOAD {
NC_PAYLOAD_ID id;
NC_PAYLOAD_TYPE type;
NC_PAYLOAD_DIRECTION direction;
NC_PAYLOAD_CONTENT content;
} NC_PAYLOAD;
typedef enum NC_PAYLOAD_PROGRESS_INFO_STATUS {
NC_PAYLOAD_PROGRESS_INFO_STATUS_SUCCESS,
NC_PAYLOAD_PROGRESS_INFO_STATUS_FAILURE,
NC_PAYLOAD_PROGRESS_INFO_STATUS_INPROGRESS,
NC_PAYLOAD_PROGRESS_INFO_STATUS_CANCELED,
} NC_PAYLOAD_PROGRESS_INFO_STATUS;
typedef struct NC_PAYLOAD_PROGRESS_INFO {
NC_PAYLOAD_ID id;
NC_PAYLOAD_PROGRESS_INFO_STATUS status;
size_t total_bytes;
size_t bytes_transferred;
} NC_PAYLOAD_PROGRESS_INFO;
typedef void (*NcCallbackPayloadReceived)(NC_INSTANCE instance, int endpoint_id,
const NC_PAYLOAD* payload);
typedef void (*NcCallbackPayloadProgressUpdated)(
NC_INSTANCE instance, int endpoint_id,
const NC_PAYLOAD_PROGRESS_INFO* info);
typedef struct NC_PAYLOAD_LISTENER {
NcCallbackPayloadReceived received_callback;
NcCallbackPayloadProgressUpdated progress_updated_callback;
} NC_PAYLOAD_LISTENER;
typedef struct NC_OUT_OF_BAND_CONNECTION_METADATA {
// Medium to use for the out-of-band connection.
NC_MEDIUM 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.
int 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.
NC_DATA endpoint_info;
// Used for Bluetooth connections.
NC_DATA remote_bluetooth_mac_address;
} NC_OUT_OF_BAND_CONNECTION_METADATA, *PNC_OUT_OF_BAND_CONNECTION_METADATA;
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_C_NC_TYPES_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
+4
View File
@@ -52,6 +52,10 @@ struct ConnectionOptions : public OptionsBase {
int keep_alive_interval_millis = 0;
int keep_alive_timeout_millis = 0;
// If true, only use WiFi Hotspot for connection when Wifi LAN is not
// connected.
bool non_disruptive_hotspot_mode = false;
std::vector<Medium> GetMediums() const;
ConnectionInfo connection_info;
};
+101 -63
View File
@@ -14,6 +14,7 @@
#include "connections/core.h"
#include <cstdint>
#include <string>
#include <utility>
#include <vector>
@@ -73,7 +74,7 @@ Core::~Core() {
CountDownLatch latch(1);
router_->StopAllEndpoints(&client_, [&latch](Status) { latch.CountDown(); });
if (!latch.Await(kWaitForDisconnect).result()) {
NEARBY_LOG(FATAL, "Unable to shutdown");
NEARBY_LOGS(FATAL) << "Unable to shutdown";
}
}
@@ -102,8 +103,8 @@ void Core::StartDiscovery(absl::string_view service_id,
CheckServiceId(service_id);
CHECK(discovery_options.strategy.IsValid());
router_->StartDiscovery(&client_, service_id, discovery_options, listener,
std::move(callback));
router_->StartDiscovery(&client_, service_id, discovery_options,
std::move(listener), std::move(callback));
}
void Core::InjectEndpoint(absl::string_view service_id,
@@ -121,7 +122,10 @@ void Core::RequestConnection(absl::string_view endpoint_id,
ConnectionRequestInfo info,
ConnectionOptions connection_options,
ResultCallback callback) {
CHECK(!endpoint_id.empty());
if (endpoint_id.empty()) {
callback(Status{.value = Status::kEndpointUnknown});
return;
}
// Assign the default from feature flags for the keep-alive frame interval and
// timeout values if client don't mind them or has the unexpected ones.
@@ -129,14 +133,13 @@ void Core::RequestConnection(absl::string_view endpoint_id,
connection_options.keep_alive_timeout_millis == 0 ||
connection_options.keep_alive_interval_millis >=
connection_options.keep_alive_timeout_millis) {
NEARBY_LOG(
WARNING,
"Client request connection with keep-alive frame as interval=%d, "
"timeout=%d, which is un-expected. Change to default.",
connection_options.keep_alive_interval_millis,
connection_options.keep_alive_timeout_millis);
connection_options.keep_alive_interval_millis =
FeatureFlags::GetInstance().GetFlags().keep_alive_interval_millis;
NEARBY_LOGS(WARNING)
<< "Client request connection with keep-alive frame as interval="
<< connection_options.keep_alive_interval_millis
<< ", timeout=" << connection_options.keep_alive_timeout_millis
<< ", which is un-expected. Change to default.",
connection_options.keep_alive_interval_millis =
FeatureFlags::GetInstance().GetFlags().keep_alive_interval_millis;
connection_options.keep_alive_timeout_millis =
FeatureFlags::GetInstance().GetFlags().keep_alive_timeout_millis;
}
@@ -147,7 +150,10 @@ void Core::RequestConnection(absl::string_view endpoint_id,
void Core::AcceptConnection(absl::string_view endpoint_id,
PayloadListener listener, ResultCallback callback) {
CHECK(!endpoint_id.empty());
if (endpoint_id.empty()) {
callback(Status{.value = Status::kEndpointUnknown});
return;
}
router_->AcceptConnection(&client_, endpoint_id, std::move(listener),
std::move(callback));
@@ -155,7 +161,10 @@ void Core::AcceptConnection(absl::string_view endpoint_id,
void Core::RejectConnection(absl::string_view endpoint_id,
ResultCallback callback) {
CHECK(!endpoint_id.empty());
if (endpoint_id.empty()) {
callback(Status{.value = Status::kEndpointUnknown});
return;
}
router_->RejectConnection(&client_, endpoint_id, std::move(callback));
}
@@ -182,7 +191,10 @@ void Core::CancelPayload(std::int64_t payload_id, ResultCallback callback) {
void Core::DisconnectFromEndpoint(absl::string_view endpoint_id,
ResultCallback callback) {
CHECK(!endpoint_id.empty());
if (endpoint_id.empty()) {
callback(Status{.value = Status::kEndpointUnknown});
return;
}
router_->DisconnectFromEndpoint(&client_, endpoint_id, std::move(callback));
}
@@ -258,21 +270,26 @@ void Core::StartAdvertisingV3(absl::string_view service_id,
CheckServiceId(service_id);
CHECK(advertising_options.strategy.IsValid());
AdvertisingOptions old_advertising_options = {
{
advertising_options.strategy,
advertising_options.advertising_mediums,
},
advertising_options.auto_upgrade_bandwidth,
advertising_options.enforce_topology_constraints,
advertising_options.power_level == PowerLevel::kLowPower, // low_power
advertising_options.enable_bluetooth_listening,
advertising_options.advertising_mediums.web_rtc,
false, // is_out_of_band_connection
advertising_options.fast_advertisement_service_uuid,
"" // device_info
};
// TODO(b/291295755): Refactor deeper to use v3 options throughout.
AdvertisingOptions old_advertising_options = {
/*OptionsBase=*/
{
/*strategy=*/advertising_options.strategy,
/*allowed=*/advertising_options.advertising_mediums,
},
/*auto_upgrade_bandwidth=*/advertising_options.auto_upgrade_bandwidth,
/*enforce_topology_constraints=*/
advertising_options.enforce_topology_constraints,
/*low_power=*/advertising_options.power_level == PowerLevel::kLowPower,
/*enable_bluetooth_listening=*/
advertising_options.enable_bluetooth_listening,
/*enable_webrtc_listening=*/
advertising_options.advertising_mediums.web_rtc,
/*use_stable_endpoint_id=*/advertising_options.use_stable_endpoint_id,
/*is_out_of_band_connection=*/false,
/*fast_advertisement_service_uuid=*/
advertising_options.fast_advertisement_service_uuid,
/*device_info=*/""};
router_->StartAdvertising(&client_, service_id, old_advertising_options,
old_info, std::move(callback));
}
@@ -302,23 +319,26 @@ void Core::StartDiscoveryV3(absl::string_view service_id,
ResultCallback callback) {
DiscoveryListener old_listener = {
.endpoint_found_cb =
[&listener](const std::string& endpoint_id,
const ByteArray& endpoint_info,
const std::string& service_id) {
[endpoint_found_cb = std::move(listener.endpoint_found_cb)](
const std::string& endpoint_id, const ByteArray& endpoint_info,
const std::string& service_id) mutable {
auto remote_device = v3::ConnectionsDevice(
endpoint_id, endpoint_info.AsStringView(), {});
listener.endpoint_found_cb(remote_device, service_id);
endpoint_found_cb(remote_device, service_id);
},
.endpoint_lost_cb =
[&listener](const std::string& endpoint_id) {
[endpoint_lost_cb = std::move(listener.endpoint_lost_cb)](
const std::string& endpoint_id) mutable {
auto remote_device = v3::ConnectionsDevice(endpoint_id, "", {});
listener.endpoint_lost_cb(remote_device);
endpoint_lost_cb(remote_device);
},
.endpoint_distance_changed_cb =
[&listener](const std::string& endpoint_id,
DistanceInfo distance_info) {
[endpoint_distance_changed_cb =
std::move(listener.endpoint_distance_changed_cb)](
const std::string& endpoint_id,
DistanceInfo distance_info) mutable {
auto remote = v3::ConnectionsDevice(endpoint_id, "", {});
listener.endpoint_distance_changed_cb(remote, distance_info);
endpoint_distance_changed_cb(remote, distance_info);
},
};
DiscoveryOptions old_discovery_options = {
@@ -333,7 +353,7 @@ void Core::StartDiscoveryV3(absl::string_view service_id,
discovery_options.power_level == PowerLevel::kLowPower,
};
// TODO(b/291295755): Deeper refactor to use v3 options throughout.
StartDiscovery(service_id, old_discovery_options, old_listener,
StartDiscovery(service_id, old_discovery_options, std::move(old_listener),
std::move(callback));
}
@@ -373,12 +393,11 @@ void Core::RequestConnectionV3(const NearbyDevice& local_device,
connection_options.keep_alive_timeout_millis == 0 ||
connection_options.keep_alive_interval_millis >=
connection_options.keep_alive_timeout_millis) {
NEARBY_LOG(
WARNING,
"Client request connection with keep-alive frame as interval=%d, "
"timeout=%d, which is un-expected. Change to default.",
connection_options.keep_alive_interval_millis,
connection_options.keep_alive_timeout_millis);
NEARBY_LOGS(WARNING)
<< "Client request connection with keep-alive frame as interval="
<< connection_options.keep_alive_interval_millis
<< ", timeout=" << connection_options.keep_alive_timeout_millis
<< ", which is un-expected. Change to default.";
connection_options.keep_alive_interval_millis =
FeatureFlags::GetInstance().GetFlags().keep_alive_interval_millis;
connection_options.keep_alive_timeout_millis =
@@ -396,7 +415,10 @@ void Core::RequestConnectionV3(const NearbyDevice& remote_device,
.local_device = const_cast<NearbyDevice&>(*(client_.GetLocalDevice())),
.listener = std::move(connection_cb),
};
CHECK(!remote_device.GetEndpointId().empty());
if (remote_device.GetEndpointId().empty()) {
result_cb(Status{.value = Status::kEndpointUnknown});
return;
}
// Assign the default from feature flags for the keep-alive frame interval and
// timeout values if client don't mind them or has the unexpected ones.
@@ -404,12 +426,11 @@ void Core::RequestConnectionV3(const NearbyDevice& remote_device,
connection_options.keep_alive_timeout_millis == 0 ||
connection_options.keep_alive_interval_millis >=
connection_options.keep_alive_timeout_millis) {
NEARBY_LOG(
WARNING,
"Client request connection with keep-alive frame as interval=%d, "
"timeout=%d, which is un-expected. Change to default.",
connection_options.keep_alive_interval_millis,
connection_options.keep_alive_timeout_millis);
NEARBY_LOGS(WARNING)
<< "Client request connection with keep-alive frame as interval="
<< connection_options.keep_alive_interval_millis
<< ", timeout=" << connection_options.keep_alive_timeout_millis
<< ", which is un-expected. Change to default.";
connection_options.keep_alive_interval_millis =
FeatureFlags::GetInstance().GetFlags().keep_alive_interval_millis;
connection_options.keep_alive_timeout_millis =
@@ -422,7 +443,10 @@ void Core::RequestConnectionV3(const NearbyDevice& remote_device,
void Core::AcceptConnectionV3(const NearbyDevice& remote_device,
v3::PayloadListener listener_cb,
ResultCallback result_cb) {
CHECK(!remote_device.GetEndpointId().empty());
if (remote_device.GetEndpointId().empty()) {
result_cb(Status{.value = Status::kEndpointUnknown});
return;
}
router_->AcceptConnectionV3(&client_, remote_device, std::move(listener_cb),
std::move(result_cb));
@@ -430,7 +454,10 @@ void Core::AcceptConnectionV3(const NearbyDevice& remote_device,
void Core::RejectConnectionV3(const NearbyDevice& remote_device,
ResultCallback result_cb) {
CHECK(!remote_device.GetEndpointId().empty());
if (remote_device.GetEndpointId().empty()) {
result_cb(Status{.value = Status::kEndpointUnknown});
return;
}
router_->RejectConnectionV3(&client_, remote_device, std::move(result_cb));
}
@@ -438,7 +465,10 @@ void Core::RejectConnectionV3(const NearbyDevice& remote_device,
void Core::SendPayloadV3(const NearbyDevice& remote_device, Payload payload,
ResultCallback result_cb) {
CHECK(payload.GetType() != PayloadType::kUnknown);
CHECK(!remote_device.GetEndpointId().empty());
if (remote_device.GetEndpointId().empty()) {
result_cb(Status{.value = Status::kEndpointUnknown});
return;
}
router_->SendPayloadV3(&client_, remote_device, std::move(payload),
std::move(result_cb));
@@ -454,7 +484,10 @@ void Core::CancelPayloadV3(const NearbyDevice& remote_device,
void Core::DisconnectFromDeviceV3(const NearbyDevice& remote_device,
ResultCallback result_cb) {
CHECK(!remote_device.GetEndpointId().empty());
if (remote_device.GetEndpointId().empty()) {
result_cb(Status{.value = Status::kEndpointUnknown});
return;
}
router_->DisconnectFromDeviceV3(&client_, remote_device,
std::move(result_cb));
@@ -475,19 +508,24 @@ void Core::UpdateAdvertisingOptionsV3(
ResultCallback result_cb) {
// TODO(b/291295755): Deeper refactor to use new advertising options.
AdvertisingOptions old_advertising_options = {
/*OptionsBase=*/
{
advertising_options.strategy,
advertising_options.advertising_mediums,
/*strategy=*/advertising_options.strategy,
/*allowed=*/advertising_options.advertising_mediums,
},
advertising_options.auto_upgrade_bandwidth,
/*auto_upgrade_bandwidth=*/advertising_options.auto_upgrade_bandwidth,
/*enforce_topology_constraints=*/
advertising_options.enforce_topology_constraints,
advertising_options.power_level == PowerLevel::kLowPower, // low_power
/*low_power=*/advertising_options.power_level == PowerLevel::kLowPower,
/*enable_bluetooth_listening=*/
advertising_options.enable_bluetooth_listening,
/*enable_webrtc_listening=*/
advertising_options.advertising_mediums.web_rtc,
false, // is_out_of_band_connection
/*use_stable_endpoint_id=*/advertising_options.use_stable_endpoint_id,
/*is_out_of_band_connection=*/false,
/*fast_advertisement_service_uuid=*/
advertising_options.fast_advertisement_service_uuid,
"" // device_info
};
/*device_info=*/""};
router_->UpdateAdvertisingOptionsV3(
&client_, service_id, old_advertising_options, std::move(result_cb));
}
+7 -1
View File
@@ -15,21 +15,27 @@
#ifndef CORE_CORE_H_
#define CORE_CORE_H_
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "connections/advertising_options.h"
#include "connections/connection_options.h"
#include "connections/discovery_options.h"
#include "connections/implementation/client_proxy.h"
#include "connections/implementation/service_controller.h"
#include "connections/implementation/service_controller_router.h"
#include "connections/listeners.h"
#include "connections/medium_selector.h"
#include "connections/out_of_band_connection_metadata.h"
#include "connections/params.h"
#include "connections/payload.h"
#include "connections/v3/advertising_options.h"
#include "connections/v3/connection_listening_options.h"
#include "connections/v3/connections_device_provider.h"
#include "connections/v3/discovery_options.h"
#include "connections/v3/listeners.h"
#include "connections/v3/listening_result.h"
+117 -57
View File
@@ -49,10 +49,10 @@ class FakeNearbyDevice : public NearbyDevice {
NearbyDevice::Type GetType() const override {
return NearbyDevice::Type::kUnknownDevice;
}
MOCK_METHOD(std::string, GetEndpointId, (), (const override));
MOCK_METHOD(std::string, GetEndpointId, (), (const, override));
MOCK_METHOD(std::vector<ConnectionInfoVariant>, GetConnectionInfos, (),
(const override));
MOCK_METHOD(std::string, ToProtoBytes, (), (const override));
(const, override));
MOCK_METHOD(std::string, ToProtoBytes, (), (const, override));
};
class FakeNearbyDeviceProvider : public NearbyDeviceProvider {
@@ -64,70 +64,130 @@ class FakeNearbyDeviceProvider : public NearbyDeviceProvider {
};
TEST(CoreTest, ConstructorDestructorWorks) {
MockServiceControllerRouter mock;
MockServiceControllerRouter mock_controller;
// Called when Core is destroyed.
EXPECT_CALL(mock, StopAllEndpoints)
EXPECT_CALL(mock_controller, StopAllEndpoints)
.WillOnce([&](ClientProxy* client, ResultCallback callback) {
callback({Status::kSuccess});
});
Core core{&mock};
Core core{&mock_controller};
}
TEST(CoreTest, DestructorReportsFatalFailure) {
ASSERT_DEATH(
{
MockServiceControllerRouter mock;
MockServiceControllerRouter mock_controller;
// Never invoke the result callback so ~Core will time out.
EXPECT_CALL(mock, StopAllEndpoints);
Core core{&mock};
EXPECT_CALL(mock_controller, StopAllEndpoints);
Core core{&mock_controller};
},
"Unable to shutdown");
}
TEST(CoreTest, RequestConnectionCallsScRouter) {
MockServiceControllerRouter mock;
MockServiceControllerRouter mock_controller;
// Called when Core is destroyed.
EXPECT_CALL(mock, StopAllEndpoints)
EXPECT_CALL(mock_controller, StopAllEndpoints)
.WillOnce([&](ClientProxy* client, ResultCallback callback) {
callback({Status::kSuccess});
});
EXPECT_CALL(mock, RequestConnection);
Core core{&mock};
EXPECT_CALL(mock_controller, RequestConnection);
Core core{&mock_controller};
core.RequestConnection("TEST", {}, {}, {});
}
TEST(CoreTest, AcceptConnectionCallsScRouter) {
MockServiceControllerRouter mock;
TEST(CoreTest, RequestConnectionFailsWithEmptyEndpoint) {
MockServiceControllerRouter mock_controller;
// Called when Core is destroyed.
EXPECT_CALL(mock, StopAllEndpoints)
EXPECT_CALL(mock_controller, StopAllEndpoints)
.WillOnce([&](ClientProxy* client, ResultCallback callback) {
callback({Status::kSuccess});
});
EXPECT_CALL(mock, AcceptConnection);
Core core{&mock};
Status final_status;
Core core{&mock_controller};
core.RequestConnection(
"", {}, {}, [&](Status result_status) { final_status = result_status; });
EXPECT_EQ(final_status.value, Status::kEndpointUnknown);
}
TEST(CoreTest, AcceptConnectionCallsScRouter) {
MockServiceControllerRouter mock_controller;
// Called when Core is destroyed.
EXPECT_CALL(mock_controller, StopAllEndpoints)
.WillOnce([&](ClientProxy* client, ResultCallback callback) {
callback({Status::kSuccess});
});
EXPECT_CALL(mock_controller, AcceptConnection);
Core core{&mock_controller};
core.AcceptConnection("TEST", {}, {});
}
TEST(CoreTest, SendPayloadCallsScRouter) {
MockServiceControllerRouter mock;
TEST(CoreTest, AcceptConnectionFailsWithEmptyEndpoint) {
MockServiceControllerRouter mock_controller;
// Called when Core is destroyed.
EXPECT_CALL(mock, StopAllEndpoints)
EXPECT_CALL(mock_controller, StopAllEndpoints)
.WillOnce([&](ClientProxy* client, ResultCallback callback) {
callback({Status::kSuccess});
});
EXPECT_CALL(mock, SendPayload);
Core core{&mock};
Status final_status;
Core core{&mock_controller};
core.AcceptConnection(
"", {}, [&](Status result_status) { final_status = result_status; });
EXPECT_EQ(final_status.value, Status::kEndpointUnknown);
}
TEST(CoreTest, RejectConnectionFailsWithEmptyEndpoint) {
MockServiceControllerRouter mock_controller;
// Called when Core is destroyed.
EXPECT_CALL(mock_controller, StopAllEndpoints)
.WillOnce([&](ClientProxy* client, ResultCallback callback) {
callback({Status::kSuccess});
});
Status final_status;
Core core{&mock_controller};
core.RejectConnection(
"", [&](Status result_status) { final_status = result_status; });
EXPECT_EQ(final_status.value, Status::kEndpointUnknown);
}
TEST(CoreTest, DisconnectFailsWithEmptyEndpoint) {
MockServiceControllerRouter mock_controller;
// Called when Core is destroyed.
EXPECT_CALL(mock_controller, StopAllEndpoints)
.WillOnce([&](ClientProxy* client, ResultCallback callback) {
callback({Status::kSuccess});
});
Status final_status;
Core core{&mock_controller};
core.DisconnectFromEndpoint(
"", [&](Status result_status) { final_status = result_status; });
EXPECT_EQ(final_status.value, Status::kEndpointUnknown);
}
TEST(CoreTest, SendPayloadCallsScRouter) {
MockServiceControllerRouter mock_controller;
// Called when Core is destroyed.
EXPECT_CALL(mock_controller, StopAllEndpoints)
.WillOnce([&](ClientProxy* client, ResultCallback callback) {
callback({Status::kSuccess});
});
EXPECT_CALL(mock_controller, SendPayload);
Core core{&mock_controller};
core.SendPayload({"TEST"}, Payload(ByteArray("Hello world")), {});
}
TEST(CoreV3Test, TestAdvertisingOptionsConversionWorks) {
MockServiceControllerRouter mock;
MockServiceControllerRouter mock_controller;
// Called when Core is destroyed.
EXPECT_CALL(mock, StopAllEndpoints)
EXPECT_CALL(mock_controller, StopAllEndpoints)
.WillOnce([&](ClientProxy* client, ResultCallback callback) {
callback({Status::kSuccess});
});
EXPECT_CALL(mock, StartAdvertising)
EXPECT_CALL(mock_controller, StartAdvertising)
.WillOnce([](ClientProxy*, absl::string_view,
const AdvertisingOptions& options,
const ConnectionRequestInfo& info, ResultCallback) {
@@ -137,7 +197,7 @@ TEST(CoreV3Test, TestAdvertisingOptionsConversionWorks) {
EXPECT_FALSE(options.auto_upgrade_bandwidth);
EXPECT_EQ(options.fast_advertisement_service_uuid, "NearbyConnections");
});
Core core{&mock};
Core core{&mock_controller};
v3::AdvertisingOptions advertising_options = {
.strategy = Strategy::kP2pCluster,
.power_level = PowerLevel::kHighPower,
@@ -150,22 +210,22 @@ TEST(CoreV3Test, TestAdvertisingOptionsConversionWorks) {
}
TEST(CoreV3Test, TestDiscoveryOptionsConversionWorks) {
MockServiceControllerRouter mock;
MockServiceControllerRouter mock_controller;
// Called when Core is destroyed.
EXPECT_CALL(mock, StopAllEndpoints)
EXPECT_CALL(mock_controller, StopAllEndpoints)
.WillOnce([&](ClientProxy* client, ResultCallback callback) {
callback({Status::kSuccess});
});
EXPECT_CALL(mock, StartDiscovery)
EXPECT_CALL(mock_controller, StartDiscovery)
.WillOnce([](ClientProxy*, absl::string_view,
const DiscoveryOptions& options,
const DiscoveryListener& info, ResultCallback) {
const DiscoveryOptions& options, DiscoveryListener,
ResultCallback) {
EXPECT_EQ(options.strategy, Strategy::kP2pCluster);
EXPECT_FALSE(options.low_power);
EXPECT_TRUE(options.auto_upgrade_bandwidth);
EXPECT_EQ(options.fast_advertisement_service_uuid, "NearbyConnections");
});
Core core{&mock};
Core core{&mock_controller};
v3::DiscoveryOptions discovery_options = {
.strategy = Strategy::kP2pCluster,
.power_level = PowerLevel::kHighPower,
@@ -176,8 +236,8 @@ TEST(CoreV3Test, TestDiscoveryOptionsConversionWorks) {
}
TEST(CoreV3Test, TestCallbackWrapWorksStartAdvertisingV3FourArgs) {
MockServiceControllerRouter mock;
EXPECT_CALL(mock, StartAdvertising)
MockServiceControllerRouter mock_controller;
EXPECT_CALL(mock_controller, StartAdvertising)
.WillOnce([&](ClientProxy*, absl::string_view, const AdvertisingOptions&,
const ConnectionRequestInfo& info, const ResultCallback&) {
NEARBY_LOGS(INFO) << "StartAdvertising called";
@@ -189,12 +249,12 @@ TEST(CoreV3Test, TestCallbackWrapWorksStartAdvertisingV3FourArgs) {
info.listener.bandwidth_changed_cb("FAKE", Medium::BLUETOOTH);
info.listener.disconnected_cb("FAKE");
});
EXPECT_CALL(mock, StopAllEndpoints)
EXPECT_CALL(mock_controller, StopAllEndpoints)
.WillOnce([&](ClientProxy* client, ResultCallback callback) {
NEARBY_LOGS(INFO) << "StopAllEndpoints called";
callback({Status::kSuccess});
});
Core core{&mock};
Core core{&mock_controller};
CountDownLatch result_latch(2);
CountDownLatch bandwidth_changed_latch(1);
CountDownLatch disconnected_latch(1);
@@ -233,8 +293,8 @@ TEST(CoreV3Test, TestCallbackWrapWorksStartAdvertisingV3FourArgs) {
}
TEST(CoreV3Test, TestStartAdvertisingV3NonConnectionsDeviceProvider) {
MockServiceControllerRouter mock;
EXPECT_CALL(mock, StartAdvertising)
MockServiceControllerRouter mock_controller;
EXPECT_CALL(mock_controller, StartAdvertising)
.WillOnce([&](ClientProxy*, absl::string_view, const AdvertisingOptions&,
const ConnectionRequestInfo& info, ResultCallback) {
NEARBY_LOGS(INFO) << "StartAdvertising called";
@@ -246,12 +306,12 @@ TEST(CoreV3Test, TestStartAdvertisingV3NonConnectionsDeviceProvider) {
info.listener.bandwidth_changed_cb("FAKE", Medium::BLUETOOTH);
info.listener.disconnected_cb("FAKE");
});
EXPECT_CALL(mock, StopAllEndpoints)
EXPECT_CALL(mock_controller, StopAllEndpoints)
.WillOnce([&](ClientProxy* client, ResultCallback callback) {
NEARBY_LOGS(INFO) << "StopAllEndpoints called";
callback({Status::kSuccess});
});
Core core{&mock};
Core core{&mock_controller};
CountDownLatch result_latch(2);
CountDownLatch bandwidth_changed_latch(1);
CountDownLatch disconnected_latch(1);
@@ -292,8 +352,8 @@ TEST(CoreV3Test, TestStartAdvertisingV3NonConnectionsDeviceProvider) {
}
TEST(CoreV3Test, TestStartAdvertisingV3NonConnectionsDevice) {
MockServiceControllerRouter mock;
EXPECT_CALL(mock, StartAdvertising)
MockServiceControllerRouter mock_controller;
EXPECT_CALL(mock_controller, StartAdvertising)
.WillOnce([&](ClientProxy*, absl::string_view, const AdvertisingOptions&,
const ConnectionRequestInfo& info, const ResultCallback&) {
NEARBY_LOGS(INFO) << "StartAdvertising called";
@@ -305,12 +365,12 @@ TEST(CoreV3Test, TestStartAdvertisingV3NonConnectionsDevice) {
info.listener.bandwidth_changed_cb("FAKE", Medium::BLUETOOTH);
info.listener.disconnected_cb("FAKE");
});
EXPECT_CALL(mock, StopAllEndpoints)
EXPECT_CALL(mock_controller, StopAllEndpoints)
.WillOnce([&](ClientProxy* client, ResultCallback callback) {
NEARBY_LOGS(INFO) << "StopAllEndpoints called";
callback({Status::kSuccess});
});
Core core{&mock};
Core core{&mock_controller};
CountDownLatch result_latch(2);
CountDownLatch bandwidth_changed_latch(1);
CountDownLatch disconnected_latch(1);
@@ -350,8 +410,8 @@ TEST(CoreV3Test, TestStartAdvertisingV3NonConnectionsDevice) {
}
TEST(CoreV3Test, TestCallbackWrapWorksStartAdvertisingV3FiveArgs) {
MockServiceControllerRouter mock;
EXPECT_CALL(mock, StartAdvertising)
MockServiceControllerRouter mock_controller;
EXPECT_CALL(mock_controller, StartAdvertising)
.WillOnce([&](ClientProxy*, absl::string_view, const AdvertisingOptions&,
const ConnectionRequestInfo& info, const ResultCallback&) {
NEARBY_LOGS(INFO) << "StartAdvertising called";
@@ -363,12 +423,12 @@ TEST(CoreV3Test, TestCallbackWrapWorksStartAdvertisingV3FiveArgs) {
info.listener.bandwidth_changed_cb("FAKE", Medium::BLUETOOTH);
info.listener.disconnected_cb("FAKE");
});
EXPECT_CALL(mock, StopAllEndpoints)
EXPECT_CALL(mock_controller, StopAllEndpoints)
.WillOnce([&](ClientProxy* client, ResultCallback callback) {
NEARBY_LOGS(INFO) << "StopAllEndpoints called";
callback({Status::kSuccess});
});
Core core{&mock};
Core core{&mock_controller};
CountDownLatch result_latch(2);
CountDownLatch bandwidth_changed_latch(1);
CountDownLatch disconnected_latch(1);
@@ -408,24 +468,24 @@ TEST(CoreV3Test, TestCallbackWrapWorksStartAdvertisingV3FiveArgs) {
}
TEST(CoreV3Test, TestCallbackWrapWorksStartDiscoveryV3) {
MockServiceControllerRouter mock;
EXPECT_CALL(mock, StartDiscovery)
MockServiceControllerRouter mock_controller;
EXPECT_CALL(mock_controller, StartDiscovery)
.WillOnce([&](ClientProxy*, absl::string_view, const DiscoveryOptions&,
const DiscoveryListener& info, const ResultCallback&) {
DiscoveryListener listener, const ResultCallback&) {
// call all callbacks to make sure it all gets called correctly.
NEARBY_LOGS(INFO) << "StartDiscovery called";
info.endpoint_distance_changed_cb("FAKE", {});
info.endpoint_found_cb("FAKE", ByteArray(), "");
info.endpoint_lost_cb("FAKE");
listener.endpoint_distance_changed_cb("FAKE", {});
listener.endpoint_found_cb("FAKE", ByteArray(), "");
listener.endpoint_lost_cb("FAKE");
});
EXPECT_CALL(mock, StopAllEndpoints)
EXPECT_CALL(mock_controller, StopAllEndpoints)
.WillOnce([&](ClientProxy* client, ResultCallback callback) {
NEARBY_LOGS(INFO) << "StopAllEndpoints called";
callback({Status::kSuccess});
});
v3::DiscoveryOptions options;
options.strategy = Strategy::kP2pCluster;
Core core{&mock};
Core core{&mock_controller};
CountDownLatch endpoint_distance_latch(1);
CountDownLatch endpoint_found_latch(1);
CountDownLatch endpoint_lost_latch(1);
+35 -15
View File
@@ -12,49 +12,69 @@
# See the License for the specific language governing permissions and
# limitations under the License.
load("//third_party/lexan/build_defs:lexan.bzl", "lexan")
load("//third_party/cpptoolchains/windows_llvm/build_defs:windows.bzl", "windows")
package(default_visibility = ["//location/nearby:__subpackages__"])
licenses(["notice"])
# Build with --config=lexan
lexan.cc_windows_dll(
name = "nearby_connections_dart",
# Build with --config=windows
windows.cc_windows_dll(
name = "nc_windows_dart",
srcs = [
"core_adapter_dart.cc",
"nc_adapter_dart.cc",
"nearby_connections_client_state.cc",
],
hdrs = [
"core_adapter_dart.h",
"nc_adapter_dart.h",
"nc_adapter_def.h",
"nc_adapter_types.h",
"nearby_connections_client_state.h",
],
copts = ["-DNC_DART_DLL"],
tags = ["windows-dll"],
deps = [
"//connections:core",
"//connections/c",
"//connections/implementation/flags:connections_flags",
"//internal/flags:nearby_flags",
"//connections/c:nc_types",
"//connections/c:nc_windows",
"//internal/platform:types",
"//internal/platform/implementation/windows",
"//third_party/dart_lang/v2:dart_api_dl",
"@com_google_absl//absl/base:core_headers",
"@com_google_absl//absl/base:no_destructor",
"@com_google_absl//absl/container:flat_hash_map",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/strings:string_view",
"@com_google_absl//absl/synchronization",
],
)
objc_library(
name = "nearby_connections_objc",
srcs = [
"core_adapter_dart.cc",
"nc_adapter_dart.cc",
"nearby_connections_client_state.cc",
],
hdrs = [
"core_adapter_dart.h",
"nc_adapter_dart.h",
"nc_adapter_def.h",
"nc_adapter_types.h",
"nearby_connections_client_state.h",
],
deps = [
"//connections:core",
"//connections:core_types",
"//connections/c",
"//connections/c:nc",
"//connections/c:nc_types",
"//connections/implementation/flags:connections_flags",
"//internal/flags:nearby_flags",
"//internal/platform:base",
"//internal/platform:types",
"//internal/platform/implementation/apple", # buildcleaner: keep
"//third_party/dart_lang/v2:dart_api_dl",
"@com_google_absl//absl/base:core_headers",
"@com_google_absl//absl/base:no_destructor",
"@com_google_absl//absl/container:flat_hash_map",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/strings:string_view",
"@com_google_absl//absl/synchronization",
],
alwayslink = 1,
)
-709
View File
@@ -1,709 +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/dart/core_adapter_dart.h"
#include <cstdint>
#include <string>
#include "connections/core.h"
#include "connections/implementation/flags/nearby_connections_feature_flags.h"
#include "connections/payload.h"
#include "internal/flags/nearby_flags.h"
#include "internal/platform/count_down_latch.h"
#include "internal/platform/logging.h"
namespace nearby::windows {
static CountDownLatch *adapter_finished;
StrategyW GetStrategy(StrategyDart strategy) {
switch (strategy) {
case StrategyDart::P2P_CLUSTER:
return StrategyW::kP2pCluster;
case StrategyDart::P2P_POINT_TO_POINT:
return StrategyW::kP2pPointToPoint;
case StrategyDart::P2P_STAR:
return StrategyW::kP2pStar;
}
return StrategyW::kNone;
}
ByteArray ConvertBluetoothMacAddress(absl::string_view address) {
return ByteArray(address.data());
}
static Dart_Port port;
static DiscoveryListenerDart current_discovery_listener_dart;
static ConnectionListenerDart current_connection_listener_dart;
static PayloadListenerDart current_payload_listener_dart;
void ResultCB(Status status) {
(void)status; // Avoid unused parameter warning
Dart_CObject dart_object_result_callback;
dart_object_result_callback.type = Dart_CObject_kInt64;
dart_object_result_callback.value.as_int64 = status.value;
const bool result = Dart_PostCObject_DL(port, &dart_object_result_callback);
if (!result) {
NEARBY_LOG(INFO, "Posting message to port failed.");
}
adapter_finished->CountDown();
}
void ListenerInitiatedCB(
const char *endpoint_id,
const ConnectionResponseInfoW &connection_response_info) {
NEARBY_LOG(INFO, "Advertising initiated: id=%s", endpoint_id);
Dart_CObject dart_object_endpoint_id;
dart_object_endpoint_id.type = Dart_CObject_kString;
dart_object_endpoint_id.value.as_string = const_cast<char *>(endpoint_id);
Dart_CObject dart_object_endpoint_info;
dart_object_endpoint_info.type = Dart_CObject_kString;
dart_object_endpoint_info.value.as_string =
const_cast<char *>(connection_response_info.remote_endpoint_info);
Dart_CObject *elements[2];
elements[0] = &dart_object_endpoint_id;
elements[1] = &dart_object_endpoint_info;
Dart_CObject dart_object_initiated;
dart_object_initiated.type = Dart_CObject_kArray;
dart_object_initiated.value.as_array.length = 2;
dart_object_initiated.value.as_array.values = elements;
const bool result =
Dart_PostCObject_DL(current_connection_listener_dart.initiated_dart_port,
&dart_object_initiated);
if (!result) {
NEARBY_LOG(INFO, "Posting message to port failed.");
}
}
void ListenerAcceptedCB(const char *endpoint_id) {
NEARBY_LOG(INFO, "Advertising accepted: id=%s", endpoint_id);
Dart_CObject dart_object_accepted;
dart_object_accepted.type = Dart_CObject_kString;
dart_object_accepted.value.as_string = const_cast<char *>(endpoint_id);
const bool result =
Dart_PostCObject_DL(current_connection_listener_dart.accepted_dart_port,
&dart_object_accepted);
if (!result) {
NEARBY_LOG(INFO, "Posting message to port failed.");
}
}
void ListenerRejectedCB(const char *endpoint_id, connections::Status status) {
NEARBY_LOG(INFO, "Advertising rejected: id=%s", endpoint_id);
Dart_CObject dart_object_rejected;
dart_object_rejected.type = Dart_CObject_kString;
dart_object_rejected.value.as_string = const_cast<char *>(endpoint_id);
const bool result =
Dart_PostCObject_DL(current_connection_listener_dart.rejected_dart_port,
&dart_object_rejected);
if (!result) {
NEARBY_LOG(INFO, "Posting message to port failed.");
}
}
void ListenerDisconnectedCB(const char *endpoint_id) {
NEARBY_LOG(INFO, "Advertising disconnected: id=%s", endpoint_id);
Dart_CObject dart_object_disconnected;
dart_object_disconnected.type = Dart_CObject_kString;
dart_object_disconnected.value.as_string = const_cast<char *>(endpoint_id);
const bool result = Dart_PostCObject_DL(
current_connection_listener_dart.disconnected_dart_port,
&dart_object_disconnected);
if (!result) {
NEARBY_LOG(INFO, "Posting message to port failed.");
}
}
void ListenerBandwidthChangedCB(const char *endpoint_id, MediumW medium) {
NEARBY_LOG(INFO, "Advertising bandwidth changed: id=%s", endpoint_id);
Dart_CObject dart_object_bandwidth_changed;
dart_object_bandwidth_changed.type = Dart_CObject_kString;
dart_object_bandwidth_changed.value.as_string =
const_cast<char *>(endpoint_id);
const bool result = Dart_PostCObject_DL(
current_connection_listener_dart.bandwidth_changed_dart_port,
&dart_object_bandwidth_changed);
if (!result) {
NEARBY_LOG(INFO, "Posting message to port failed.");
}
}
void ListenerEndpointFoundCB(const char *endpoint_id, const char *endpoint_info,
size_t endpoint_info_size,
const char *str_service_id) {
NEARBY_LOG(INFO, "Device discovered: id=%s", endpoint_id);
NEARBY_LOG(INFO, "Device discovered: service_id=%s", str_service_id);
NEARBY_LOG(INFO, "Device discovered: info=%s", endpoint_info);
Dart_CObject dart_object_endpoint_id;
dart_object_endpoint_id.type = Dart_CObject_kString;
dart_object_endpoint_id.value.as_string = const_cast<char *>(endpoint_id);
Dart_CObject dart_object_endpoint_info;
dart_object_endpoint_info.type = Dart_CObject_kString;
dart_object_endpoint_info.value.as_string = const_cast<char *>(endpoint_info);
Dart_CObject *elements[2];
elements[0] = &dart_object_endpoint_id;
elements[1] = &dart_object_endpoint_info;
Dart_CObject dart_object_found;
dart_object_found.type = Dart_CObject_kArray;
dart_object_found.value.as_array.length = 2;
dart_object_found.value.as_array.values = elements;
const bool result = Dart_PostCObject_DL(
current_discovery_listener_dart.found_dart_port, &dart_object_found);
if (!result) {
NEARBY_LOG(INFO, "Posting message to port failed.");
}
}
void ListenerEndpointLostCB(const char *endpoint_id) {
NEARBY_LOG(INFO, "Device lost: id=%s", endpoint_id);
Dart_CObject dart_object_lost;
dart_object_lost.type = Dart_CObject_kString;
dart_object_lost.value.as_string = const_cast<char *>(endpoint_id);
const bool result = Dart_PostCObject_DL(
current_discovery_listener_dart.lost_dart_port, &dart_object_lost);
if (!result) {
NEARBY_LOG(INFO, "Posting message to port failed.");
}
}
void ListenerEndpointDistanceChangedCB(const char *endpoint_id,
DistanceInfoW distance_info) {
(void)distance_info; // Avoid unused parameter warning
NEARBY_LOG(INFO, "Device distance changed: id=%s", endpoint_id);
Dart_CObject dart_object_distance_changed;
dart_object_distance_changed.type = Dart_CObject_kString;
dart_object_distance_changed.value.as_string =
const_cast<char *>(endpoint_id);
const bool result = Dart_PostCObject_DL(
current_discovery_listener_dart.distance_changed_dart_port,
&dart_object_distance_changed);
if (!result) {
NEARBY_LOG(INFO, "Posting message to port failed.");
}
}
void ListenerPayloadCB(const char *endpoint_id, PayloadW &payload) {
NEARBY_LOG(INFO,
"Payload callback called. id: %s, "
"payload_id: %d, type: %d, offset: %d",
endpoint_id, payload.GetId(), payload.GetType(),
payload.GetOffset());
Dart_CObject dart_object_endpoint_id;
dart_object_endpoint_id.type = Dart_CObject_kString;
dart_object_endpoint_id.value.as_string = const_cast<char *>(endpoint_id);
Dart_CObject dart_object_payload_id;
dart_object_payload_id.type = Dart_CObject_kInt64;
dart_object_payload_id.value.as_int64 = payload.GetId();
switch (payload.GetType()) {
case nearby::connections::PayloadType::kBytes: {
const char *bytes = nullptr;
size_t bytes_size;
if (!payload.AsBytes(bytes, bytes_size)) {
NEARBY_LOG(INFO, "Failed to get the payload as bytes.");
return;
}
Dart_CObject dart_object_bytes;
dart_object_bytes.type = Dart_CObject_kTypedData;
dart_object_bytes.value.as_typed_data = {
.type = Dart_TypedData_kUint8,
.length = static_cast<intptr_t>(bytes_size),
.values = reinterpret_cast<const uint8_t *>(bytes),
};
Dart_CObject *elements[] = {
&dart_object_endpoint_id,
&dart_object_payload_id,
&dart_object_bytes,
};
Dart_CObject dart_object_payload;
dart_object_payload.type = Dart_CObject_kArray;
dart_object_payload.value.as_array.length = 3;
dart_object_payload.value.as_array.values = elements;
if (!Dart_PostCObject_DL(
current_payload_listener_dart.initial_byte_info_port,
&dart_object_payload)) {
NEARBY_LOG(INFO, "Posting message to port failed.");
}
return;
}
case nearby::connections::PayloadType::kStream: {
Dart_CObject *elements[] = {
&dart_object_endpoint_id,
&dart_object_payload_id,
};
Dart_CObject dart_object_payload;
dart_object_payload.type = Dart_CObject_kArray;
dart_object_payload.value.as_array.length = 2;
dart_object_payload.value.as_array.values = elements;
if (!Dart_PostCObject_DL(
current_payload_listener_dart.initial_stream_info_port,
&dart_object_payload)) {
NEARBY_LOG(INFO, "Posting message to port failed.");
}
return;
}
case nearby::connections::PayloadType::kFile: {
Dart_CObject dart_object_offset;
dart_object_offset.type = Dart_CObject_kInt64;
dart_object_offset.value.as_int64 = payload.GetOffset();
std::string path = payload.AsFile()->GetFilePath();
Dart_CObject dart_object_path;
dart_object_path.type = Dart_CObject_kString;
dart_object_path.value.as_string = const_cast<char *>(path.c_str());
Dart_CObject *elements[] = {
&dart_object_endpoint_id,
&dart_object_payload_id,
&dart_object_offset,
&dart_object_path,
};
Dart_CObject dart_object_payload;
dart_object_payload.type = Dart_CObject_kArray;
dart_object_payload.value.as_array.length = 4;
dart_object_payload.value.as_array.values = elements;
if (!Dart_PostCObject_DL(
current_payload_listener_dart.initial_file_info_port,
&dart_object_payload)) {
NEARBY_LOG(INFO, "Posting message to port failed.");
}
return;
}
default:
NEARBY_LOG(INFO, "Invalid payload type.");
return;
}
}
void ListenerPayloadProgressCB(
const char *endpoint_id,
const PayloadProgressInfoW &payload_progress_info) {
NEARBY_LOG(INFO,
"Payload progress callback called. id: %s, "
"payload_id: %d, bytes transferred: %d, total: %d, status: %d",
endpoint_id, payload_progress_info.payload_id,
payload_progress_info.bytes_transferred,
payload_progress_info.total_bytes, payload_progress_info.status);
Dart_CObject dart_object_endpoint_id;
dart_object_endpoint_id.type = Dart_CObject_kString;
dart_object_endpoint_id.value.as_string = const_cast<char *>(endpoint_id);
Dart_CObject dart_object_payload_id;
dart_object_payload_id.type = Dart_CObject_kInt64;
dart_object_payload_id.value.as_int64 = payload_progress_info.payload_id;
Dart_CObject dart_object_bytes_transferred;
dart_object_bytes_transferred.type = Dart_CObject_kInt64;
dart_object_bytes_transferred.value.as_int64 =
payload_progress_info.bytes_transferred;
Dart_CObject dart_object_total_bytes;
dart_object_total_bytes.type = Dart_CObject_kInt64;
dart_object_total_bytes.value.as_int64 = payload_progress_info.total_bytes;
Dart_CObject dart_object_status;
dart_object_status.type = Dart_CObject_kInt64;
dart_object_status.value.as_int64 = (int64_t)payload_progress_info.status;
Dart_CObject *elements[5];
elements[0] = &dart_object_endpoint_id;
elements[1] = &dart_object_payload_id;
elements[2] = &dart_object_bytes_transferred;
elements[3] = &dart_object_total_bytes;
elements[4] = &dart_object_status;
Dart_CObject dart_object_payload_progress;
dart_object_payload_progress.type = Dart_CObject_kArray;
dart_object_payload_progress.value.as_array.length = 5;
dart_object_payload_progress.value.as_array.values = elements;
if (!Dart_PostCObject_DL(
current_payload_listener_dart.payload_progress_dart_port,
&dart_object_payload_progress)) {
NEARBY_LOG(INFO, "Posting message to port failed.");
}
}
void SetResultCallback(ResultCallbackW &result_callback, Dart_Port &dart_port) {
port = dart_port;
result_callback.result_cb = ResultCB;
}
void PostResult(Dart_Port &result_cb, Status::Value value) {
port = result_cb;
Dart_CObject dart_object_result_callback;
dart_object_result_callback.type = Dart_CObject_kInt64;
dart_object_result_callback.value.as_int64 = value;
const bool result =
Dart_PostCObject_DL(result_cb, &dart_object_result_callback);
if (!result) {
NEARBY_LOG(INFO, "Returning error to port failed.");
}
}
void EnableBleV2Dart(Core *pCore, int64_t enable, Dart_Port result_cb) {
if (!pCore) {
PostResult(result_cb, Status::Value::kError);
return;
}
port = result_cb;
NearbyFlags::GetInstance().OverrideBoolFlagValue(
connections::config_package_nearby::nearby_connections_feature::
kEnableBleV2,
enable);
PostResult(result_cb, Status::kSuccess);
}
void StartAdvertisingDart(
Core *pCore, const char *service_id,
AdvertisingOptionsDart connection_options_dart,
ConnectionRequestInfoDart connection_request_info_dart,
Dart_Port result_cb) {
if (!pCore) {
PostResult(result_cb, Status::Value::kError);
return;
}
port = result_cb;
current_connection_listener_dart =
connection_request_info_dart.connection_listener;
AdvertisingOptionsW advertising_options;
advertising_options.strategy = GetStrategy(connection_options_dart.strategy);
advertising_options.auto_upgrade_bandwidth =
connection_options_dart.auto_upgrade_bandwidth;
advertising_options.enforce_topology_constraints =
connection_options_dart.enforce_topology_constraints;
advertising_options.low_power = connection_options_dart.low_power;
advertising_options.fast_advertisement_service_uuid =
connection_options_dart.fast_advertisement_service_uuid;
advertising_options.allowed.bluetooth =
connection_options_dart.mediums.bluetooth;
advertising_options.allowed.ble = connection_options_dart.mediums.ble;
advertising_options.allowed.wifi_lan =
connection_options_dart.mediums.wifi_lan;
advertising_options.allowed.wifi_hotspot =
connection_options_dart.mediums.wifi_hotspot;
advertising_options.allowed.web_rtc = connection_options_dart.mediums.web_rtc;
ConnectionListenerW listener(ListenerInitiatedCB, ListenerAcceptedCB,
ListenerRejectedCB, ListenerDisconnectedCB,
ListenerBandwidthChangedCB);
ConnectionRequestInfoW info{
connection_request_info_dart.endpoint_info,
strlen(connection_request_info_dart.endpoint_info), listener};
ResultCallbackW callback;
SetResultCallback(callback, result_cb);
CountDownLatch finished(1);
adapter_finished = &finished;
StartAdvertising(pCore, service_id, advertising_options, info, callback);
finished.Await();
}
void StopAdvertisingDart(Core *pCore, Dart_Port dart_port) {
if (!pCore) {
PostResult(dart_port, Status::Value::kError);
return;
}
port = dart_port;
ResultCallbackW callback;
SetResultCallback(callback, dart_port);
CountDownLatch finished(1);
adapter_finished = &finished;
StopAdvertising(pCore, callback);
finished.Await();
}
void StartDiscoveryDart(Core *pCore, const char *service_id,
DiscoveryOptionsDart discovery_options_dart,
DiscoveryListenerDart discovery_listener_dart,
Dart_Port dart_port) {
if (!pCore) {
PostResult(dart_port, Status::Value::kError);
return;
}
port = dart_port;
current_discovery_listener_dart = discovery_listener_dart;
DiscoveryOptionsW discovery_options;
discovery_options.strategy = GetStrategy(discovery_options_dart.strategy);
discovery_options.allowed.web_rtc = false;
discovery_options.enforce_topology_constraints = true;
// This needs to be passed in by the UI. If it's null, then no
// fast_advertisement_service. Otherwise this interface will always
// and forever be locked into 0000FE2C-0000-1000-8000-00805F9B34FB
// whenever fast advertisement service is requested.
discovery_options.fast_advertisement_service_uuid =
discovery_options_dart.fast_advertisement_service_uuid;
discovery_options.allowed.bluetooth =
discovery_options_dart.mediums.bluetooth;
discovery_options.allowed.ble = discovery_options_dart.mediums.ble;
discovery_options.allowed.wifi_lan = discovery_options_dart.mediums.wifi_lan;
discovery_options.allowed.wifi_hotspot =
discovery_options_dart.mediums.wifi_hotspot;
discovery_options.allowed.web_rtc = discovery_options_dart.mediums.web_rtc;
DiscoveryListenerW listener(ListenerEndpointFoundCB, ListenerEndpointLostCB,
ListenerEndpointDistanceChangedCB);
ResultCallbackW callback;
SetResultCallback(callback, dart_port);
CountDownLatch finished(1);
adapter_finished = &finished;
StartDiscovery(pCore, service_id, discovery_options, listener, callback);
finished.Await();
}
void StopDiscoveryDart(Core *pCore, Dart_Port dart_port) {
if (!pCore) {
PostResult(dart_port, Status::Value::kError);
return;
}
port = dart_port;
ResultCallbackW callback;
SetResultCallback(callback, dart_port);
CountDownLatch finished(1);
adapter_finished = &finished;
StopDiscovery(pCore, callback);
adapter_finished->Await();
}
void RequestConnectionDart(
Core *pCore, const char *endpoint_id,
ConnectionOptionsDart connection_options_dart,
ConnectionRequestInfoDart connection_request_info_dart,
Dart_Port dart_port) {
if (!pCore) {
PostResult(dart_port, Status::Value::kError);
return;
}
port = dart_port;
current_connection_listener_dart =
connection_request_info_dart.connection_listener;
ConnectionOptionsW connection_options;
connection_options.enforce_topology_constraints = false;
connection_options.remote_bluetooth_mac_address =
connection_options_dart.remote_bluetooth_mac_address;
connection_options.fast_advertisement_service_uuid =
connection_options_dart.fast_advertisement_service_uuid;
connection_options.keep_alive_interval_millis =
connection_options_dart.keep_alive_interval_millis;
connection_options.keep_alive_timeout_millis =
connection_options_dart.keep_alive_timeout_millis;
connection_options.allowed.bluetooth =
connection_options_dart.mediums.bluetooth;
connection_options.allowed.ble = connection_options_dart.mediums.ble;
connection_options.allowed.wifi_lan =
connection_options_dart.mediums.wifi_lan;
connection_options.allowed.wifi_hotspot =
connection_options_dart.mediums.wifi_hotspot;
connection_options.allowed.web_rtc = connection_options_dart.mediums.web_rtc;
ConnectionListenerW listener(ListenerInitiatedCB, ListenerAcceptedCB,
ListenerRejectedCB, ListenerDisconnectedCB,
ListenerBandwidthChangedCB);
ConnectionRequestInfoW info{
connection_request_info_dart.endpoint_info,
strlen(connection_request_info_dart.endpoint_info), listener};
ResultCallbackW callback;
SetResultCallback(callback, dart_port);
CountDownLatch finished(1);
adapter_finished = &finished;
RequestConnection(pCore, endpoint_id, info, connection_options, callback);
adapter_finished->Await();
}
void AcceptConnectionDart(Core *pCore, const char *endpoint_id,
PayloadListenerDart payload_listener_dart,
Dart_Port dart_port) {
if (!pCore) {
PostResult(dart_port, Status::Value::kError);
return;
}
port = dart_port;
current_payload_listener_dart = payload_listener_dart;
PayloadListenerW listener(ListenerPayloadCB, ListenerPayloadProgressCB);
ResultCallbackW callback;
SetResultCallback(callback, dart_port);
CountDownLatch finished(1);
adapter_finished = &finished;
AcceptConnection(pCore, endpoint_id, listener, callback);
finished.Await();
}
void RejectConnectionDart(Core *pCore, const char *endpoint_id,
Dart_Port dart_port) {
if (!pCore) {
PostResult(dart_port, Status::Value::kError);
return;
}
port = dart_port;
ResultCallbackW callback;
SetResultCallback(callback, dart_port);
CountDownLatch finished(1);
adapter_finished = &finished;
RejectConnection(pCore, endpoint_id, callback);
finished.Await();
}
void DisconnectFromEndpointDart(Core *pCore, char *endpoint_id,
Dart_Port dart_port) {
if (!pCore) {
PostResult(dart_port, Status::Value::kError);
return;
}
port = dart_port;
ResultCallbackW callback;
SetResultCallback(callback, dart_port);
CountDownLatch finished(1);
adapter_finished = &finished;
DisconnectFromEndpoint(pCore, endpoint_id, callback);
finished.Await();
}
void SendPayloadDart(Core *pCore, const char *endpoint_id,
PayloadDart payload_dart, Dart_Port dart_port) {
if (!pCore) {
PostResult(dart_port, Status::Value::kError);
return;
}
port = dart_port;
ResultCallbackW callback;
std::vector<std::string> endpoint_ids = {std::string(endpoint_id)};
NEARBY_LOG(INFO, "Payload type: %d", payload_dart.type);
switch (payload_dart.type) {
case UNKNOWN:
case STREAM:
NEARBY_LOG(INFO, "Payload type not supported yet");
PostResult(dart_port, Status::Value::kPayloadUnknown);
break;
case BYTE: {
PayloadW payload(PayloadW::GenerateId(), payload_dart.data,
payload_dart.size);
std::vector<const char *> c_string_array;
std::transform(endpoint_ids.begin(), endpoint_ids.end(),
std::back_inserter(c_string_array),
[](const std::string &s) {
char *pc = new char[s.size() + 1];
strncpy(pc, s.c_str(), s.size() + 1);
return pc;
});
SetResultCallback(callback, dart_port);
CountDownLatch finished(1);
adapter_finished = &finished;
SendPayload(pCore, c_string_array.data(), c_string_array.size(),
std::move(payload), callback);
adapter_finished->Await();
} break;
case FILE:
NEARBY_LOG(INFO, "File name: %s, size %d", payload_dart.data,
payload_dart.size);
std::string file_name_str(payload_dart.data);
InputFileW input_file(file_name_str.c_str(), payload_dart.size);
PayloadW payload(input_file);
std::vector<const char *> c_string_array;
std::transform(endpoint_ids.begin(), endpoint_ids.end(),
std::back_inserter(c_string_array),
[](const std::string &s) {
char *pc = new char[s.size() + 1];
strncpy(pc, s.c_str(), s.size() + 1);
return pc;
});
SetResultCallback(callback, dart_port);
CountDownLatch finished(1);
adapter_finished = &finished;
SendPayload(pCore, c_string_array.data(), c_string_array.size(),
std::move(payload), callback);
adapter_finished->Await();
break;
}
}
} // namespace nearby::windows
-310
View File
@@ -1,310 +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 LOCATION_NEARBY_CONNECTIONS_DART_CORE_ADAPTER_DART_H_
#define LOCATION_NEARBY_CONNECTIONS_DART_CORE_ADAPTER_DART_H_
#include "third_party/dart_lang/v2/runtime/include/dart_api_dl.h"
#include "third_party/dart_lang/v2/runtime/include/dart_native_api.h"
#include "connections/c/core_adapter.h"
namespace nearby::windows {
enum class StrategyDart {
P2P_CLUSTER = 0,
P2P_STAR,
P2P_POINT_TO_POINT,
};
enum PayloadType {
// LINT.IfChange
UNKNOWN = 0,
BYTE,
STREAM,
FILE,
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/payload.dart)
};
struct Mediums {
// LINT.IfChange
int64_t bluetooth;
int64_t ble;
int64_t wifi_lan;
int64_t wifi_hotspot;
int64_t web_rtc;
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/mediums.dart)
};
extern "C" {
struct AdvertisingOptionsDart {
// LINT.IfChange
StrategyDart strategy;
int64_t auto_upgrade_bandwidth;
int64_t enforce_topology_constraints;
int64_t low_power;
// Whether this is intended to be used in conjunction with InjectEndpoint().
int64_t 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;
Mediums mediums;
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/advertising_options.dart)
};
struct ConnectionOptionsDart {
// LINT.IfChange
StrategyDart strategy;
// Whether this is intended to be used in conjunction with InjectEndpoint().
int64_t auto_upgrade_bandwidth;
int64_t enforce_topology_constraints;
int64_t low_power;
// Whether this is intended to be used in conjunction with InjectEndpoint().
int64_t is_out_of_band_connection = false;
char *remote_bluetooth_mac_address;
char *fast_advertisement_service_uuid;
int64_t keep_alive_interval_millis;
int64_t keep_alive_timeout_millis;
Mediums mediums;
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/connection_options.dart)
};
struct DiscoveryOptionsDart {
// LINT.IfChange
StrategyDart strategy;
int64_t auto_upgrade_bandwidth;
int64_t enforce_topology_constraints;
// Whether this is intended to be used in conjunction with InjectEndpoint().
int64_t is_out_of_band_connection = false;
const char *fast_advertisement_service_uuid;
const char *remote_bluetooth_mac_address;
Mediums mediums;
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/discovery_options.dart)
};
struct DiscoveryListenerDart {
// LINT.IfChange
int64_t found_dart_port;
int64_t lost_dart_port;
int64_t distance_changed_dart_port;
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/discovery_listener.dart)
};
struct PayloadListenerDart {
// LINT.IfChange
int64_t initial_byte_info_port;
int64_t initial_stream_info_port;
int64_t initial_file_info_port;
int64_t payload_progress_dart_port;
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/payload_listener.dart)
};
struct ConnectionListenerDart {
// LINT.IfChange
int64_t initiated_dart_port;
int64_t accepted_dart_port;
int64_t rejected_dart_port;
int64_t disconnected_dart_port;
int64_t bandwidth_changed_dart_port;
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/connection_listener.dart)
};
struct ConnectionRequestInfoDart {
// LINT.IfChange
char *endpoint_info;
ConnectionListenerDart connection_listener;
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/connection_request_info.dart)
};
struct PayloadDart {
// LINT.IfChange
int64_t id;
PayloadType type;
int64_t size;
char *data;
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/payload.dart)
};
static void ResultCB(Status status);
static void ListenerInitiatedCB(const char *endpoint_id,
const ConnectionResponseInfoW &connection_info);
static void ListenerAcceptedCB(const char *endpoint_id);
static void ListenerRejectedCB(const char *endpoint_id,
connections::Status status);
static void ListenerDisconnectedCB(const char *endpoint_id);
static void ListenerBandwidthChangedCB(const char *endpoint_id, MediumW medium);
static void ListenerEndpointFoundCB(const char *endpoint_id,
const char *endpoint_info,
size_t endpoint_info_size,
const char *str_service_id);
static void ListenerEndpointLostCB(const char *endpoint_id);
static void ListenerEndpointDistanceChangedCB(const char *endpoint_id,
DistanceInfoW info);
static void ListenerPayloadCB(const char *endpoint_id, PayloadW &payload);
static void ListenerPayloadProgressCB(const char *endpoint_id,
const PayloadProgressInfoW &info);
DLL_API void __stdcall EnableBleV2Dart(Core *pCore, int64_t enable,
Dart_Port result_cb);
// 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.
// options_dart - options for advertising
// info_dart - Including callbacks notified when remote
// endpoints request a connection to this endpoint.
// result_cb - 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 StartAdvertisingDart(Core *pCore, const char *service_id,
AdvertisingOptionsDart options_dart,
ConnectionRequestInfoDart info_dart,
Dart_Port result_cb);
// 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 StopAdvertisingDart(Core *pCore, Dart_Port result_cb);
// 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.
// options - The options for discovery.
// listener - Callbacks notified when a remote endpoint is discovered.
// 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 StartDiscoveryDart(Core *pCore, const char *service_id,
DiscoveryOptionsDart options_dart,
DiscoveryListenerDart listener_dart,
Dart_Port result_cb);
// 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 StopDiscoveryDart(Core *pCore, Dart_Port result_cb);
// 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()
// options_dart - The options for connection.
// info_dart - Connection parameters:
// > name - A human readable name for the local endpoint, to appear on
// the remote endpoint.
// > listener - Callbacks 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 RequestConnectionDart(
Core *pCore, const char *endpoint_id, ConnectionOptionsDart options_dart,
ConnectionRequestInfoDart info_dart, Dart_Port result_cb);
// 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_dart - 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 AcceptConnectionDart(Core *pCore,
const char *endpoint_id,
PayloadListenerDart listener_dart,
Dart_Port result_cb);
DLL_API void __stdcall RejectConnectionDart(Core *pCore,
const char *endpoint_id,
Dart_Port result_cb);
// 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 DisconnectFromEndpointDart(Core *pCore,
char *endpoint_id,
Dart_Port result_cb);
// 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_id - Remote endpoint identifier 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 SendPayloadDart(Core *pCore, const char *endpoint_id,
PayloadDart payload_dart,
Dart_Port result_cb);
} // extern "C"
} // namespace nearby::windows
#endif // LOCATION_NEARBY_CONNECTIONS_DART_CORE_ADAPTER_DART_H_
+774
View File
@@ -0,0 +1,774 @@
// Copyright 2024 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/dart/nc_adapter_dart.h"
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/no_destructor.h"
#include "absl/strings/escaping.h"
#include "absl/strings/string_view.h"
#include "third_party/dart_lang/v2/runtime/include/dart_api.h"
#include "third_party/dart_lang/v2/runtime/include/dart_api_dl.h"
#include "third_party/dart_lang/v2/runtime/include/dart_native_api.h"
#include "connections/c/nc.h"
#include "connections/c/nc_types.h"
#include "connections/dart/nc_adapter_types.h"
#include "connections/dart/nearby_connections_client_state.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/logging.h"
#include "internal/platform/prng.h"
using nearby::connections::dart::NearbyConnectionsClientState;
using NearbyConnectionsApi = nearby::connections::dart::
NearbyConnectionsClientState::NearbyConnectionsApi;
static absl::NoDestructor<NearbyConnectionsClientState> kClientState;
NC_STRATEGY_TYPE GetStrategy(StrategyDart strategy) {
switch (strategy) {
case STRATEGY_P2P_CLUSTER:
return NC_STRATEGY_TYPE_P2P_CLUSTER;
case STRATEGY_P2P_POINT_TO_POINT:
return NC_STRATEGY_TYPE_P2P_POINT_TO_POINT;
case STRATEGY_P2P_STAR:
return NC_STRATEGY_TYPE_P2P_STAR;
default:
break;
}
return NC_STRATEGY_TYPE_NONE;
}
nearby::ByteArray ConvertBluetoothMacAddress(absl::string_view address) {
return nearby::ByteArray(std::string(address));
}
NC_PAYLOAD_ID GeneratePayloadId() { return nearby::Prng().NextInt64(); }
void ResultCB(std::optional<Dart_Port> port, NC_STATUS status) {
(void)status; // Avoid unused parameter warning
if (!port.has_value()) {
NEARBY_LOGS(ERROR) << "ResultCB called with invalid port.";
return;
}
Dart_CObject dart_object_result_callback;
dart_object_result_callback.type = Dart_CObject_kInt64;
dart_object_result_callback.value.as_int64 = static_cast<int64_t>(status);
const bool result = Dart_PostCObject_DL(*port, &dart_object_result_callback);
if (!result) {
NEARBY_LOGS(WARNING) << "Posting message to port failed.";
}
}
std::string GetEndpointIdString(int endpoint_id) {
std::string endpoint_id_str;
endpoint_id_str.resize(4);
endpoint_id_str[0] = endpoint_id & 0xff;
endpoint_id_str[1] = (endpoint_id >> 8) & 0xff;
endpoint_id_str[2] = (endpoint_id >> 16) & 0xff;
endpoint_id_str[3] = (endpoint_id >> 24) & 0xff;
return endpoint_id_str;
}
void ListenerInitiatedCB(
NC_INSTANCE instance, int endpoint_id,
const NC_CONNECTION_RESPONSE_INFO *connection_response_info) {
NEARBY_LOGS(INFO) << "Advertising initiated: id="
<< GetEndpointIdString(endpoint_id);
Dart_CObject dart_object_endpoint_id = {
.type = Dart_CObject_Type::Dart_CObject_kInt32,
.value = {.as_int32 = endpoint_id}};
Dart_CObject dart_object_endpoint_info = {
.type = Dart_CObject_Type::Dart_CObject_kTypedData,
.value = {.as_typed_data{
.type = Dart_TypedData_Type::Dart_TypedData_kUint8,
.length =
(intptr_t)connection_response_info->remote_endpoint_info.size,
.values =
(uint8_t *)connection_response_info->remote_endpoint_info.data}}};
Dart_CObject *elements[2];
elements[0] = &dart_object_endpoint_id;
elements[1] = &dart_object_endpoint_info;
Dart_CObject dart_object_initiated;
dart_object_initiated.type = Dart_CObject_kArray;
dart_object_initiated.value.as_array.length = 2;
dart_object_initiated.value.as_array.values = elements;
const bool result = Dart_PostCObject_DL(
kClientState->GetConnectionListenerDart()->initiated_dart_port,
&dart_object_initiated);
if (!result) {
NEARBY_LOGS(INFO) << "Posting message to port failed.";
}
}
void ListenerAcceptedCB(NC_INSTANCE instance, int endpoint_id) {
NEARBY_LOGS(INFO) << "Advertising accepted: id="
<< GetEndpointIdString(endpoint_id);
Dart_CObject dart_object_accepted;
dart_object_accepted.type = Dart_CObject_kInt32;
dart_object_accepted.value.as_int32 = endpoint_id;
const bool result = Dart_PostCObject_DL(
kClientState->GetConnectionListenerDart()->accepted_dart_port,
&dart_object_accepted);
if (!result) {
NEARBY_LOGS(INFO) << "Posting message to port failed.";
}
}
void ListenerRejectedCB(NC_INSTANCE instance, int endpoint_id,
NC_STATUS status) {
NEARBY_LOGS(INFO) << "Advertising rejected: id="
<< GetEndpointIdString(endpoint_id);
Dart_CObject dart_object_rejected;
dart_object_rejected.type = Dart_CObject_kInt32;
dart_object_rejected.value.as_int32 = endpoint_id;
const bool result = Dart_PostCObject_DL(
kClientState->GetConnectionListenerDart()->rejected_dart_port,
&dart_object_rejected);
if (!result) {
NEARBY_LOGS(INFO) << "Posting message to port failed.";
}
}
void ListenerDisconnectedCB(NC_INSTANCE instance, int endpoint_id) {
NEARBY_LOGS(INFO) << "Advertising disconnected: id="
<< GetEndpointIdString(endpoint_id);
Dart_CObject dart_object_disconnected;
dart_object_disconnected.type = Dart_CObject_kInt32;
dart_object_disconnected.value.as_int32 = endpoint_id;
const bool result = Dart_PostCObject_DL(
kClientState->GetConnectionListenerDart()->disconnected_dart_port,
&dart_object_disconnected);
if (!result) {
NEARBY_LOGS(INFO) << "Posting message to port failed.";
}
}
void ListenerBandwidthChangedCB(NC_INSTANCE instance, int endpoint_id,
NC_MEDIUM medium) {
NEARBY_LOGS(INFO) << "Advertising bandwidth changed: id="
<< GetEndpointIdString(endpoint_id);
Dart_CObject dart_object_bandwidth_changed;
dart_object_bandwidth_changed.type = Dart_CObject_kInt32;
dart_object_bandwidth_changed.value.as_int32 = endpoint_id;
const bool result = Dart_PostCObject_DL(
kClientState->GetConnectionListenerDart()->bandwidth_changed_dart_port,
&dart_object_bandwidth_changed);
if (!result) {
NEARBY_LOGS(INFO) << "Posting message to port failed.";
}
}
void ListenerEndpointFoundCB(NC_INSTANCE instance, int endpoint_id,
const NC_DATA *endpoint_info,
const NC_DATA *service_id) {
NEARBY_LOGS(INFO) << "Device discovered: id="
<< GetEndpointIdString(endpoint_id);
NEARBY_LOGS(INFO) << "Device discovered: service_id="
<< std::string(service_id->data, service_id->size);
std::string endpoint_info_str = absl::BytesToHexString(
absl::string_view(endpoint_info->data, endpoint_info->size));
NEARBY_LOGS(INFO) << "Device discovered: info=" << endpoint_info_str;
Dart_CObject dart_object_endpoint_id = {
.type = Dart_CObject_Type::Dart_CObject_kInt32,
.value = {.as_int32 = endpoint_id}};
Dart_CObject dart_object_endpoint_info = {
.type = Dart_CObject_Type::Dart_CObject_kTypedData,
.value = {
.as_typed_data{.type = Dart_TypedData_Type::Dart_TypedData_kUint8,
.length = (intptr_t)endpoint_info->size,
.values = (uint8_t *)endpoint_info->data}}};
Dart_CObject *elements[2];
elements[0] = &dart_object_endpoint_id;
elements[1] = &dart_object_endpoint_info;
Dart_CObject dart_object_found;
dart_object_found.type = Dart_CObject_kArray;
dart_object_found.value.as_array.length = 2;
dart_object_found.value.as_array.values = elements;
const bool result = Dart_PostCObject_DL(
kClientState->GetDiscoveryListenerDart()->found_dart_port,
&dart_object_found);
if (!result) {
NEARBY_LOGS(INFO) << "Posting message to port failed.";
}
}
void ListenerEndpointLostCB(NC_INSTANCE instance, int endpoint_id) {
NEARBY_LOGS(INFO) << "Device lost: id=" << GetEndpointIdString(endpoint_id);
Dart_CObject dart_object_lost;
dart_object_lost.type = Dart_CObject_kInt32;
dart_object_lost.value.as_int32 = endpoint_id;
const bool result = Dart_PostCObject_DL(
kClientState->GetDiscoveryListenerDart()->lost_dart_port,
&dart_object_lost);
if (!result) {
NEARBY_LOGS(INFO) << "Posting message to port failed.";
}
}
void ListenerEndpointDistanceChangedCB(NC_INSTANCE instance, int endpoint_id,
NC_DISTANCE_INFO distance_info) {
(void)distance_info; // Avoid unused parameter warning
NEARBY_LOGS(INFO) << "Device distance changed: id="
<< GetEndpointIdString(endpoint_id);
Dart_CObject dart_object_distance_changed;
dart_object_distance_changed.type = Dart_CObject_kInt32;
dart_object_distance_changed.value.as_int32 = endpoint_id;
const bool result = Dart_PostCObject_DL(
kClientState->GetDiscoveryListenerDart()->distance_changed_dart_port,
&dart_object_distance_changed);
if (!result) {
NEARBY_LOGS(INFO) << "Posting message to port failed.";
}
}
void ListenerPayloadCB(NC_INSTANCE instance, int endpoint_id,
const NC_PAYLOAD *payload) {
NEARBY_LOGS(INFO) << "Payload callback called. id: "
<< GetEndpointIdString(endpoint_id)
<< ", payload_id: " << payload->id
<< ", type: " << payload->type;
Dart_CObject dart_object_endpoint_id;
dart_object_endpoint_id.type = Dart_CObject_kInt32;
dart_object_endpoint_id.value.as_int32 = endpoint_id;
Dart_CObject dart_object_payload_id;
dart_object_payload_id.type = Dart_CObject_kInt64;
dart_object_payload_id.value.as_int64 = payload->id;
switch (payload->type) {
case NC_PAYLOAD_TYPE_BYTES: {
const char *bytes = payload->content.bytes.content.data;
size_t bytes_size = payload->content.bytes.content.size;
if (bytes_size == 0) {
NEARBY_LOGS(INFO) << "Failed to get the payload as bytes.";
return;
}
Dart_CObject dart_object_bytes;
dart_object_bytes.type = Dart_CObject_kTypedData;
dart_object_bytes.value.as_typed_data = {
.type = Dart_TypedData_kUint8,
.length = static_cast<intptr_t>(bytes_size),
.values = reinterpret_cast<const uint8_t *>(bytes),
};
Dart_CObject *elements[] = {
&dart_object_endpoint_id,
&dart_object_payload_id,
&dart_object_bytes,
};
Dart_CObject dart_object_payload;
dart_object_payload.type = Dart_CObject_kArray;
dart_object_payload.value.as_array.length = 3;
dart_object_payload.value.as_array.values = elements;
if (!Dart_PostCObject_DL(
kClientState->GetPayloadListenerDart()->initial_byte_info_port,
&dart_object_payload)) {
NEARBY_LOGS(INFO) << "Posting message to port failed.";
}
return;
}
case NC_PAYLOAD_TYPE_STREAM: {
Dart_CObject *elements[] = {
&dart_object_endpoint_id,
&dart_object_payload_id,
};
Dart_CObject dart_object_payload;
dart_object_payload.type = Dart_CObject_kArray;
dart_object_payload.value.as_array.length = 2;
dart_object_payload.value.as_array.values = elements;
if (!Dart_PostCObject_DL(
kClientState->GetPayloadListenerDart()->initial_stream_info_port,
&dart_object_payload)) {
NEARBY_LOGS(INFO) << "Posting message to port failed.";
}
return;
}
case NC_PAYLOAD_TYPE_FILE: {
Dart_CObject dart_object_offset;
dart_object_offset.type = Dart_CObject_kInt64;
dart_object_offset.value.as_int64 = payload->content.file.offset;
std::string path = payload->content.file.file_name;
Dart_CObject dart_object_path;
dart_object_path.type = Dart_CObject_kString;
dart_object_path.value.as_string = const_cast<char *>(path.c_str());
Dart_CObject *elements[] = {
&dart_object_endpoint_id,
&dart_object_payload_id,
&dart_object_offset,
&dart_object_path,
};
Dart_CObject dart_object_payload;
dart_object_payload.type = Dart_CObject_kArray;
dart_object_payload.value.as_array.length = 4;
dart_object_payload.value.as_array.values = elements;
if (!Dart_PostCObject_DL(
kClientState->GetPayloadListenerDart()->initial_file_info_port,
&dart_object_payload)) {
NEARBY_LOGS(INFO) << "Posting message to port failed.";
}
return;
}
default:
NEARBY_LOGS(INFO) << "Invalid payload type.";
return;
}
}
void ListenerPayloadProgressCB(
NC_INSTANCE instance, int endpoint_id,
const NC_PAYLOAD_PROGRESS_INFO *payload_progress_info) {
NEARBY_LOGS(INFO) << "Payload progress callback called. id: "
<< GetEndpointIdString(endpoint_id)
<< ", payload_id: " << payload_progress_info->id
<< ", bytes transferred: "
<< payload_progress_info->bytes_transferred
<< ", total: " << payload_progress_info->total_bytes
<< ", status: " << payload_progress_info->status;
Dart_CObject dart_object_endpoint_id;
dart_object_endpoint_id.type = Dart_CObject_kInt32;
dart_object_endpoint_id.value.as_int32 = endpoint_id;
Dart_CObject dart_object_payload_id;
dart_object_payload_id.type = Dart_CObject_kInt64;
dart_object_payload_id.value.as_int64 = payload_progress_info->id;
Dart_CObject dart_object_bytes_transferred;
dart_object_bytes_transferred.type = Dart_CObject_kInt64;
dart_object_bytes_transferred.value.as_int64 =
payload_progress_info->bytes_transferred;
Dart_CObject dart_object_total_bytes;
dart_object_total_bytes.type = Dart_CObject_kInt64;
dart_object_total_bytes.value.as_int64 = payload_progress_info->total_bytes;
Dart_CObject dart_object_status;
dart_object_status.type = Dart_CObject_kInt64;
dart_object_status.value.as_int64 = (int64_t)payload_progress_info->status;
Dart_CObject *elements[5];
elements[0] = &dart_object_endpoint_id;
elements[1] = &dart_object_payload_id;
elements[2] = &dart_object_bytes_transferred;
elements[3] = &dart_object_total_bytes;
elements[4] = &dart_object_status;
Dart_CObject dart_object_payload_progress;
dart_object_payload_progress.type = Dart_CObject_kArray;
dart_object_payload_progress.value.as_array.length = 5;
dart_object_payload_progress.value.as_array.values = elements;
if (!Dart_PostCObject_DL(
kClientState->GetPayloadListenerDart()->payload_progress_dart_port,
&dart_object_payload_progress)) {
NEARBY_LOGS(INFO) << "Posting message to port failed.";
}
}
void PostResult(Dart_Port &result_cb, NC_STATUS value) {
Dart_CObject dart_object_result_callback;
dart_object_result_callback.type = Dart_CObject_kInt64;
dart_object_result_callback.value.as_int64 = static_cast<int64_t>(value);
const bool result =
Dart_PostCObject_DL(result_cb, &dart_object_result_callback);
if (!result) {
NEARBY_LOGS(INFO) << "Returning error to port failed.";
}
}
NC_INSTANCE CreateServiceDart() {
NC_INSTANCE instance = kClientState->GetOpennedService();
if (instance == nullptr) {
instance = NcCreateService();
kClientState->SetOpennedService(instance);
}
return instance;
}
void CloseServiceDart(NC_INSTANCE instance) {
NcCloseService(instance);
kClientState->reset();
}
int GetLocalEndpointIdDart(NC_INSTANCE instance) {
return NcGetLocalEndpointId(instance);
}
void EnableBleV2Dart(NC_INSTANCE instance, int64_t enable,
Dart_Port result_cb) {
kClientState->PushNearbyConnectionsApiPort(NearbyConnectionsApi::kEnableBleV2,
result_cb);
NcEnableBleV2(instance, enable, [](NC_STATUS status) {
ResultCB(kClientState->PopNearbyConnectionsApiPort(
NearbyConnectionsApi::kEnableBleV2),
status);
});
NEARBY_LOGS(INFO) << "EnableBleV2Dart callback is called with enable="
<< enable;
}
void StartAdvertisingDart(NC_INSTANCE instance, DataDart service_id,
AdvertisingOptionsDart options_dart,
ConnectionRequestInfoDart info_dart,
Dart_Port result_cb) {
if (instance == nullptr) {
PostResult(result_cb, NC_STATUS_ERROR);
return;
}
kClientState->PushNearbyConnectionsApiPort(
NearbyConnectionsApi::kStartAdvertising, result_cb);
kClientState->SetConnectionListenerDart(
std::make_unique<ConnectionListenerDart>(info_dart.connection_listener));
NC_ADVERTISING_OPTIONS advertising_options{};
advertising_options.common_options.strategy.type =
GetStrategy(options_dart.strategy);
advertising_options.auto_upgrade_bandwidth =
options_dart.auto_upgrade_bandwidth;
advertising_options.enforce_topology_constraints =
options_dart.enforce_topology_constraints;
advertising_options.low_power = options_dart.low_power;
advertising_options.fast_advertisement_service_uuid.data =
const_cast<char *>(options_dart.fast_advertisement_service_uuid.data);
advertising_options.fast_advertisement_service_uuid.size =
options_dart.fast_advertisement_service_uuid.size;
advertising_options.common_options.allowed_mediums[NC_MEDIUM_BLUETOOTH] =
options_dart.mediums.bluetooth != 0;
advertising_options.common_options.allowed_mediums[NC_MEDIUM_BLE] =
options_dart.mediums.ble != 0;
advertising_options.common_options.allowed_mediums[NC_MEDIUM_WIFI_LAN] =
options_dart.mediums.wifi_lan != 0;
advertising_options.common_options.allowed_mediums[NC_MEDIUM_WIFI_HOTSPOT] =
options_dart.mediums.wifi_hotspot;
advertising_options.common_options.allowed_mediums[NC_MEDIUM_WEB_RTC] =
options_dart.mediums.web_rtc;
NC_CONNECTION_REQUEST_INFO request_info{};
request_info.endpoint_info.data = info_dart.endpoint_info.data;
request_info.endpoint_info.size = info_dart.endpoint_info.size;
request_info.initiated_callback = &ListenerInitiatedCB;
request_info.accepted_callback = ListenerAcceptedCB;
request_info.rejected_callback = ListenerRejectedCB;
request_info.disconnected_callback = ListenerDisconnectedCB;
request_info.bandwidth_changed_callback = ListenerBandwidthChangedCB;
NC_DATA service_id_data =
NC_DATA{.size = service_id.size, .data = service_id.data};
NcStartAdvertising(instance, &service_id_data, &advertising_options,
&request_info, [](NC_STATUS status) {
ResultCB(kClientState->PopNearbyConnectionsApiPort(
NearbyConnectionsApi::kStartAdvertising),
status);
});
}
void StopAdvertisingDart(NC_INSTANCE instance, Dart_Port result_cb) {
if (instance == nullptr) {
PostResult(result_cb, NC_STATUS_ERROR);
return;
}
kClientState->PushNearbyConnectionsApiPort(
NearbyConnectionsApi::kStopAdvertising, result_cb);
NcStopAdvertising(instance, [](NC_STATUS status) {
kClientState->SetConnectionListenerDart(nullptr);
ResultCB(kClientState->PopNearbyConnectionsApiPort(
NearbyConnectionsApi::kStopAdvertising),
status);
});
}
void StartDiscoveryDart(NC_INSTANCE instance, DataDart service_id,
DiscoveryOptionsDart options_dart,
DiscoveryListenerDart listener_dart,
Dart_Port result_cb) {
if (instance == nullptr) {
PostResult(result_cb, NC_STATUS_ERROR);
return;
}
kClientState->PushNearbyConnectionsApiPort(
NearbyConnectionsApi::kStartDiscovery, result_cb);
kClientState->SetDiscoveryListenerDart(
std::make_unique<DiscoveryListenerDart>(listener_dart));
NC_DISCOVERY_OPTIONS discovery_options{};
discovery_options.common_options.strategy.type =
GetStrategy(options_dart.strategy);
discovery_options.enforce_topology_constraints = true;
// This needs to be passed in by the UI. If it's null, then no
// fast_advertisement_service. Otherwise this interface will always
// and forever be locked into 0000FE2C-0000-1000-8000-00805F9B34FB
// whenever fast advertisement service is requested.
discovery_options.fast_advertisement_service_uuid.data =
const_cast<char *>(options_dart.fast_advertisement_service_uuid.data);
discovery_options.fast_advertisement_service_uuid.size =
options_dart.fast_advertisement_service_uuid.size;
discovery_options.common_options.allowed_mediums[NC_MEDIUM_BLUETOOTH] =
options_dart.mediums.bluetooth != 0;
discovery_options.common_options.allowed_mediums[NC_MEDIUM_BLE] =
options_dart.mediums.ble != 0;
discovery_options.common_options.allowed_mediums[NC_MEDIUM_WIFI_LAN] =
options_dart.mediums.wifi_lan != 0;
discovery_options.common_options.allowed_mediums[NC_MEDIUM_WIFI_HOTSPOT] =
options_dart.mediums.wifi_hotspot;
discovery_options.common_options.allowed_mediums[NC_MEDIUM_WEB_RTC] =
options_dart.mediums.web_rtc;
discovery_options.low_power = options_dart.low_power;
NC_DISCOVERY_LISTENER listener{};
listener.endpoint_distance_changed_callback =
ListenerEndpointDistanceChangedCB;
listener.endpoint_found_callback = &ListenerEndpointFoundCB;
listener.endpoint_lost_callback = &ListenerEndpointLostCB;
NC_DATA service_id_data =
NC_DATA{.size = service_id.size, .data = service_id.data};
NcStartDiscovery(instance, &service_id_data, &discovery_options, &listener,
[](NC_STATUS status) {
ResultCB(kClientState->PopNearbyConnectionsApiPort(
NearbyConnectionsApi::kStartDiscovery),
status);
});
}
void StopDiscoveryDart(NC_INSTANCE instance, Dart_Port result_cb) {
if (instance == nullptr) {
PostResult(result_cb, NC_STATUS_ERROR);
return;
}
kClientState->PushNearbyConnectionsApiPort(
NearbyConnectionsApi::kStopDiscovery, result_cb);
NcStopDiscovery(instance, [](NC_STATUS status) {
kClientState->SetDiscoveryListenerDart(nullptr);
ResultCB(kClientState->PopNearbyConnectionsApiPort(
NearbyConnectionsApi::kStopDiscovery),
status);
});
}
void RequestConnectionDart(NC_INSTANCE instance, int endpoint_id,
ConnectionOptionsDart options_dart,
ConnectionRequestInfoDart info_dart,
Dart_Port result_cb) {
if (instance == nullptr) {
PostResult(result_cb, NC_STATUS_ERROR);
return;
}
kClientState->PushNearbyConnectionsApiPort(
NearbyConnectionsApi::kRequestConnection, result_cb);
kClientState->SetConnectionListenerDart(
std::make_unique<ConnectionListenerDart>(info_dart.connection_listener));
NC_CONNECTION_OPTIONS connection_options;
connection_options.enforce_topology_constraints =
options_dart.enforce_topology_constraints;
connection_options.remote_bluetooth_mac_address.data =
options_dart.remote_bluetooth_mac_address.data;
connection_options.remote_bluetooth_mac_address.size =
options_dart.remote_bluetooth_mac_address.size;
connection_options.fast_advertisement_service_uuid.data =
options_dart.fast_advertisement_service_uuid.data;
connection_options.fast_advertisement_service_uuid.size =
options_dart.fast_advertisement_service_uuid.size;
connection_options.keep_alive_interval_millis =
options_dart.keep_alive_interval_millis;
connection_options.keep_alive_timeout_millis =
options_dart.keep_alive_timeout_millis;
connection_options.common_options.allowed_mediums[NC_MEDIUM_BLUETOOTH] =
options_dart.mediums.bluetooth != 0;
connection_options.common_options.allowed_mediums[NC_MEDIUM_BLE] =
options_dart.mediums.ble != 0;
connection_options.common_options.allowed_mediums[NC_MEDIUM_WIFI_LAN] =
options_dart.mediums.wifi_lan != 0;
connection_options.common_options.allowed_mediums[NC_MEDIUM_WIFI_HOTSPOT] =
options_dart.mediums.wifi_hotspot;
connection_options.common_options.allowed_mediums[NC_MEDIUM_WEB_RTC] =
options_dart.mediums.web_rtc;
NC_CONNECTION_REQUEST_INFO request_info{};
request_info.endpoint_info.data = info_dart.endpoint_info.data;
request_info.endpoint_info.size = info_dart.endpoint_info.size;
request_info.initiated_callback = ListenerInitiatedCB;
request_info.accepted_callback = ListenerAcceptedCB;
request_info.rejected_callback = ListenerRejectedCB;
request_info.disconnected_callback = ListenerDisconnectedCB;
request_info.bandwidth_changed_callback = ListenerBandwidthChangedCB;
NcRequestConnection(instance, endpoint_id, &request_info, &connection_options,
[](NC_STATUS status) {
ResultCB(kClientState->PopNearbyConnectionsApiPort(
NearbyConnectionsApi::kRequestConnection),
status);
});
}
void AcceptConnectionDart(NC_INSTANCE instance, int endpoint_id,
PayloadListenerDart listener_dart,
Dart_Port result_cb) {
if (instance == nullptr) {
PostResult(result_cb, NC_STATUS_ERROR);
return;
}
kClientState->PushNearbyConnectionsApiPort(
NearbyConnectionsApi::kAcceptConnection, result_cb);
kClientState->SetPayloadListenerDart(
std::make_unique<PayloadListenerDart>(listener_dart));
NC_PAYLOAD_LISTENER listener{};
listener.received_callback = &ListenerPayloadCB;
listener.progress_updated_callback = &ListenerPayloadProgressCB;
NcAcceptConnection(instance, endpoint_id, listener, [](NC_STATUS status) {
ResultCB(kClientState->PopNearbyConnectionsApiPort(
NearbyConnectionsApi::kAcceptConnection),
status);
});
}
void RejectConnectionDart(NC_INSTANCE instance, int endpoint_id,
Dart_Port result_cb) {
if (instance == nullptr) {
PostResult(result_cb, NC_STATUS_ERROR);
return;
}
kClientState->PushNearbyConnectionsApiPort(
NearbyConnectionsApi::kRejectConnection, result_cb);
NcRejectConnection(instance, endpoint_id, [](NC_STATUS status) {
ResultCB(kClientState->PopNearbyConnectionsApiPort(
NearbyConnectionsApi::kRejectConnection),
status);
});
}
void DisconnectFromEndpointDart(NC_INSTANCE instance, int endpoint_id,
Dart_Port result_cb) {
if (instance == nullptr) {
PostResult(result_cb, NC_STATUS_ERROR);
return;
}
kClientState->PushNearbyConnectionsApiPort(
NearbyConnectionsApi::kDisconnectFromEndpoint, result_cb);
NcDisconnectFromEndpoint(instance, endpoint_id, [](NC_STATUS status) {
ResultCB(kClientState->PopNearbyConnectionsApiPort(
NearbyConnectionsApi::kDisconnectFromEndpoint),
status);
});
}
void SendPayloadDart(NC_INSTANCE instance, int endpoint_id,
PayloadDart payload_dart, Dart_Port result_cb) {
if (instance == nullptr) {
PostResult(result_cb, NC_STATUS_ERROR);
return;
}
kClientState->PushNearbyConnectionsApiPort(NearbyConnectionsApi::kSendPayload,
result_cb);
std::vector<int> endpoint_ids = {endpoint_id};
NEARBY_LOGS(INFO) << "Payload type: " << payload_dart.type;
switch (payload_dart.type) {
case PAYLOAD_TYPE_UNKNOWN:
case PAYLOAD_TYPE_STREAM:
NEARBY_LOGS(INFO) << "Payload type not supported yet";
PostResult(result_cb, NC_STATUS_PAYLOADUNKNOWN);
break;
case PAYLOAD_TYPE_BYTE: {
NC_PAYLOAD payload{};
payload.id = GeneratePayloadId();
payload.type = NC_PAYLOAD_TYPE_BYTES;
payload.direction = NC_PAYLOAD_DIRECTION_INCOMING;
payload.content.bytes.content.data = payload_dart.data.data;
payload.content.bytes.content.size = payload_dart.data.size;
const int *endpoint_ids_ptr = endpoint_ids.data();
NcSendPayload(instance, endpoint_ids.size(), endpoint_ids_ptr, &payload,
[](NC_STATUS status) {
ResultCB(kClientState->PopNearbyConnectionsApiPort(
NearbyConnectionsApi::kSendPayload),
status);
});
break;
}
case PAYLOAD_TYPE_FILE:
NEARBY_LOGS(INFO) << "File name: "
<< std::string(payload_dart.data.data,
payload_dart.data.size)
<< ", size " << payload_dart.size;
std::string file_name_str(payload_dart.data.data, payload_dart.data.size);
NC_PAYLOAD payload{};
payload.id = GeneratePayloadId();
payload.type = NC_PAYLOAD_TYPE_FILE;
payload.direction = NC_PAYLOAD_DIRECTION_OUTGOING;
payload.content.file.file_name =
const_cast<char *>(file_name_str.c_str());
payload.content.file.parent_folder = nullptr;
const int *endpoint_ids_ptr = endpoint_ids.data();
NC_PAYLOAD moved_payload = std::move(payload);
NcSendPayload(instance, endpoint_ids.size(), endpoint_ids_ptr,
&moved_payload, [](NC_STATUS status) {
ResultCB(kClientState->PopNearbyConnectionsApiPort(
NearbyConnectionsApi::kSendPayload),
status);
});
break;
}
}
+198
View File
@@ -0,0 +1,198 @@
// Copyright 2024 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_DART_NC_ADAPTER_DART_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_DART_NC_ADAPTER_DART_H_
#include "third_party/dart_lang/v2/runtime/include/dart_api_dl.h"
#include "third_party/dart_lang/v2/runtime/include/dart_native_api.h"
#include "connections/c/nc.h"
#include "connections/c/nc_types.h"
#include "connections/dart/nc_adapter_def.h"
#include "connections/dart/nc_adapter_types.h"
#ifdef __cplusplus
extern "C" {
#endif
static void ResultCB(NC_STATUS status);
static void ListenerInitiatedCB(
NC_INSTANCE instance, int endpoint_id,
const NC_CONNECTION_RESPONSE_INFO &connection_response_info);
static void ListenerAcceptedCB(NC_INSTANCE instance, int endpoint_id);
static void ListenerRejectedCB(NC_INSTANCE instance, int endpoint_id,
NC_STATUS status);
static void ListenerDisconnectedCB(NC_INSTANCE instance, int endpoint_id);
static void ListenerBandwidthChangedCB(NC_INSTANCE instance, int endpoint_id,
NC_MEDIUM medium);
static void ListenerEndpointFoundCB(NC_INSTANCE instance, int endpoint_id,
const NC_DATA &endpoint_info,
const NC_DATA &service_id);
static void ListenerEndpointLostCB(NC_INSTANCE instance, int endpoint_id);
static void ListenerEndpointDistanceChangedCB(NC_INSTANCE instance,
int endpoint_id,
NC_DISTANCE_INFO distance_info);
static void ListenerPayloadCB(NC_INSTANCE instance, int endpoint_id,
const NC_PAYLOAD &payload);
static void ListenerPayloadProgressCB(
NC_INSTANCE instance, int endpoint_id,
const NC_PAYLOAD_PROGRESS_INFO &payload_progress_info);
DART_API NC_INSTANCE CreateServiceDart();
DART_API void CloseServiceDart(NC_INSTANCE instance);
DART_API int GetLocalEndpointIdDart(NC_INSTANCE instance);
DART_API void EnableBleV2Dart(NC_INSTANCE instance, int64_t enable,
Dart_Port result_cb);
// 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.
// options_dart - options for advertising
// info_dart - Including callbacks notified when remote
// endpoints request a connection to this endpoint.
// result_cb - 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.
DART_API void StartAdvertisingDart(NC_INSTANCE instance, DataDart service_id,
AdvertisingOptionsDart options_dart,
ConnectionRequestInfoDart info_dart,
Dart_Port result_cb);
// 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.
DART_API void StopAdvertisingDart(NC_INSTANCE instance, Dart_Port result_cb);
// 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.
// options - The options for discovery.
// listener - Callbacks notified when a remote endpoint is discovered.
// 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.
DART_API void StartDiscoveryDart(NC_INSTANCE instance, DataDart service_id,
DiscoveryOptionsDart options_dart,
DiscoveryListenerDart listener_dart,
Dart_Port result_cb);
// 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.
DART_API void StopDiscoveryDart(NC_INSTANCE instance, Dart_Port result_cb);
// 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()
// options_dart - The options for connection.
// info_dart - Connection parameters:
// > name - A human readable name for the local endpoint, to appear on
// the remote endpoint.
// > listener - Callbacks 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.
DART_API void RequestConnectionDart(NC_INSTANCE instance, int endpoint_id,
ConnectionOptionsDart options_dart,
ConnectionRequestInfoDart info_dart,
Dart_Port result_cb);
// 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_dart - 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.
DART_API void AcceptConnectionDart(NC_INSTANCE instance, int endpoint_id,
PayloadListenerDart listener_dart,
Dart_Port result_cb);
DART_API void RejectConnectionDart(NC_INSTANCE instance, int endpoint_id,
Dart_Port result_cb);
// 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.
DART_API void DisconnectFromEndpointDart(NC_INSTANCE instance, int endpoint_id,
Dart_Port result_cb);
// 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_id - Remote endpoint identifier 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.
DART_API void SendPayloadDart(NC_INSTANCE instance, int endpoint_id,
PayloadDart payload_dart, Dart_Port result_cb);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_DART_NC_ADAPTER_DART_H_
+31
View File
@@ -0,0 +1,31 @@
// Copyright 2024 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_DART_NC_ADAPTER_DEF_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_DART_NC_ADAPTER_DEF_H_
#ifdef _WIN32 // These storage class specifiers only matter to win32 dll
// builds.
#ifdef NC_DART_DLL
// If we're building the core, we're exporting.
#define DART_API __declspec(dllexport)
#else // !NC_DLL
// If we're not building the core, we're importing.
#define DART_API __declspec(dllimport)
#endif // NC_DLL
#else // !_WIN32
#define DART_API // We're not building a win32 dll, leave the source unchanged.
#endif // _WIN32
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_DART_NC_ADAPTER_DEF_H_
+161
View File
@@ -0,0 +1,161 @@
// Copyright 2024 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_DART_NC_ADAPTER_TYPES_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_DART_NC_ADAPTER_TYPES_H_
#include <cstdint>
#ifdef __cplusplus
extern "C" {
#endif
enum StrategyDart {
// LINT.IfChange
STRATEGY_UNKNOWN = -1,
STRATEGY_P2P_CLUSTER = 0,
STRATEGY_P2P_STAR,
STRATEGY_P2P_POINT_TO_POINT,
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/strategy.dart)
};
enum PayloadTypeDart {
// LINT.IfChange
PAYLOAD_TYPE_UNKNOWN = 0,
PAYLOAD_TYPE_BYTE,
PAYLOAD_TYPE_STREAM,
PAYLOAD_TYPE_FILE,
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/payload.dart)
};
struct MediumsDart {
// LINT.IfChange
int64_t bluetooth;
int64_t ble;
int64_t wifi_lan;
int64_t wifi_hotspot;
int64_t web_rtc;
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/mediums.dart)
};
struct DataDart {
// LINT.IfChange
int64_t size;
char *data;
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/data.dart)
};
struct AdvertisingOptionsDart {
// LINT.IfChange
StrategyDart strategy;
int64_t auto_upgrade_bandwidth;
int64_t enforce_topology_constraints;
int64_t low_power;
// Whether this is intended to be used in conjunction with InjectEndpoint().
int64_t is_out_of_band_connection = false;
DataDart fast_advertisement_service_uuid;
// The information about this device (eg. name, device type),
// to appear on the remote device.
// Defined by client/application.
DataDart device_info;
MediumsDart mediums;
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/advertising_options.dart)
};
struct ConnectionOptionsDart {
// LINT.IfChange
StrategyDart strategy;
// Whether this is intended to be used in conjunction with InjectEndpoint().
int64_t auto_upgrade_bandwidth;
int64_t enforce_topology_constraints;
int64_t low_power;
// Whether this is intended to be used in conjunction with InjectEndpoint().
int64_t is_out_of_band_connection = false;
DataDart remote_bluetooth_mac_address;
DataDart fast_advertisement_service_uuid;
int64_t keep_alive_interval_millis;
int64_t keep_alive_timeout_millis;
MediumsDart mediums;
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/connection_options.dart)
};
struct DiscoveryOptionsDart {
// LINT.IfChange
StrategyDart strategy;
int64_t auto_upgrade_bandwidth;
int64_t enforce_topology_constraints;
// Whether this is intended to be used in conjunction with InjectEndpoint().
int64_t is_out_of_band_connection = false;
DataDart fast_advertisement_service_uuid;
DataDart remote_bluetooth_mac_address;
int64_t low_power;
MediumsDart mediums;
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/discovery_options.dart)
};
struct DiscoveryListenerDart {
// LINT.IfChange
int64_t found_dart_port;
int64_t lost_dart_port;
int64_t distance_changed_dart_port;
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/discovery_listener.dart)
};
struct PayloadListenerDart {
// LINT.IfChange
int64_t initial_byte_info_port;
int64_t initial_stream_info_port;
int64_t initial_file_info_port;
int64_t payload_progress_dart_port;
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/payload_listener.dart)
};
struct ConnectionListenerDart {
// LINT.IfChange
int64_t initiated_dart_port;
int64_t accepted_dart_port;
int64_t rejected_dart_port;
int64_t disconnected_dart_port;
int64_t bandwidth_changed_dart_port;
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/connection_listener.dart)
};
struct ConnectionRequestInfoDart {
// LINT.IfChange
DataDart endpoint_info;
ConnectionListenerDart connection_listener;
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/connection_request_info.dart)
};
struct PayloadDart {
// LINT.IfChange
int64_t id;
PayloadTypeDart type;
int64_t size;
DataDart data;
// LINT.ThenChange(//depot/google3/location/nearby/apps/helloconnections/plugins/nearby_connections/platform/lib/types/payload.dart)
};
#ifdef __cplusplus
}
#endif
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_DART_NC_ADAPTER_TYPES_H_
@@ -0,0 +1,104 @@
// Copyright 2024 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/dart/nearby_connections_client_state.h"
#include <deque>
#include <memory>
#include <optional>
#include <utility>
#include "absl/synchronization/mutex.h"
#include "third_party/dart_lang/v2/runtime/include/dart_api.h"
#include "connections/c/nc_types.h"
#include "connections/dart/nc_adapter_types.h"
namespace nearby::connections::dart {
NC_INSTANCE NearbyConnectionsClientState::GetOpennedService() const {
absl::MutexLock lock(&mutex_);
return opened_instance_;
}
void NearbyConnectionsClientState::SetOpennedService(NC_INSTANCE nc_instance) {
absl::MutexLock lock(&mutex_);
opened_instance_ = nc_instance;
}
DiscoveryListenerDart*
NearbyConnectionsClientState::GetDiscoveryListenerDart() {
absl::MutexLock lock(&mutex_);
return discovery_listener_dart_.get();
}
void NearbyConnectionsClientState::SetDiscoveryListenerDart(
std::unique_ptr<DiscoveryListenerDart> discovery_listener_dart) {
absl::MutexLock lock(&mutex_);
discovery_listener_dart_ = std::move(discovery_listener_dart);
}
ConnectionListenerDart*
NearbyConnectionsClientState::GetConnectionListenerDart() {
absl::MutexLock lock(&mutex_);
return connection_listener_dart_.get();
}
void NearbyConnectionsClientState::SetConnectionListenerDart(
std::unique_ptr<ConnectionListenerDart> connection_listener_dart) {
absl::MutexLock lock(&mutex_);
connection_listener_dart_ = std::move(connection_listener_dart);
}
PayloadListenerDart* NearbyConnectionsClientState::GetPayloadListenerDart() {
absl::MutexLock lock(&mutex_);
return payload_listener_dart_.get();
}
void NearbyConnectionsClientState::SetPayloadListenerDart(
std::unique_ptr<PayloadListenerDart> payload_listener_dart) {
absl::MutexLock lock(&mutex_);
payload_listener_dart_ = std::move(payload_listener_dart);
}
std::optional<Dart_Port>
NearbyConnectionsClientState::PopNearbyConnectionsApiPort(
NearbyConnectionsApi api) {
absl::MutexLock lock(&mutex_);
std::deque<Dart_Port>& port_list = nearby_connections_api_ports_[api];
if (port_list.empty()) {
return std::nullopt;
}
Dart_Port port = port_list.front();
port_list.pop_front();
return port;
}
void NearbyConnectionsClientState::PushNearbyConnectionsApiPort(
NearbyConnectionsApi api, Dart_Port dart_port) {
absl::MutexLock lock(&mutex_);
std::deque<Dart_Port>& port_list = nearby_connections_api_ports_[api];
port_list.push_back(dart_port);
}
void NearbyConnectionsClientState::reset() {
absl::MutexLock lock(&mutex_);
opened_instance_ = nullptr;
nearby_connections_api_ports_.clear();
discovery_listener_dart_.reset();
connection_listener_dart_.reset();
payload_listener_dart_.reset();
}
} // namespace nearby::connections::dart
@@ -0,0 +1,95 @@
// Copyright 2024 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_DART_NEARBY_CONNECTIONS_CLIENT_STATE_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_DART_NEARBY_CONNECTIONS_CLIENT_STATE_H_
#include <deque>
#include <memory>
#include <optional>
#include "absl/container/flat_hash_map.h"
#include "absl/synchronization/mutex.h"
#include "third_party/dart_lang/v2/runtime/include/dart_api.h"
#include "connections/c/nc.h"
#include "connections/dart/nc_adapter_types.h"
namespace nearby::connections::dart {
// This class maintains the client state of Nearby Connections. An applicaiton
// should only maintain one client.
class NearbyConnectionsClientState {
public:
enum class NearbyConnectionsApi {
kStartAdvertising,
kStopAdvertising,
kStartDiscovery,
kStopDiscovery,
kRequestConnection,
kAcceptConnection,
kRejectConnection,
kDisconnectFromEndpoint,
kSendPayload,
kEnableBleV2
};
NearbyConnectionsClientState() = default;
NearbyConnectionsClientState(const NearbyConnectionsClientState&) = delete;
NearbyConnectionsClientState& operator=(const NearbyConnectionsClientState&) =
delete;
NC_INSTANCE GetOpennedService() const ABSL_LOCKS_EXCLUDED(mutex_);
void SetOpennedService(NC_INSTANCE nc_instance) ABSL_LOCKS_EXCLUDED(mutex_);
DiscoveryListenerDart* GetDiscoveryListenerDart() ABSL_LOCKS_EXCLUDED(mutex_);
void SetDiscoveryListenerDart(
std::unique_ptr<DiscoveryListenerDart> discovery_listener_dart)
ABSL_LOCKS_EXCLUDED(mutex_);
ConnectionListenerDart* GetConnectionListenerDart()
ABSL_LOCKS_EXCLUDED(mutex_);
void SetConnectionListenerDart(
std::unique_ptr<ConnectionListenerDart> connection_listener_dart)
ABSL_LOCKS_EXCLUDED(mutex_);
PayloadListenerDart* GetPayloadListenerDart() ABSL_LOCKS_EXCLUDED(mutex_);
void SetPayloadListenerDart(
std::unique_ptr<PayloadListenerDart> payload_listener_dart)
ABSL_LOCKS_EXCLUDED(mutex_);
std::optional<Dart_Port> PopNearbyConnectionsApiPort(NearbyConnectionsApi api)
ABSL_LOCKS_EXCLUDED(mutex_);
void PushNearbyConnectionsApiPort(NearbyConnectionsApi api,
Dart_Port dart_port)
ABSL_LOCKS_EXCLUDED(mutex_);
void reset() ABSL_LOCKS_EXCLUDED(mutex_);
private:
mutable absl::Mutex mutex_;
NC_INSTANCE opened_instance_ ABSL_GUARDED_BY(mutex_) = nullptr;
absl::flat_hash_map<NearbyConnectionsApi, std::deque<Dart_Port>>
nearby_connections_api_ports_ ABSL_GUARDED_BY(mutex_);
std::unique_ptr<DiscoveryListenerDart> discovery_listener_dart_
ABSL_GUARDED_BY(mutex_);
std::unique_ptr<ConnectionListenerDart> connection_listener_dart_
ABSL_GUARDED_BY(mutex_);
std::unique_ptr<PayloadListenerDart> payload_listener_dart_
ABSL_GUARDED_BY(mutex_);
};
} // namespace nearby::connections::dart
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_DART_NEARBY_CONNECTIONS_CLIENT_STATE_H_
+305 -35
View File
@@ -42,6 +42,7 @@ cc_library(
"p2p_star_pcp_handler.cc",
"payload_manager.cc",
"pcp_manager.cc",
"reconnect_manager.cc",
"service_controller_router.cc",
"webrtc_bwu_handler.cc",
"webrtc_bwu_handler_stub.cc",
@@ -85,6 +86,7 @@ cc_library(
"pcp.h",
"pcp_handler.h",
"pcp_manager.h",
"reconnect_manager.h",
"service_controller.h",
"service_controller_router.h",
"service_id_constants.h",
@@ -104,10 +106,11 @@ cc_library(
"-DNO_WEBRTC",
],
visibility = [
"//chrome/chromeos/assistant/data_migration/lib:__pkg__",
"//connections:__pkg__",
"//connections/implementation/fuzzers:__pkg__",
"//location/nearby/cpp/sharing/implementation:__pkg__",
"//third_party/nearby/sharing:__subpackages__",
"//connections/implementation/mediums/multiplex:__pkg__",
"//sharing:__subpackages__",
],
deps = [
"//connections:core_types",
@@ -119,6 +122,7 @@ cc_library(
"//connections/v3:v3_types",
"//internal/analytics:event_logger",
"//internal/flags:nearby_flags",
"//internal/interop:authentication_status",
"//internal/interop:authentication_transport_interface",
"//internal/interop:device",
"//internal/platform:base",
@@ -130,7 +134,8 @@ cc_library(
"//internal/platform:util",
"//internal/platform/implementation:comm",
"//internal/platform/implementation:platform",
"//internal/platform/implementation/shared:file",
"//internal/platform/implementation:types",
"//internal/platform/implementation:wifi_utils",
"//internal/proto/analytics:connections_log_cc_proto",
"//proto:connections_enums_cc_proto",
"@com_google_absl//absl/base:core_headers",
@@ -140,7 +145,8 @@ cc_library(
"@com_google_absl//absl/functional:any_invocable",
"@com_google_absl//absl/functional:bind_front",
"@com_google_absl//absl/log:check",
"@com_google_absl//absl/memory",
"@com_google_absl//absl/status",
"@com_google_absl//absl/status:statusor",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/strings:str_format",
"@com_google_absl//absl/time",
@@ -172,6 +178,7 @@ cc_library(
hdrs = [
"fake_bwu_handler.h",
"fake_endpoint_channel.h",
"mock_device.h",
"mock_service_controller.h",
"mock_service_controller_router.h",
"offline_simulation_user.h",
@@ -186,8 +193,8 @@ cc_library(
"//connections/implementation/flags:connections_flags",
"//connections/v3:v3_types",
"//internal/flags:nearby_flags",
"//internal/interop:device",
"//internal/platform:base",
"//internal/platform:test_util",
"//internal/platform:types",
"@com_google_absl//absl/functional:any_invocable",
"@com_google_absl//absl/functional:bind_front",
@@ -197,35 +204,61 @@ cc_library(
)
cc_test(
name = "core_internal_test",
size = "small",
timeout = "moderate",
name = "bwu_test",
srcs = [
"base_bwu_handler_test.cc",
"base_endpoint_channel_test.cc",
"base_pcp_handler_test.cc",
"ble_advertisement_test.cc",
"bluetooth_device_name_test.cc",
"bluetooth_bwu_test.cc",
"bwu_manager_test.cc",
"client_proxy_test.cc",
"connections_authentication_transport_test.cc",
"encryption_runner_test.cc",
"endpoint_channel_manager_test.cc",
"endpoint_manager_test.cc",
"injected_bluetooth_device_store_test.cc",
"internal_payload_factory_test.cc",
"offline_frames_validator_test.cc",
"offline_service_controller_test.cc",
"wifi_direct_bwu_test.cc",
"wifi_hotspot_bwu_test.cc",
],
deps = [
":internal",
":internal_test",
"//connections:core_types",
"//connections/implementation/flags:connections_flags",
"//connections/implementation/mediums",
"//internal/flags:nearby_flags",
"//internal/platform:base",
"//internal/platform:test_util",
"//internal/platform:types",
"//internal/platform/implementation/g3", # build_cleaner: keep
"//internal/proto/analytics:connections_log_cc_proto",
"//proto:connections_enums_cc_proto",
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/time",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "pcp_manager_test",
srcs = ["pcp_manager_test.cc"],
deps = [
":internal",
":internal_test",
"//connections:core_types",
"//connections/v3:v3_types",
"//internal/platform:base",
"//internal/platform:test_util",
"//internal/platform:types",
"//internal/platform/implementation/g3", # build_cleaner: keep
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/time",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "pcp_handler_test",
timeout = "moderate",
srcs = [
"base_pcp_handler_test.cc",
"p2p_cluster_pcp_handler_test.cc",
"p2p_point_to_point_pcp_handler_test.cc",
"payload_manager_test.cc",
"pcp_manager_test.cc",
"service_controller_router_test.cc",
"wifi_direct_bwu_test.cc",
"wifi_hotspot_test.cc",
"wifi_lan_service_info_test.cc",
],
shard_count = 16,
shard_count = 8,
deps = [
":internal",
":internal_test",
@@ -235,27 +268,264 @@ cc_test(
"//connections/implementation/mediums",
"//connections/implementation/proto:offline_wire_formats_cc_proto",
"//connections/v3:v3_types",
"//internal/analytics:event_logger",
"//internal/flags:nearby_flags",
"//internal/interop:authentication_status",
"//internal/interop:authentication_transport_interface",
"//internal/interop:device",
"//internal/platform:base",
"//internal/platform:comm",
"//internal/platform:test_util",
"//internal/platform:types",
"//internal/platform/implementation/g3", # build_cleaner: keep
"//internal/proto/analytics:connections_log_cc_proto",
"//internal/test",
"//proto:connections_enums_cc_proto",
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/base:core_headers",
"@com_google_absl//absl/container:flat_hash_set",
"@com_google_absl//absl/strings:string_view",
"@com_google_absl//absl/time",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "advertisement_test",
srcs = [
"ble_advertisement_test.cc",
"bluetooth_device_name_test.cc",
"wifi_lan_service_info_test.cc",
],
deps = [
":internal",
"//internal/platform:base",
"//internal/platform/implementation/g3", # build_cleaner: keep
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/status",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "offline_frames_test",
srcs = ["offline_frames_validator_test.cc"],
deps = [
":internal",
"//connections/implementation/flags:connections_flags",
"//connections/implementation/proto:offline_wire_formats_cc_proto",
"//internal/flags:nearby_flags",
"//internal/platform:base",
"//internal/platform/implementation/g3", # build_cleaner: keep
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/strings",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "client_proxy_test",
srcs = [
"client_proxy_test.cc",
],
deps = [
":internal",
"//base:casts",
"//connections:core_types",
"//connections/implementation/flags:connections_flags",
"//connections/v3:v3_types",
"//internal/analytics:mock_event_logger",
"//internal/flags:nearby_flags",
"//internal/interop:device",
"//internal/platform:base",
"//internal/platform:cancellation_flag",
"//internal/platform:test_util",
"//internal/platform:types",
"//internal/platform/implementation/g3", # build_cleaner: keep
"//proto:connections_enums_cc_proto",
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/strings:str_format",
"@com_google_absl//absl/synchronization",
"@com_google_absl//absl/time",
"@com_google_absl//absl/types:span",
"@com_google_googletest//:gtest",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "encryption_runner_test",
srcs = [
"encryption_runner_test.cc",
],
deps = [
":internal",
"//connections/implementation/analytics",
"//internal/platform:base",
"//internal/platform:types",
"//internal/platform/implementation/g3", # build_cleaner: keep
"//proto:connections_enums_cc_proto",
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/time",
"@com_google_googletest//:gtest_main",
"@com_google_ukey2//:ukey2",
],
)
cc_test(
name = "endpoint_manager_test",
srcs = [
"endpoint_manager_test.cc",
],
deps = [
":internal",
"//connections:core_types",
"//connections/implementation/analytics",
"//connections/implementation/flags:connections_flags",
"//internal/flags:nearby_flags",
"//internal/platform:base",
"//internal/platform:types",
"//internal/platform/implementation/g3", # build_cleaner: keep
"//internal/test",
"//proto:connections_enums_cc_proto",
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/synchronization",
"@com_google_absl//absl/time",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "endpoint_channel_test",
srcs = [
"base_endpoint_channel_test.cc",
"endpoint_channel_manager_test.cc",
],
deps = [
":internal",
"//internal/platform:base",
"//internal/platform:types",
"//internal/platform/implementation/g3", # build_cleaner: keep
"//internal/proto/analytics:connections_log_cc_proto",
"//proto:connections_enums_cc_proto",
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/synchronization",
"@com_google_absl//absl/time",
"@com_google_googletest//:gtest_main",
"@com_google_ukey2//:ukey2",
],
)
cc_test(
name = "connections_authentication_transport_test",
srcs = [
"connections_authentication_transport_test.cc",
],
deps = [
":internal",
"//connections/implementation/analytics",
"//internal/platform:base",
"//internal/platform/implementation/g3", # build_cleaner: keep
"//proto:connections_enums_cc_proto",
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/time",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "payload_manager_test",
srcs = [
"payload_manager_test.cc",
],
deps = [
":internal",
":internal_test",
"//connections:core_types",
"//connections/implementation/analytics",
"//connections/implementation/flags:connections_flags",
"//internal/flags:nearby_flags",
"//internal/platform:base",
"//internal/platform:test_util",
"//internal/platform:types",
"//internal/platform/implementation/g3", # build_cleaner: keep
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/time",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "reconnect_manager_test",
srcs = [
"reconnect_manager_test.cc",
],
deps = [
":internal",
":internal_test",
"//connections:core_types",
"//connections/implementation/mediums",
"//internal/platform:test_util",
"//internal/platform:types",
"//internal/platform/implementation/g3", # build_cleaner: keep
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/strings:string_view",
"@com_google_absl//absl/time",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "service_controller_test",
srcs = [
"offline_service_controller_test.cc",
"service_controller_router_test.cc",
],
deps = [
":internal",
":internal_test",
"//connections:core_types",
"//connections/implementation/flags:connections_flags",
"//connections/v3:v3_types",
"//internal/flags:nearby_flags",
"//internal/interop:authentication_status",
"//internal/platform:base",
"//internal/platform:test_util",
"//internal/platform:types",
"//internal/platform/implementation/g3", # build_cleaner: keep
"//proto:connections_enums_cc_proto",
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/strings:string_view",
"@com_google_absl//absl/time",
"@com_google_absl//absl/types:span",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "injected_bluetooth_device_store_test",
srcs = [
"injected_bluetooth_device_store_test.cc",
],
deps = [
":internal",
"//internal/platform:base",
"//internal/platform:comm",
"//internal/platform/implementation/g3", # build_cleaner: keep
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "internal_payload_factory_test",
srcs = [
"internal_payload_factory_test.cc",
],
deps = [
":internal",
"//connections:core_types",
"//connections/implementation/proto:offline_wire_formats_cc_proto",
"//internal/platform:base",
"//internal/platform:types",
"//internal/platform/implementation/g3", # build_cleaner: keep
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_googletest//:gtest_main",
],
)
+2 -3
View File
@@ -43,6 +43,7 @@ cc_library(
"@com_google_absl//absl/strings",
"@com_google_absl//absl/strings:str_format",
"@com_google_absl//absl/time",
"@com_google_protobuf//:protobuf_lite",
],
)
@@ -56,16 +57,14 @@ cc_test(
shard_count = 16,
deps = [
":analytics",
"//internal/analytics:event_logger",
"//internal/analytics:mock_event_logger",
"//internal/platform:base",
"//internal/platform:comm",
"//internal/platform:error_code_recorder",
"//internal/platform:types",
"//internal/platform/implementation/g3", # build_cleaner: keep
"//internal/proto/analytics:connections_log_cc_proto",
"//net/proto2/contrib/parse_proto:parse_text_proto",
"//proto:connections_enums_cc_proto",
"//third_party/protobuf:protobuf_lite",
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/time",
"@com_google_googletest//:gtest_main",
@@ -27,6 +27,9 @@
#include "absl/container/btree_map.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "connections/implementation/analytics/connection_attempt_metadata_params.h"
#include "connections/payload_type.h"
#include "connections/strategy.h"
#include "internal/analytics/event_logger.h"
#include "internal/platform/count_down_latch.h"
#include "internal/platform/error_code_params.h"
@@ -36,6 +39,7 @@
#include "internal/platform/single_thread_executor.h"
#include "internal/proto/analytics/connections_log.pb.h"
#include "proto/connections_enums.pb.h"
#include "google/protobuf/repeated_ptr_field.h"
namespace nearby {
namespace analytics {
@@ -43,6 +47,7 @@ namespace analytics {
namespace {
const char kVersion[] = "v1.0.0";
constexpr absl::string_view kOnStartClientSession = "OnStartClientSession";
const absl::Duration kConnectionTokenMaxLife = absl::Hours(24);
} // namespace
using ::location::nearby::analytics::proto::ConnectionsLog;
@@ -95,6 +100,8 @@ using ::location::nearby::proto::connections::UPGRADE_SUCCESS;
using ::location::nearby::proto::connections::UPGRADE_UNFINISHED;
using ::location::nearby::proto::connections::UPGRADED;
using ::nearby::analytics::EventLogger;
using SafeDisconnectionResult = ::location::nearby::analytics::proto::
ConnectionsLog::EstablishedConnection::SafeDisconnectionResult;
AnalyticsRecorder::AnalyticsRecorder(EventLogger *event_logger)
: event_logger_(event_logger) {
@@ -475,21 +482,23 @@ void AnalyticsRecorder::OnConnectionEstablished(
void AnalyticsRecorder::OnConnectionClosed(const std::string &endpoint_id,
Medium medium,
DisconnectionReason reason) {
DisconnectionReason reason,
SafeDisconnectionResult result) {
MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__
<< ": OnConnectionClosed is called with endpoint_id:"
<< endpoint_id << ", medium:" << Medium_Name(medium)
<< ", reason:" << DisconnectionReason_Name(reason);
<< ", reason:" << DisconnectionReason_Name(reason)
<< ", result:" << result;
if (!CanRecordAnalyticsLocked("OnConnectionClosed")) {
return;
}
if (current_strategy_session_ == nullptr) {
NEARBY_LOGS(VERBOSE)
<< "AnalyticsRecorder CanRecordAnalytics Unexpected call " << __func__
<< " since current_strategy_session_ is required.";
NEARBY_VLOG(1) << "AnalyticsRecorder CanRecordAnalytics Unexpected call "
<< __func__
<< " since current_strategy_session_ is required.";
return;
}
@@ -498,7 +507,7 @@ void AnalyticsRecorder::OnConnectionClosed(const std::string &endpoint_id,
return;
}
const std::unique_ptr<LogicalConnection> &logical_connection = it->second;
logical_connection->PhysicalConnectionClosed(medium, reason);
logical_connection->PhysicalConnectionClosed(medium, reason, result);
if (reason != UPGRADED) {
// Unless this is an upgraded connection, remove this from our active
// connections. Any future communication with an endpoint will need to be
@@ -703,9 +712,8 @@ void AnalyticsRecorder::OnErrorCode(const ErrorCodeParams &params) {
connections_log.set_version(kVersion);
connections_log.set_allocated_error_code(error_code);
NEARBY_LOGS(VERBOSE)
<< "AnalyticsRecorder LogErrorCode connections_log="
<< connections_log.DebugString();
NEARBY_VLOG(1) << "AnalyticsRecorder LogErrorCode connections_log="
<< connections_log.DebugString(); // NOLINT
event_logger_->Log(connections_log);
});
@@ -767,16 +775,15 @@ AnalyticsRecorder::BuildConnectionAttemptMetadataParams(
bool AnalyticsRecorder::CanRecordAnalyticsLocked(
absl::string_view method_name) {
NEARBY_LOGS(VERBOSE) << "AnalyticsRecorder LogEvent " << method_name
<< " is calling.";
NEARBY_VLOG(1) << "AnalyticsRecorder LogEvent " << method_name
<< " is calling.";
if (event_logger_ == nullptr) {
return false;
}
if (session_was_logged_) {
NEARBY_LOGS(VERBOSE)
<< "AnalyticsRecorder CanRecordAnalytics Unexpected call "
<< method_name << " after session has already been logged.";
NEARBY_VLOG(1) << "AnalyticsRecorder CanRecordAnalytics Unexpected call "
<< method_name << " after session has already been logged.";
return false;
}
@@ -792,9 +799,8 @@ void AnalyticsRecorder::LogClientSessionLocked() {
connections_log.set_allocated_client_session(client_session.release());
connections_log.set_version(kVersion);
NEARBY_LOGS(VERBOSE)
<< "AnalyticsRecorder LogClientSession connections_log="
<< connections_log.DebugString();
NEARBY_VLOG(1) << "AnalyticsRecorder LogClientSession connections_log="
<< connections_log.DebugString(); // NOLINT
event_logger_->Log(connections_log);
});
@@ -807,8 +813,8 @@ void AnalyticsRecorder::LogEvent(EventType event_type) {
connections_log.set_event_type(event_type);
connections_log.set_version(kVersion);
NEARBY_LOGS(VERBOSE) << "AnalyticsRecorder LogEvent connections_log="
<< connections_log.DebugString();
NEARBY_VLOG(1) << "AnalyticsRecorder LogEvent connections_log="
<< connections_log.DebugString(); // NOLINT
event_logger_->Log(connections_log);
});
@@ -1127,7 +1133,7 @@ void AnalyticsRecorder::LogicalConnection::PhysicalConnectionEstablished(
}
void AnalyticsRecorder::LogicalConnection::PhysicalConnectionClosed(
Medium medium, DisconnectionReason reason) {
Medium medium, DisconnectionReason reason, SafeDisconnectionResult result) {
if (current_medium_ == UNKNOWN_MEDIUM) {
NEARBY_LOGS(WARNING)
<< "Unexpected call to PhysicalConnectionClosed() for medium "
@@ -1159,7 +1165,7 @@ void AnalyticsRecorder::LogicalConnection::PhysicalConnectionClosed(
established_connection->disconnection_reason());
return;
}
FinishPhysicalConnection(established_connection, reason);
FinishPhysicalConnection(established_connection, reason, result);
if (medium == current_medium_) {
// If the EstablishedConnection we just closed was the one that we have
@@ -1173,7 +1179,9 @@ void AnalyticsRecorder::LogicalConnection::CloseAllPhysicalConnections() {
ConnectionsLog::EstablishedConnection *established_connection =
physical_connection.second.get();
if (!established_connection->has_disconnection_reason()) {
FinishPhysicalConnection(established_connection, UNFINISHED);
FinishPhysicalConnection(
established_connection, UNFINISHED,
ConnectionsLog::EstablishedConnection::SAFE_DISCONNECTION);
}
}
current_medium_ = UNKNOWN_MEDIUM;
@@ -1192,6 +1200,15 @@ AnalyticsRecorder::LogicalConnection::GetEstablisedConnections() {
std::back_inserter(established_connections),
[](auto &kv) { return *kv.second; });
physical_connections_.clear();
for (auto &established_connection : established_connections) {
if (absl::Milliseconds(established_connection.duration_millis()) >=
kConnectionTokenMaxLife) {
NEARBY_LOGS(INFO) << "connection token exceed TTL, drop token.";
established_connection.set_connection_token("");
}
}
return established_connections;
}
@@ -1269,8 +1286,9 @@ void AnalyticsRecorder::LogicalConnection::OutgoingPayloadDone(
void AnalyticsRecorder::LogicalConnection::FinishPhysicalConnection(
ConnectionsLog::EstablishedConnection *established_connection,
DisconnectionReason reason) {
DisconnectionReason reason, SafeDisconnectionResult result) {
established_connection->set_disconnection_reason(reason);
established_connection->set_safe_disconnection_result(result);
established_connection->set_duration_millis(
absl::ToUnixMillis(SystemClock::ElapsedRealtime()) -
established_connection->duration_millis());
@@ -119,7 +119,7 @@ class AnalyticsRecorder {
bool wifi_hotspot_enabled = false, int max_wifi_tx_speed = 0,
int max_wifi_rx_speed = 0, int channel_width = -1);
// Connection established
// Connection establishedSafeDisconnectionResult
void OnConnectionEstablished(
const std::string &endpoint_id,
location::nearby::proto::connections::Medium medium,
@@ -127,7 +127,9 @@ class AnalyticsRecorder {
void OnConnectionClosed(
const std::string &endpoint_id,
location::nearby::proto::connections::Medium medium,
location::nearby::proto::connections ::DisconnectionReason reason)
location::nearby::proto::connections::DisconnectionReason reason,
location::nearby::analytics::proto::ConnectionsLog::
EstablishedConnection::SafeDisconnectionResult result)
ABSL_LOCKS_EXCLUDED(mutex_);
// Payload
@@ -246,7 +248,9 @@ class AnalyticsRecorder {
const std::string &connection_token);
void PhysicalConnectionClosed(
location::nearby::proto::connections::Medium medium,
location::nearby::proto::connections::DisconnectionReason reason);
location::nearby::proto::connections::DisconnectionReason reason,
location::nearby::analytics::proto::ConnectionsLog::
EstablishedConnection::SafeDisconnectionResult result);
void CloseAllPhysicalConnections();
void IncomingPayloadStarted(
@@ -274,7 +278,9 @@ class AnalyticsRecorder {
void FinishPhysicalConnection(
location::nearby::analytics::proto::ConnectionsLog::
EstablishedConnection *established_connection,
location::nearby::proto::connections::DisconnectionReason reason);
location::nearby::proto::connections::DisconnectionReason reason,
location::nearby::analytics::proto::ConnectionsLog::
EstablishedConnection::SafeDisconnectionResult result);
std::vector<location::nearby::analytics::proto::ConnectionsLog::Payload>
ResolvePendingPayloads(
absl::btree_map<std::int64_t, std::unique_ptr<PendingPayload>>
@@ -17,7 +17,6 @@
#include <stddef.h>
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
@@ -25,16 +24,14 @@
#include "gmock/gmock.h"
#include "protobuf-matchers/protocol-buffer-matchers.h"
#include "gtest/gtest.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "internal/analytics/event_logger.h"
#include "internal/analytics/mock_event_logger.h"
#include "internal/platform/count_down_latch.h"
#include "internal/platform/error_code_params.h"
#include "internal/platform/error_code_recorder.h"
#include "internal/platform/exception.h"
#include "internal/proto/analytics/connections_log.proto.h"
#include "proto/connections_enums.proto.h"
#include "third_party/protobuf/message_lite.h"
namespace nearby {
namespace analytics {
@@ -70,7 +67,7 @@ using ::location::nearby::proto::connections::WEB_RTC;
using ::location::nearby::proto::connections::WIFI_LAN;
using ::location::nearby::proto::connections::WIFI_LAN_MEDIUM_ERROR;
using ::location::nearby::proto::connections::WIFI_LAN_SOCKET_CREATION;
using ::nearby::analytics::EventLogger;
using ::nearby::analytics::MockEventLogger;
using ::proto2::contrib::parse_proto::ParseTextProtoOrDie;
using ::testing::Contains;
using ::protobuf_matchers::EqualsProto;
@@ -79,7 +76,7 @@ using ::testing::proto::Partially;
constexpr absl::Duration kDefaultTimeout = absl::Milliseconds(1000);
class FakeEventLogger : public EventLogger {
class FakeEventLogger : public MockEventLogger {
public:
explicit FakeEventLogger(CountDownLatch& client_session_done_latch)
: client_session_done_latch_(client_session_done_latch) {}
@@ -90,20 +87,15 @@ class FakeEventLogger : public EventLogger {
start_client_session_done_latch_ptr_(
start_client_session_done_latch_ptr) {}
void Log(const ::google::protobuf::MessageLite& message) override {
auto connections_log = dynamic_cast<const ConnectionsLog*>(&message);
if (connections_log == nullptr) {
return;
}
EventType event_type = connections_log->event_type();
void Log(const ConnectionsLog& message) override {
EventType event_type = message.event_type();
logged_event_types_.push_back(event_type);
if (event_type == CLIENT_SESSION) {
logged_client_session_count_++;
logged_client_session_ = connections_log->client_session();
logged_client_session_ = message.client_session();
}
if (event_type == ERROR_CODE) {
error_code_ = connections_log->error_code();
error_code_ = message.error_code();
}
if (event_type == STOP_CLIENT_SESSION) {
client_session_done_latch_.CountDown();
@@ -742,7 +734,9 @@ TEST(AnalyticsRecorderTest, UnfinishedEstablishedConnectionsAddedAsUnfinished) {
/*mediums=*/{BLE, BLUETOOTH});
analytics_recorder.OnConnectionEstablished(endpoint_id, BLUETOOTH,
connection_token);
analytics_recorder.OnConnectionClosed(endpoint_id, BLUETOOTH, UPGRADED);
analytics_recorder.OnConnectionClosed(
endpoint_id, BLUETOOTH, UPGRADED, ConnectionsLog::EstablishedConnection::
UNKNOWN_SAFE_DISCONNECTION_RESULT);
analytics_recorder.OnConnectionEstablished(endpoint_id, WIFI_LAN,
connection_token);
@@ -796,7 +790,9 @@ TEST(AnalyticsRecorderTest, OutgoingPayloadUpgraded) {
{endpoint_id}, payload_id, connections::PayloadType::kFile, 50);
analytics_recorder.OnPayloadChunkSent(endpoint_id, payload_id, 10);
analytics_recorder.OnPayloadChunkSent(endpoint_id, payload_id, 10);
analytics_recorder.OnConnectionClosed(endpoint_id, BLUETOOTH, UPGRADED);
analytics_recorder.OnConnectionClosed(
endpoint_id, BLUETOOTH, UPGRADED,
ConnectionsLog::EstablishedConnection::SAFE_DISCONNECTION);
analytics_recorder.OnConnectionEstablished(endpoint_id, WIFI_LAN,
connection_token);
analytics_recorder.OnPayloadChunkSent(endpoint_id, payload_id, 10);
@@ -804,7 +800,9 @@ TEST(AnalyticsRecorderTest, OutgoingPayloadUpgraded) {
analytics_recorder.OnPayloadChunkSent(endpoint_id, payload_id, 10);
analytics_recorder.OnOutgoingPayloadDone(endpoint_id, payload_id, SUCCESS);
analytics_recorder.OnConnectionClosed(endpoint_id, WIFI_LAN,
LOCAL_DISCONNECTION);
LOCAL_DISCONNECTION,
ConnectionsLog::EstablishedConnection::
SAFE_DISCONNECTION);
analytics_recorder.LogSession();
ASSERT_TRUE(client_session_done_latch.Await(kDefaultTimeout).result());
@@ -1907,7 +1905,9 @@ TEST(AnalyticsRecorderOnConnectionClosedTest,
// current_strategy_session_.
analytics_recorder.OnConnectionEstablished(endpoint_id, BLUETOOTH,
/*connection_token=*/"");
analytics_recorder.OnConnectionClosed(endpoint_id, BLUETOOTH, UPGRADED);
analytics_recorder.OnConnectionClosed(
endpoint_id, BLUETOOTH, UPGRADED,
ConnectionsLog::EstablishedConnection::SAFE_DISCONNECTION);
analytics_recorder.LogSession();
@@ -20,6 +20,7 @@
#include <utility>
#include "absl/strings/str_cat.h"
#include "connections/implementation/endpoint_channel_manager.h"
#include "connections/implementation/offline_frames.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/exception.h"
@@ -31,6 +32,9 @@ namespace nearby {
namespace connections {
namespace {
using ::location::nearby::analytics::proto::ConnectionsLog;
using DisconnectionReason =
::location::nearby::proto::connections::DisconnectionReason;
std::int32_t BytesToInt(const ByteArray& bytes) {
const char* int_bytes = bytes.data();
@@ -135,6 +139,7 @@ ExceptionOr<ByteArray> BaseEndpointChannel::Read(
{
MutexLock crypto_lock(&crypto_mutex_);
Exception message_exception{Exception::kInvalidProtocolBuffer};
if (IsEncryptionEnabledLocked()) {
// If encryption is enabled, decode the message.
std::string input(std::move(result));
@@ -165,6 +170,7 @@ ExceptionOr<ByteArray> BaseEndpointChannel::Read(
<< parser::GetFrameType(parsed.result());
}
} else {
message_exception.value = parsed.exception();
NEARBY_LOGS(WARNING)
<< __func__ << ": Unable to parse data as unencrypted message.";
}
@@ -172,7 +178,7 @@ ExceptionOr<ByteArray> BaseEndpointChannel::Read(
packet_meta_data.StopEncryption();
if (result.Empty()) {
NEARBY_LOGS(WARNING) << __func__ << ": Unable to parse read result.";
return ExceptionOr<ByteArray>(Exception::kInvalidProtocolBuffer);
return ExceptionOr<ByteArray>(message_exception);
}
}
}
@@ -266,7 +272,7 @@ void BaseEndpointChannel::Close() {
// In case channel is paused, resume it first thing.
MutexLock lock(&is_paused_mutex_);
if (is_closed_) {
NEARBY_LOGS(VERBOSE) << "EndpointChannel already closed";
NEARBY_VLOG(1) << "EndpointChannel already closed";
return;
}
is_closed_ = true;
@@ -309,12 +315,19 @@ void BaseEndpointChannel::SetAnalyticsRecorder(
void BaseEndpointChannel::Close(
location::nearby::proto::connections::DisconnectionReason reason) {
Close(reason, ConnectionsLog::EstablishedConnection::SAFE_DISCONNECTION);
}
void BaseEndpointChannel::Close(
location::nearby::proto::connections::DisconnectionReason reason,
SafeDisconnectionResult result) {
NEARBY_LOGS(INFO) << __func__
<< ": Closing endpoint channel, reason: " << reason;
Close();
if (analytics_recorder_ != nullptr && !endpoint_id_.empty()) {
analytics_recorder_->OnConnectionClosed(endpoint_id_, GetMedium(), reason);
analytics_recorder_->OnConnectionClosed(endpoint_id_, GetMedium(), reason,
result);
}
}
@@ -28,6 +28,7 @@
#include "internal/platform/input_stream.h"
#include "internal/platform/mutex.h"
#include "internal/platform/output_stream.h"
#include "internal/platform/socket.h"
namespace nearby {
namespace connections {
@@ -58,6 +59,10 @@ class BaseEndpointChannel : public EndpointChannel {
void Close() ABSL_LOCKS_EXCLUDED(is_paused_mutex_) override;
void Close(location::nearby::proto::connections::DisconnectionReason reason)
override;
void Close(
location::nearby::proto::connections::DisconnectionReason reason,
location::nearby::analytics::proto::ConnectionsLog::
EstablishedConnection::SafeDisconnectionResult result) override;
std::string GetType() const override;
std::string GetServiceId() const override;
std::string GetName() const override;
@@ -58,7 +58,7 @@ class TestEndpointChannel : public BaseEndpointChannel {
using BaseEndpointChannel::EncodeMessageForTests;
MOCK_METHOD(Medium, GetMedium, (), (const override));
MOCK_METHOD(Medium, GetMedium, (), (const, override));
MOCK_METHOD(void, CloseImpl, (), (override));
};
+531 -104
View File
@@ -1,4 +1,4 @@
// Copyright 2021 Google LLC
// Copyright 2021-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.
@@ -15,6 +15,7 @@
#include "connections/implementation/base_pcp_handler.h"
#include <algorithm>
#include <cstdint>
#include <memory>
#include <sstream>
#include <string>
@@ -22,32 +23,61 @@
#include <vector>
#include "securegcm/ukey2_handshake.h"
#include "absl/base/thread_annotations.h"
#include "absl/container/btree_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "connections/advertising_options.h"
#include "connections/connection_options.h"
#include "connections/implementation/endpoint_channel_manager.h"
#include "connections/discovery_options.h"
#include "connections/implementation/analytics/connection_attempt_metadata_params.h"
#include "connections/implementation/bwu_manager.h"
#include "connections/implementation/client_proxy.h"
#include "connections/implementation/connections_authentication_transport.h"
#include "connections/implementation/encryption_runner.h"
#include "connections/implementation/endpoint_channel.h"
#include "connections/implementation/endpoint_channel_manager.h"
#include "connections/implementation/endpoint_manager.h"
#include "connections/implementation/flags/nearby_connections_feature_flags.h"
#include "connections/implementation/mediums/mediums.h"
#include "connections/implementation/mediums/utils.h"
#include "connections/implementation/mediums/webrtc_peer_id.h"
#include "connections/implementation/offline_frames.h"
#include "connections/implementation/pcp.h"
#include "connections/implementation/proto/offline_wire_formats.pb.h"
#include "connections/listeners.h"
#include "connections/medium_selector.h"
#include "connections/out_of_band_connection_metadata.h"
#include "connections/params.h"
#include "connections/status.h"
#include "connections/v3/connection_listening_options.h"
#include "connections/v3/listeners.h"
#include "internal/flags/nearby_flags.h"
#include "internal/interop/authentication_status.h"
#include "internal/interop/device.h"
#include "internal/interop/device_provider.h"
#include "internal/platform/base64_utils.h"
#include "internal/platform/bluetooth_adapter.h"
#include "internal/platform/bluetooth_connection_info.h"
#include "internal/platform/bluetooth_utils.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/cancelable_alarm.h"
#include "internal/platform/connection_info.h"
#include "internal/platform/count_down_latch.h"
#include "internal/platform/exception.h"
#include "internal/platform/feature_flags.h"
#include "internal/platform/future.h"
#include "internal/platform/implementation/system_clock.h"
#include "internal/platform/implementation/wifi.h"
#include "internal/platform/logging.h"
#include "internal/platform/mutex_lock.h"
#include "internal/platform/prng.h"
#include "internal/platform/runnable.h"
#include "internal/platform/wifi.h"
#include "internal/platform/wifi_lan_connection_info.h"
#include "proto/connections_enums.pb.h"
@@ -55,7 +85,20 @@ namespace nearby {
namespace connections {
namespace {
constexpr int kEndpointCancelAlarmTimeout = 10;
std::string AuthenticationStatusToString(nearby::AuthenticationStatus status) {
switch (status) {
case AuthenticationStatus::kUnknown:
return "unknown";
case AuthenticationStatus::kSuccess:
return "success";
case AuthenticationStatus::kFailure:
return "failure";
}
}
} // namespace
using ::location::nearby::connections::ConnectionRequestFrame;
@@ -81,7 +124,7 @@ BasePcpHandler::BasePcpHandler(Mediums* mediums,
bwu_manager_(bwu_manager) {}
BasePcpHandler::~BasePcpHandler() {
NEARBY_LOGS(VERBOSE) << __func__;
NEARBY_VLOG(1) << __func__;
Shutdown();
}
@@ -186,20 +229,34 @@ Status BasePcpHandler::StartAdvertising(
"start-advertising",
[this, client, &service_id, &info, &compatible_advertising_options,
&response]() RUN_ON_PCP_HANDLER_THREAD() {
// The endpoint id inside of the advertisement is different to high
// visibility and low visibility mode. In order to decide if client
// should grab the high visibility or low visibility id, it needs to
// tell client which one right now, before
// client#StartedAdvertising.
if (ShouldEnterHighVisibilityMode(compatible_advertising_options)) {
client->EnterHighVisibilityMode();
if (NearbyFlags::GetInstance().GetBoolFlag(
connections::config_package_nearby::nearby_connections_feature::
kUseStableEndpointId)) {
if (ShouldEnterStableEndpointIdMode(compatible_advertising_options)) {
client->EnterStableEndpointIdMode();
}
} else {
// The endpoint id inside of the advertisement is different to high
// visibility and low visibility mode. In order to decide if client
// should grab the high visibility or low visibility id, it needs to
// tell client which one right now, before
// client#StartedAdvertising.
if (ShouldEnterHighVisibilityMode(compatible_advertising_options)) {
client->EnterHighVisibilityMode();
}
}
auto result = StartAdvertisingImpl(
client, service_id, client->GetLocalEndpointId(),
info.endpoint_info, compatible_advertising_options);
if (!result.status.Ok()) {
client->ExitHighVisibilityMode();
if (NearbyFlags::GetInstance().GetBoolFlag(
connections::config_package_nearby::
nearby_connections_feature::kUseStableEndpointId)) {
client->ExitStableEndpointIdMode();
} else {
client->ExitHighVisibilityMode();
}
response.Set(result.status);
return;
}
@@ -292,6 +349,17 @@ bool BasePcpHandler::ShouldEnterHighVisibilityMode(
advertising_options.allowed.bluetooth;
}
bool BasePcpHandler::ShouldEnterStableEndpointIdMode(
const AdvertisingOptions& advertising_options) {
if (advertising_options.use_stable_endpoint_id) {
return true;
} else if (advertising_options.low_power) {
return false;
} else {
return true;
}
}
BooleanMediumSelector BasePcpHandler::ComputeIntersectionOfSupportedMediums(
const PendingConnectionInfo& connection_info) {
absl::flat_hash_set<Medium> intersection;
@@ -353,7 +421,7 @@ BooleanMediumSelector BasePcpHandler::ComputeIntersectionOfSupportedMediums(
Status BasePcpHandler::StartDiscovery(ClientProxy* client,
const std::string& service_id,
const DiscoveryOptions& discovery_options,
const DiscoveryListener& listener) {
DiscoveryListener listener) {
Future<Status> response;
DiscoveryOptions stripped_discovery_options = discovery_options;
StripOutUnavailableMediums(stripped_discovery_options);
@@ -362,9 +430,9 @@ Status BasePcpHandler::StartDiscovery(ClientProxy* client,
stripped_discovery_options);
RunOnPcpHandlerThread(
"start-discovery",
[this, client, service_id, stripped_discovery_options, &listener,
&response]() RUN_ON_PCP_HANDLER_THREAD()
ABSL_LOCKS_EXCLUDED(discovered_endpoint_mutex_) {
[this, client, service_id, stripped_discovery_options,
listener = std::move(listener), &response]() RUN_ON_PCP_HANDLER_THREAD()
ABSL_LOCKS_EXCLUDED(discovered_endpoint_mutex_) mutable {
// Ask the implementation to attempt to start discovery.
auto result = StartDiscoveryImpl(client, service_id,
stripped_discovery_options);
@@ -379,9 +447,9 @@ Status BasePcpHandler::StartDiscovery(ClientProxy* client,
MutexLock lock(&discovered_endpoint_mutex_);
discovered_endpoints_.clear();
}
client->StartedDiscovery(service_id, GetStrategy(), listener,
absl::MakeSpan(result.mediums),
stripped_discovery_options);
client->StartedDiscovery(
service_id, GetStrategy(), std::move(listener),
absl::MakeSpan(result.mediums), stripped_discovery_options);
response.Set({Status::kSuccess});
});
return WaitForResult(absl::StrCat("StartDiscovery(", service_id, ")"),
@@ -480,11 +548,115 @@ EncryptionRunner::ResultListener BasePcpHandler::GetResultListener() {
};
}
EncryptionRunner::ResultListener BasePcpHandler::GetResultListenerV3(
const NearbyDeviceProvider& device_provider,
const NearbyDevice& remote_device,
const EndpointChannel& endpoint_channel) {
return {
.on_success_cb =
[this, &device_provider, &remote_device, &endpoint_channel](
const std::string& endpoint_id,
std::unique_ptr<UKey2Handshake> ukey2,
const std::string& auth_token, const ByteArray& raw_auth_token) {
RunOnPcpHandlerThread(
"encryption-success",
[this, &device_provider, &remote_device, &endpoint_channel,
raw_ukey2 = ukey2.release(), auth_token,
raw_auth_token]() RUN_ON_PCP_HANDLER_THREAD() mutable {
OnEncryptionSuccessRunnableV3(
remote_device, std::unique_ptr<UKey2Handshake>(raw_ukey2),
auth_token, raw_auth_token, endpoint_channel,
device_provider);
});
},
.on_failure_cb =
[this](const std::string& endpoint_id, EndpointChannel* channel) {
RunOnPcpHandlerThread(
"encryption-failure",
[this, endpoint_id, channel]() RUN_ON_PCP_HANDLER_THREAD() {
NEARBY_LOGS(ERROR)
<< "Encryption failed for endpoint_id=" << endpoint_id
<< " on medium="
<< location::nearby::proto::connections::Medium_Name(
channel->GetMedium());
OnEncryptionFailureRunnable(endpoint_id, channel);
});
},
};
}
void BasePcpHandler::OnEncryptionSuccessRunnableV3(
const NearbyDevice& remote_device, std::unique_ptr<UKey2Handshake> ukey2,
absl::string_view auth_token, const ByteArray& raw_auth_token,
const EndpointChannel& endpoint_channel,
const NearbyDeviceProvider& device_provider) {
// Quick fail if we've been removed from pending connections while we were
// busy running UKEY2.
// TODO(b/316421187): Add test coverage
auto it = pending_connections_.find(remote_device.GetEndpointId());
if (it == pending_connections_.end()) {
NEARBY_LOGS(ERROR)
<< __func__
<< ": Connection not found on UKEY negotination complete; endpoint_id="
<< remote_device.GetEndpointId();
return;
}
BasePcpHandler::PendingConnectionInfo& connection_info = it->second;
// TODO(b/300149127): Add test coverage.
if (!ukey2) {
// Fail early, if there is no crypto context.
ProcessPreConnectionInitiationFailure(
connection_info.client, connection_info.medium,
remote_device.GetEndpointId(), connection_info.channel.get(),
connection_info.is_incoming, connection_info.start_time,
{Status::kEndpointIoError}, connection_info.result.lock().get());
return;
}
// For the Nearby Presence MVP on ChromeOS, only outgoing connections are
// support in the RequestConnectionV3() API, and this is enforced below with
// an early return. This means `OnEncryptionSuccessRunnableV3()` only needs to
// authenticate in the initiator role (as opposed to responder). In order to
// support incoming connections post MVP, the responder role needs to be
// implemented, and triggered appropriately here.
//
// TODO(b/305004353): Authenticate the connection in the responder role for
// outgoing connections.
if (!connection_info.is_incoming) {
NEARBY_LOGS(ERROR) << __func__
<< ": only outgoing connections are supported";
return;
}
NEARBY_VLOG(1)
<< __func__
<< ": beginning authentication to the remote device as an initiator";
ConnectionsAuthenticationTransport connections_authentication_transport =
ConnectionsAuthenticationTransport(endpoint_channel);
connection_info.authentication_status =
device_provider.AuthenticateAsInitiator(
/*remote_device=*/remote_device,
/*shared_secret=*/auth_token,
/*authentication_transport=*/connections_authentication_transport);
NEARBY_LOGS(INFO) << __func__ << ": authentication result = "
<< AuthenticationStatusToString(
connection_info.authentication_status);
RegisterDeviceAfterEncryptionSuccess(
/*endpoint_id=*/remote_device.GetEndpointId(),
/*ukey2=*/std::move(ukey2), /*auth_token=*/auth_token,
/*raw_auth_token=*/raw_auth_token,
/*connection_info=*/connection_info);
}
void BasePcpHandler::OnEncryptionSuccessRunnable(
const std::string& endpoint_id, std::unique_ptr<UKey2Handshake> ukey2,
const std::string& auth_token, const ByteArray& raw_auth_token) {
// Quick fail if we've been removed from pending connections while we were
// busy running UKEY2.
// TODO(b/316421187): Add test coverage
auto it = pending_connections_.find(endpoint_id);
if (it == pending_connections_.end()) {
NEARBY_LOGS(INFO)
@@ -494,18 +666,28 @@ void BasePcpHandler::OnEncryptionSuccessRunnable(
}
BasePcpHandler::PendingConnectionInfo& connection_info = it->second;
Medium medium = connection_info.channel->GetMedium();
if (!ukey2) {
// Fail early, if there is no crypto context.
ProcessPreConnectionInitiationFailure(
connection_info.client, medium, endpoint_id,
connection_info.client, connection_info.medium, endpoint_id,
connection_info.channel.get(), connection_info.is_incoming,
connection_info.start_time, {Status::kEndpointIoError},
connection_info.result.lock().get());
return;
}
RegisterDeviceAfterEncryptionSuccess(
/*endpoint_id=*/endpoint_id,
/*ukey2=*/std::move(ukey2), /*auth_token=*/auth_token,
/*raw_auth_token=*/raw_auth_token,
/*connection_info=*/connection_info);
}
void BasePcpHandler::RegisterDeviceAfterEncryptionSuccess(
std::string_view endpoint_id, std::unique_ptr<UKey2Handshake> ukey2,
std::string_view auth_token, const ByteArray& raw_auth_token,
BasePcpHandler::PendingConnectionInfo& connection_info) {
connection_info.SetCryptoContext(std::move(ukey2));
connection_info.connection_token = GetHashedConnectionToken(raw_auth_token);
NEARBY_LOGS(INFO)
@@ -521,14 +703,15 @@ void BasePcpHandler::OnEncryptionSuccessRunnable(
// Now we register our endpoint so that we can listen for both sides to
// accept.
LogConnectionAttemptSuccess(endpoint_id, connection_info);
LogConnectionAttemptSuccess(std::string(endpoint_id), connection_info);
endpoint_manager_->RegisterEndpoint(
connection_info.client, endpoint_id,
connection_info.client, std::string(endpoint_id),
{
.remote_endpoint_info = connection_info.remote_endpoint_info,
.authentication_token = auth_token,
.authentication_token = std::string(auth_token),
.raw_authentication_token = raw_auth_token,
.is_incoming_connection = connection_info.is_incoming,
.authentication_status = connection_info.authentication_status,
},
connection_options, std::move(connection_info.channel),
connection_info.listener, connection_info.connection_token);
@@ -566,7 +749,7 @@ void BasePcpHandler::OnEncryptionFailureRunnable(
}
ProcessPreConnectionInitiationFailure(
info.client, info.channel->GetMedium(), endpoint_id, info.channel.get(),
info.client, info.medium, endpoint_id, info.channel.get(),
info.is_incoming, info.start_time, {Status::kEndpointIoError},
info.result.lock().get());
}
@@ -595,6 +778,15 @@ ConnectionInfo BasePcpHandler::FillConnectionInfo(
}
connection_info.supported_mediums =
GetSupportedConnectionMediumsByPriority(connection_options);
if (!NearbyFlags::GetInstance().GetBoolFlag(
config_package_nearby::nearby_connections_feature::
kEnableWifiHotspotClient) ||
connection_options.non_disruptive_hotspot_mode) {
// Remove Wi-Fi Hotspot if WiFi LAN is available.
StripOutWifiHotspotMedium(connection_info);
}
connection_info.keep_alive_interval_millis =
connection_options.keep_alive_interval_millis;
connection_info.keep_alive_timeout_millis =
@@ -613,27 +805,141 @@ Status BasePcpHandler::RequestConnection(
result]() RUN_ON_PCP_HANDLER_THREAD() {
absl::Time start_time = SystemClock::ElapsedRealtime();
// If we already have a pending connection, then we shouldn't allow any
// more outgoing connections to this endpoint.
if (pending_connections_.count(endpoint_id)) {
DiscoveredEndpoint* endpoint = GetDiscoveredEndpoint(endpoint_id);
if (endpoint == nullptr) {
NEARBY_LOGS(INFO)
<< "In requestConnection(), connection requested with "
"endpoint(id="
<< endpoint_id
<< "), but we already have a pending connection with them.";
result->Set({Status::kAlreadyConnectedToEndpoint});
<< "Discovered endpoint not found: endpoint_id=" << endpoint_id;
result->Set({Status::kEndpointUnknown});
return;
}
// If our child class says we can't send any more outgoing connections,
// listen to them.
if (client->ShouldEnforceTopologyConstraints() &&
!CanSendOutgoingConnection(client)) {
auto remote_bluetooth_mac_address = BluetoothUtils::ToString(
connection_options.remote_bluetooth_mac_address);
if (!remote_bluetooth_mac_address.empty()) {
if (AppendRemoteBluetoothMacAddressEndpoint(
endpoint_id, remote_bluetooth_mac_address,
client->GetDiscoveryOptions()))
NEARBY_LOGS(INFO)
<< "Appended remote Bluetooth MAC Address endpoint ["
<< remote_bluetooth_mac_address << "]";
}
if (AppendWebRTCEndpoint(endpoint_id, client->GetDiscoveryOptions()))
NEARBY_LOGS(INFO) << "Appended Web RTC endpoint.";
auto discovered_endpoints = GetDiscoveredEndpoints(endpoint_id);
std::unique_ptr<EndpointChannel> channel;
ConnectImplResult connect_impl_result;
for (auto connect_endpoint : discovered_endpoints) {
if (!MediumSupportedByClientOptions(connect_endpoint->medium,
connection_options))
continue;
connect_impl_result = ConnectImpl(client, connect_endpoint);
if (connect_impl_result.status.Ok()) {
channel = std::move(connect_impl_result.endpoint_channel);
break;
}
}
Medium channel_medium =
channel ? channel->GetMedium() : Medium::UNKNOWN_MEDIUM;
if (channel == nullptr) {
NEARBY_LOGS(INFO)
<< "In requestConnection(), client=" << client->GetClientId()
<< " attempted a connection with endpoint(id=" << endpoint_id
<< "), but outgoing connections are disallowed";
result->Set({Status::kOutOfOrderApiCall});
<< "Endpoint channel not available: endpoint_id=" << endpoint_id;
ProcessPreConnectionInitiationFailure(
client, channel_medium, endpoint_id, channel.get(),
/* is_incoming = */ false, start_time, connect_impl_result.status,
result.get());
return;
}
NEARBY_LOGS(INFO)
<< "In requestConnection(), wrote ConnectionRequestFrame "
"to endpoint_id="
<< endpoint_id;
ConnectionInfo connection_info =
FillConnectionInfo(client, info, connection_options);
const NearbyDevice* local_device = client->GetLocalDevice();
Exception write_exception = WriteConnectionRequestFrame(
local_device->GetType(), local_device->ToProtoBytes(),
connection_info, channel.get());
if (!write_exception.Ok()) {
NEARBY_LOGS(INFO) << "Failed to send connection request: endpoint_id="
<< endpoint_id;
ProcessPreConnectionInitiationFailure(
client, channel_medium, endpoint_id, channel.get(),
/* is_incoming = */ false, start_time, {Status::kEndpointIoError},
result.get());
return;
}
NEARBY_LOGS(INFO) << "Adding connection to pending set: endpoint_id="
<< endpoint_id;
// We've successfully connected to the device, and are now about to jump
// on to the EncryptionRunner thread to start running our encryption
// protocol. We'll mark ourselves as pending in case we get another call
// to RequestConnection or OnIncomingConnection, so that we can cancel
// the connection if needed.
// Not using designated initializers here since the VS C++ compiler
// errors out indicating that MediumSelector<bool> is not an aggregate
// TODO(b/300149127): Add test coverage to `PendingConnectionInfo`
// fields.
PendingConnectionInfo pendingConnectionInfo{};
pendingConnectionInfo.client = client;
pendingConnectionInfo.remote_endpoint_info = endpoint->endpoint_info;
pendingConnectionInfo.nonce = connection_info.nonce;
pendingConnectionInfo.is_incoming = false;
pendingConnectionInfo.start_time = start_time;
pendingConnectionInfo.listener = info.listener;
pendingConnectionInfo.connection_options = connection_options;
pendingConnectionInfo.result = result;
pendingConnectionInfo.medium = channel->GetMedium();
pendingConnectionInfo.channel = std::move(channel);
EndpointChannel* endpoint_channel =
pending_connections_
.emplace(endpoint_id, std::move(pendingConnectionInfo))
.first->second.channel.get();
NEARBY_LOGS(INFO) << "Initiating secure connection: endpoint_id="
<< endpoint_id;
// Next, we'll set up encryption. When it's done, our future will return
// and RequestConnection() will finish.
encryption_runner_.StartClient(client, endpoint_id, endpoint_channel,
GetResultListener());
});
NEARBY_LOGS(INFO) << "Waiting for connection to complete: endpoint_id="
<< endpoint_id;
auto status =
WaitForResult(absl::StrCat("RequestConnection(", endpoint_id, ")"),
client->GetClientId(), result.get());
NEARBY_LOGS(INFO) << "Wait is complete: endpoint_id=" << endpoint_id
<< "; status=" << status.value;
return status;
}
Status BasePcpHandler::RequestConnectionV3(
ClientProxy* client, const NearbyDevice& remote_device,
const ConnectionRequestInfo& info,
const ConnectionOptions& connection_options) {
auto result = std::make_shared<Future<Status>>();
std::string endpoint_id = remote_device.GetEndpointId();
RunOnPcpHandlerThread(
"request-connection-v3",
[this, client, &info, connection_options, &remote_device,
result]() RUN_ON_PCP_HANDLER_THREAD() {
absl::Time start_time = SystemClock::ElapsedRealtime();
std::string endpoint_id = remote_device.GetEndpointId();
auto connection_request_verification_status =
VerifyConnectionRequest(endpoint_id, client);
if (!connection_request_verification_status.Ok()) {
result->Set(connection_request_verification_status);
return;
}
@@ -692,7 +998,7 @@ Status BasePcpHandler::RequestConnection(
}
NEARBY_LOGS(INFO)
<< "In requestConnection(), wrote ConnectionRequestFrame "
<< "In requestConnectionV3(), wrote ConnectionRequestFrame "
"to endpoint_id="
<< endpoint_id;
@@ -727,15 +1033,18 @@ Status BasePcpHandler::RequestConnection(
// the connection if needed.
// Not using designated initializers here since the VS C++ compiler
// errors out indicating that MediumSelector<bool> is not an aggregate
// For the Nearby Presence MVP on ChromeOS, only outgoing connections
// are supported in the RequestConnectionV3() API.
PendingConnectionInfo pendingConnectionInfo{};
pendingConnectionInfo.client = client;
pendingConnectionInfo.remote_endpoint_info = endpoint->endpoint_info;
pendingConnectionInfo.nonce = connection_info.nonce;
pendingConnectionInfo.is_incoming = false;
pendingConnectionInfo.is_incoming = true;
pendingConnectionInfo.start_time = start_time;
pendingConnectionInfo.listener = info.listener;
pendingConnectionInfo.connection_options = connection_options;
pendingConnectionInfo.result = result;
pendingConnectionInfo.medium = channel->GetMedium();
pendingConnectionInfo.channel = std::move(channel);
EndpointChannel* endpoint_channel =
@@ -745,15 +1054,18 @@ Status BasePcpHandler::RequestConnection(
NEARBY_LOGS(INFO) << "Initiating secure connection: endpoint_id="
<< endpoint_id;
// Next, we'll set up encryption. When it's done, our future will return
// and RequestConnection() will finish.
encryption_runner_.StartClient(client, endpoint_id, endpoint_channel,
GetResultListener());
// Next, we'll set up encryption and authenticate the remote device.
// When it's done, our future will return and RequestConnectionV3()
// will finish.
encryption_runner_.StartClient(
client, endpoint_id, endpoint_channel,
GetResultListenerV3(*(client->GetLocalDeviceProvider()),
remote_device, *endpoint_channel));
});
NEARBY_LOGS(INFO) << "Waiting for connection to complete: endpoint_id="
<< endpoint_id;
auto status =
WaitForResult(absl::StrCat("RequestConnection(", endpoint_id, ")"),
WaitForResult(absl::StrCat("RequestConnectionV3(", endpoint_id, ")"),
client->GetClientId(), result.get());
NEARBY_LOGS(INFO) << "Wait is complete: endpoint_id=" << endpoint_id
<< "; status=" << status.value;
@@ -876,7 +1188,7 @@ BasePcpHandler::GetDiscoveredEndpoints(const std::string& endpoint_id) {
std::vector<BasePcpHandler::DiscoveredEndpoint*>
BasePcpHandler::GetDiscoveredEndpoints(
const location::nearby::proto::connections::Medium medium) {
location::nearby::proto::connections::Medium medium) {
std::vector<BasePcpHandler::DiscoveredEndpoint*> result;
MutexLock lock(&discovered_endpoint_mutex_);
for (const auto& item : discovered_endpoints_) {
@@ -937,6 +1249,25 @@ mediums::WebrtcPeerId BasePcpHandler::CreatePeerIdFromAdvertisement(
return mediums::WebrtcPeerId::FromSeed(ByteArray(std::move(seed)));
}
void BasePcpHandler::StripOutWifiHotspotMedium(
ConnectionInfo& connection_info) {
bool has_wifi_lan = false;
for (auto medium : connection_info.supported_mediums) {
if (medium == location::nearby::proto::connections::WIFI_LAN) {
has_wifi_lan = true;
break;
}
}
if (has_wifi_lan) {
connection_info.supported_mediums.erase(
std::remove(connection_info.supported_mediums.begin(),
connection_info.supported_mediums.end(),
Medium::WIFI_HOTSPOT),
connection_info.supported_mediums.end());
}
}
bool BasePcpHandler::HasOutgoingConnections(ClientProxy* client) const {
for (const auto& item : pending_connections_) {
auto& connection = item.second;
@@ -1062,7 +1393,8 @@ Status BasePcpHandler::AcceptConnection(ClientProxy* client,
Exception write_exception =
channel->Write(parser::ForConnectionResponse(
Status::kSuccess, client->GetLocalOsInfo()));
Status::kSuccess, client->GetLocalOsInfo(),
client->GetLocalMultiplexSocketBitmask()));
if (!write_exception.Ok()) {
NEARBY_LOGS(INFO)
<< "AcceptConnection: failed to send response: endpoint_id="
@@ -1093,7 +1425,7 @@ Status BasePcpHandler::RejectConnection(ClientProxy* client,
RunOnPcpHandlerThread(
"reject-connection",
[this, client, endpoint_id, &response]() RUN_ON_PCP_HANDLER_THREAD() {
NEARBY_LOG(INFO, "RejectConnection: id=%s", endpoint_id.c_str());
NEARBY_LOGS(INFO) << "RejectConnection: id=" << endpoint_id;
if (!pending_connections_.count(endpoint_id)) {
NEARBY_LOGS(INFO)
<< "RejectConnection: no pending connection for endpoint_id="
@@ -1124,7 +1456,8 @@ Status BasePcpHandler::RejectConnection(ClientProxy* client,
Exception write_exception =
channel->Write(parser::ForConnectionResponse(
Status::kConnectionRejected, client->GetLocalOsInfo()));
Status::kConnectionRejected, client->GetLocalOsInfo(),
client->GetLocalMultiplexSocketBitmask()));
if (!write_exception.Ok()) {
NEARBY_LOGS(INFO)
<< "RejectConnection: failed to send response: endpoint_id="
@@ -1195,6 +1528,11 @@ void BasePcpHandler::OnIncomingFrame(
client->SetRemoteOsInfo(endpoint_id, connection_response.os_info());
}
if (connection_response.has_multiplex_socket_bitmask()) {
client->SetRemoteMultiplexSocketBitmask(
endpoint_id, connection_response.multiplex_socket_bitmask());
}
if (connection_response.has_safe_to_disconnect_version()) {
NEARBY_LOGS(INFO)
<< "[safe-to-disconnect]: endpoint_id=" << endpoint_id
@@ -1203,8 +1541,8 @@ void BasePcpHandler::OnIncomingFrame(
client->SetRemoteSafeToDisconnectVersion(
endpoint_id, connection_response.safe_to_disconnect_version());
}
channel_manager_->UpdateSafeToDisconnectForEndpoint(endpoint_id,
client->IsSafeToDisconnectEnabled(endpoint_id));
channel_manager_->UpdateSafeToDisconnectForEndpoint(
endpoint_id, client->IsSafeToDisconnectEnabled(endpoint_id));
EvaluateConnectionResult(client, endpoint_id,
/* can_close_immediately= */ true);
@@ -1222,21 +1560,20 @@ void BasePcpHandler::OnEndpointDisconnect(ClientProxy* client,
barrier.CountDown();
return;
}
RunOnPcpHandlerThread("on-endpoint-disconnect",
[this, client, endpoint_id, barrier, reason]()
RUN_ON_PCP_HANDLER_THREAD() mutable {
auto item = pending_alarms_.find(endpoint_id);
if (item != pending_alarms_.end()) {
auto& alarm = item->second;
alarm->Cancel();
pending_alarms_.erase(item);
}
ProcessPreConnectionResultFailure(
client, endpoint_id,
/* should_call_disconnect_endpoint= */ false,
reason);
barrier.CountDown();
});
RunOnPcpHandlerThread(
"on-endpoint-disconnect", [this, client, endpoint_id, barrier,
reason]() RUN_ON_PCP_HANDLER_THREAD() mutable {
auto item = pending_alarms_.find(endpoint_id);
if (item != pending_alarms_.end()) {
auto& alarm = item->second;
alarm->Cancel();
pending_alarms_.erase(item);
}
ProcessPreConnectionResultFailure(
client, endpoint_id,
/* should_call_disconnect_endpoint= */ false, reason);
barrier.CountDown();
});
}
BluetoothDevice BasePcpHandler::GetRemoteBluetoothDevice(
@@ -1249,21 +1586,29 @@ void BasePcpHandler::OnEndpointFound(
ClientProxy* client, std::shared_ptr<DiscoveredEndpoint> endpoint) {
// Check if we've seen this endpoint ID before.
std::string& endpoint_id = endpoint->endpoint_id;
NEARBY_LOGS(INFO) << "OnEndpointFound: id=" << endpoint_id << " [enter]";
NEARBY_LOGS(INFO) << "OnEndpointFound: id=" << endpoint_id << ", medium="
<< location::nearby::proto::connections::Medium_Name(
endpoint->medium)
<< " [enter]";
MutexLock lock(&discovered_endpoint_mutex_);
auto range = discovered_endpoints_.equal_range(endpoint->endpoint_id);
bool is_range_empty = range.first == range.second;
DiscoveredEndpoint* owned_endpoint = nullptr;
for (auto& item = range.first; item != range.second; ++item) {
auto& discovered_endpoint = item->second;
if (discovered_endpoint->medium != endpoint->medium) continue;
// Check if there was a info change. If there was, report the previous
// endpoint as lost.
if (discovered_endpoint->endpoint_info != endpoint->endpoint_info) {
owned_endpoint = discovered_endpoint.get();
client->OnEndpointLost(owned_endpoint->service_id,
owned_endpoint->endpoint_id);
discovered_endpoints_.erase(item);
// Endpoint info should be same for an endpoint ID. If it is changed,
// we should reset discovered endpoints of the endpoint ID, and use the
// new endpoint info and medium as discovered endpoint.
NEARBY_LOGS(INFO) << "Endpoint info of endpoint " << endpoint_id
<< " changed on medium "
<< location::nearby::proto::connections::Medium_Name(
endpoint->medium);
// Report endpoint lost
client->OnEndpointLost(endpoint->service_id, endpoint->endpoint_id);
// Reset discovered endpoints
discovered_endpoints_.erase(item->first);
// Add the endpoint as discovered endpoint.
owned_endpoint =
discovered_endpoints_.emplace(endpoint_id, std::move(endpoint))
->second.get();
@@ -1273,17 +1618,19 @@ void BasePcpHandler::OnEndpointFound(
owned_endpoint->service_id, owned_endpoint->endpoint_id,
owned_endpoint->endpoint_info, owned_endpoint->medium);
return;
} else {
owned_endpoint = endpoint.get();
break;
}
if (discovered_endpoint->medium == endpoint->medium) {
NEARBY_LOGS(INFO) << "Ignore the dup endpoint info on medium "
<< location::nearby::proto::connections::Medium_Name(
endpoint->medium);
return;
}
}
if (!owned_endpoint) {
owned_endpoint =
discovered_endpoints_.emplace(endpoint_id, std::move(endpoint))
->second.get();
}
owned_endpoint =
discovered_endpoints_.emplace(endpoint_id, std::move(endpoint))
->second.get();
NEARBY_LOGS(INFO) << "Adding new medium for endpoint: endpoint_id="
<< endpoint_id << "; medium="
<< location::nearby::proto::connections::Medium_Name(
@@ -1329,7 +1676,8 @@ void BasePcpHandler::OnEndpointLost(
<< absl::BytesToHexString(
discovered_endpoint->endpoint_info.data());
}
NEARBY_LOGS(INFO) << "Erase Endpoint with Meduim: "
NEARBY_LOGS(INFO) << "Erase Endpoint " << endpoint.endpoint_id
<< " on Medium "
<< location::nearby::proto::connections::Medium_Name(
discovered_endpoint->medium);
if (--count == 0) {
@@ -1340,6 +1688,26 @@ void BasePcpHandler::OnEndpointLost(
}
}
void BasePcpHandler::OnInstantLost(ClientProxy* client,
const std::string& endpoint_id,
const ByteArray& endpoint_info) {
NEARBY_LOGS(INFO) << "OnInstantLost: id=" << endpoint_id;
std::vector<BasePcpHandler::DiscoveredEndpoint*> discovered_endpoints =
GetDiscoveredEndpoints(endpoint_id);
if (discovered_endpoints.empty()) {
return;
}
for (auto& discovered_endpoint : discovered_endpoints) {
if (discovered_endpoint->endpoint_info == endpoint_info) {
OnEndpointLost(client, *discovered_endpoint);
}
}
NEARBY_LOGS(INFO) << "Reported lost endpoint " << endpoint_id
<< " on all mediums.";
}
Status BasePcpHandler::UpdateAdvertisingOptions(
ClientProxy* client, absl::string_view service_id,
const AdvertisingOptions& advertising_options) {
@@ -1469,9 +1837,8 @@ Exception BasePcpHandler::OnIncomingConnection(
<< "; device=" << absl::BytesToHexString(remote_endpoint_info.data())
<< "with error: " << wrapped_frame.exception();
ProcessPreConnectionInitiationFailure(
client, medium, "", channel.get(),
/* is_incoming= */ false, start_time, {Status::kError}, nullptr);
return {Exception::kSuccess};
client, medium, /*endpoint_id=*/"", channel.get(),
/*is_incoming=*/true, start_time, {Status::kError}, nullptr);
}
return wrapped_frame.GetException();
}
@@ -1593,6 +1960,7 @@ Exception BasePcpHandler::OnIncomingConnection(
pendingConnectionInfo.connection_options = connection_options;
pendingConnectionInfo.supported_mediums =
parser::ConnectionRequestMediumsToMediums(connection_request);
pendingConnectionInfo.medium = channel->GetMedium();
pendingConnectionInfo.channel = std::move(channel);
auto* owned_channel = pending_connections_
@@ -1652,7 +2020,6 @@ bool BasePcpHandler::BreakTie(ClientProxy* client,
// Oh. Huh. We both lost. Well, that's awkward. We'll clean up both and
// just force the devices to retry.
endpoint_channel->Close();
ProcessTieBreakLoss(client, endpoint_id, &info);
NEARBY_LOGS(INFO)
@@ -1670,13 +2037,39 @@ bool BasePcpHandler::BreakTie(ClientProxy* client,
return false;
}
Status BasePcpHandler::VerifyConnectionRequest(const std::string& endpoint_id,
ClientProxy* client) {
// If we already have a pending connection, then we shouldn't allow any
// more outgoing connections to this endpoint.
if (pending_connections_.count(endpoint_id)) {
NEARBY_LOGS(INFO)
<< "In requestConnection(), connection requested with "
"endpoint(id="
<< endpoint_id
<< "), but we already have a pending connection with them.";
return {Status::kAlreadyConnectedToEndpoint};
}
// If our child class says we can't send any more outgoing connections,
// listen to them.
if (client->ShouldEnforceTopologyConstraints() &&
!CanSendOutgoingConnection(client)) {
NEARBY_LOGS(INFO) << "In requestConnection(), client="
<< client->GetClientId()
<< " attempted a connection with endpoint(id="
<< endpoint_id
<< "), but outgoing connections are disallowed";
return {Status::kOutOfOrderApiCall};
}
return {Status::kSuccess};
}
void BasePcpHandler::ProcessTieBreakLoss(
ClientProxy* client, const std::string& endpoint_id,
BasePcpHandler::PendingConnectionInfo* info) {
ProcessPreConnectionInitiationFailure(
client, info->channel->GetMedium(), endpoint_id, info->channel.get(),
info->is_incoming, info->start_time, {Status::kEndpointIoError},
info->result.lock().get());
client, info->medium, endpoint_id, info->channel.get(), info->is_incoming,
info->start_time, {Status::kEndpointIoError}, info->result.lock().get());
ProcessPreConnectionResultFailure(client, endpoint_id,
/* should_call_disconnect_endpoint= */ true,
DisconnectionReason::IO_ERROR);
@@ -1766,8 +2159,8 @@ void BasePcpHandler::EvaluateConnectionResult(ClientProxy* client,
bool can_close_immediately) {
// Short-circuit immediately if we're not in an actionable state yet. We will
// be called again once the other side has made their decision.
if (!client->IsConnectionAccepted(endpoint_id) &&
!client->IsConnectionRejected(endpoint_id)) {
bool is_connection_accepted = client->IsConnectionAccepted(endpoint_id);
if (!is_connection_accepted && !client->IsConnectionRejected(endpoint_id)) {
if (!client->HasLocalEndpointResponded(endpoint_id)) {
NEARBY_LOGS(INFO)
<< "ConnectionResult: local client did not respond; endpoint_id="
@@ -1791,7 +2184,15 @@ void BasePcpHandler::EvaluateConnectionResult(ClientProxy* client,
auto pair = pending_connections_.extract(it);
BasePcpHandler::PendingConnectionInfo& connection_info = pair.mapped();
bool is_connection_accepted = client->IsConnectionAccepted(endpoint_id);
std::shared_ptr<EndpointChannel> endpint_channel =
channel_manager_->GetChannelForEndpoint(endpoint_id);
if (endpint_channel == nullptr) {
NEARBY_LOGS(WARNING) << "No endpint channel for endpoint_id="
<< endpoint_id;
return;
}
Medium medium = endpint_channel->GetMedium();
Status response_code;
if (is_connection_accepted) {
@@ -1814,6 +2215,28 @@ void BasePcpHandler::EvaluateConnectionResult(ClientProxy* client,
std::move(context))) {
response_code = {Status::kEndpointUnknown};
}
std::shared_ptr<EndpointChannel> channel =
channel_manager_->GetChannelForEndpoint(endpoint_id);
if (channel != nullptr) {
if (client->IsMultiplexSocketSupported(endpoint_id,
channel->GetMedium())) {
if (!channel->EnableMultiplexSocket()) {
NEARBY_LOGS(INFO)
<< "MultiplexSocket is not implemented for Medium: "
<< location::nearby::proto::connections::Medium_Name(
channel->GetMedium());
} else {
NEARBY_LOGS(INFO)
<< "MultiplexSocket is supported for Medium: "
<< location::nearby::proto::connections::Medium_Name(
channel->GetMedium())
<< " on both sides.";
}
}
} else {
NEARBY_LOGS(INFO) << "channel is null";
}
} else {
NEARBY_LOGS(INFO) << "Pending connection rejected; endpoint_id="
<< endpoint_id;
@@ -1843,8 +2266,6 @@ void BasePcpHandler::EvaluateConnectionResult(ClientProxy* client,
return;
}
Medium medium =
channel_manager_->GetChannelForEndpoint(endpoint_id)->GetMedium();
client->GetAnalyticsRecorder().OnConnectionEstablished(
endpoint_id, medium, connection_info.connection_token);
@@ -1852,6 +2273,13 @@ void BasePcpHandler::EvaluateConnectionResult(ClientProxy* client,
client->OnConnectionAccepted(endpoint_id);
// Report the current bandwidth to the client
if (FeatureFlags::GetInstance()
.GetFlags()
.support_web_rtc_non_cellular_medium) {
if (medium == Medium::WEB_RTC && !mediums_->GetWebRtc().IsUsingCellular()) {
medium = Medium::WEB_RTC_NON_CELLULAR;
}
}
client->OnBandwidthChanged(endpoint_id, medium);
NEARBY_LOGS(INFO) << "Connection accepted on Medium:"
@@ -1949,15 +2377,14 @@ void BasePcpHandler::LogConnectionAttemptSuccess(
connection_info.channel->GetFrequency(),
connection_info.channel->GetTryCount());
} else {
NEARBY_LOG(ERROR,
"PendingConnectionInfo channel is null for "
"LogConnectionAttemptSuccess. Bail out.");
NEARBY_LOGS(ERROR) << "PendingConnectionInfo channel is null for "
"LogConnectionAttemptSuccess. Bail out.";
return;
}
if (connection_info.is_incoming) {
connection_info.client->GetAnalyticsRecorder().OnIncomingConnectionAttempt(
location::nearby::proto::connections::INITIAL,
connection_info.channel->GetMedium(),
location::nearby::proto::connections::INITIAL, connection_info.medium,
location::nearby::proto::connections::RESULT_SUCCESS,
SystemClock::ElapsedRealtime() - connection_info.start_time,
connection_info.connection_token,
@@ -1965,7 +2392,7 @@ void BasePcpHandler::LogConnectionAttemptSuccess(
} else {
connection_info.client->GetAnalyticsRecorder().OnOutgoingConnectionAttempt(
endpoint_id, location::nearby::proto::connections::INITIAL,
connection_info.channel->GetMedium(),
connection_info.medium,
location::nearby::proto::connections::RESULT_SUCCESS,
SystemClock::ElapsedRealtime() - connection_info.start_time,
connection_info.connection_token,
@@ -1992,7 +2419,7 @@ void BasePcpHandler::PendingConnectionInfo::SetCryptoContext(
BasePcpHandler::PendingConnectionInfo::~PendingConnectionInfo() {
auto future_status = result.lock();
if (future_status && !future_status->IsSet()) {
NEARBY_LOG(INFO, "Future was not set; destroying info");
NEARBY_LOGS(INFO) << "Future was not set; destroying info";
future_status->Set({Status::kError});
}
+73 -5
View File
@@ -17,6 +17,7 @@
#include <cstdint>
#include <memory>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
@@ -25,27 +26,45 @@
#include "absl/base/thread_annotations.h"
#include "absl/container/btree_map.h"
#include "absl/container/flat_hash_map.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "connections/advertising_options.h"
#include "connections/connection_options.h"
#include "connections/discovery_options.h"
#include "connections/implementation/analytics/packet_meta_data.h"
#include "connections/implementation/bwu_manager.h"
#include "connections/implementation/client_proxy.h"
#include "connections/implementation/encryption_runner.h"
#include "connections/implementation/endpoint_channel.h"
#include "connections/implementation/endpoint_channel_manager.h"
#include "connections/implementation/endpoint_manager.h"
#include "connections/implementation/mediums/mediums.h"
#include "connections/implementation/mediums/webrtc_peer_id.h"
#include "connections/implementation/pcp.h"
#include "connections/implementation/pcp_handler.h"
#include "connections/listeners.h"
#include "connections/medium_selector.h"
#include "connections/out_of_band_connection_metadata.h"
#include "connections/params.h"
#include "connections/status.h"
#include "connections/strategy.h"
#include "connections/v3/connection_listening_options.h"
#include "connections/v3/listeners.h"
#include "internal/interop/authentication_status.h"
#include "internal/interop/device.h"
#include "internal/interop/device_provider.h"
#include "internal/platform/atomic_boolean.h"
#include "internal/platform/ble_v2.h"
#include "internal/platform/bluetooth_adapter.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/cancelable_alarm.h"
#include "internal/platform/connection_info.h"
#include "internal/platform/count_down_latch.h"
#include "internal/platform/exception.h"
#include "internal/platform/future.h"
#include "internal/platform/prng.h"
#include "internal/platform/mutex.h"
#include "internal/platform/nsd_service_info.h"
#include "internal/platform/runnable.h"
#include "internal/platform/scheduled_executor.h"
#include "internal/platform/single_thread_executor.h"
@@ -106,7 +125,7 @@ class BasePcpHandler : public PcpHandler,
// DiscoveryListener will get called in case of any event.
Status StartDiscovery(ClientProxy* client, const std::string& service_id,
const DiscoveryOptions& discovery_options,
const DiscoveryListener& listener) override;
DiscoveryListener listener) override;
// Stops Discovery if it is active, and changes CLientProxy state,
// otherwise does nothing.
@@ -126,6 +145,11 @@ class BasePcpHandler : public PcpHandler,
const ConnectionRequestInfo& info,
const ConnectionOptions& connection_options) override;
Status RequestConnectionV3(
ClientProxy* client, const NearbyDevice& remote_device,
const ConnectionRequestInfo& info,
const ConnectionOptions& connection_options) override;
// Called by either party to accept connection on their part.
// Until both parties call it, connection will not reach a data phase.
// Updates state in ClientProxy.
@@ -268,6 +292,10 @@ class BasePcpHandler : public PcpHandler,
RUN_ON_PCP_HANDLER_THREAD()
ABSL_LOCKS_EXCLUDED(discovered_endpoint_mutex_);
void OnInstantLost(ClientProxy* client, const std::string& endpoint_id,
const ByteArray& endpoint_info)
RUN_ON_PCP_HANDLER_THREAD();
Exception OnIncomingConnection(
ClientProxy* client, const ByteArray& remote_endpoint_info,
std::unique_ptr<EndpointChannel> endpoint_channel,
@@ -355,7 +383,7 @@ class BasePcpHandler : public PcpHandler,
// Returns a vector of discovered endpoints that share a given Medium.
std::vector<BasePcpHandler::DiscoveredEndpoint*> GetDiscoveredEndpoints(
const location::nearby::proto::connections::Medium medium)
location::nearby::proto::connections::Medium medium)
ABSL_LOCKS_EXCLUDED(discovered_endpoint_mutex_);
// Start alarms for endpoints lost by their mediums. Used when updating
@@ -374,7 +402,7 @@ class BasePcpHandler : public PcpHandler,
absl::string_view service_id, StartOperationResult result);
mediums::WebrtcPeerId CreatePeerIdFromAdvertisement(
const string& service_id, const string& endpoint_id,
const std::string& service_id, const std::string& endpoint_id,
const ByteArray& endpoint_info);
SingleThreadExecutor* GetPcpHandlerThread()
@@ -382,6 +410,8 @@ class BasePcpHandler : public PcpHandler,
return &serial_executor_;
}
void StripOutWifiHotspotMedium(ConnectionInfo& connection_info);
// Test only.
int GetEndpointLostByMediumAlarmsCount() RUN_ON_PCP_HANDLER_THREAD() {
return endpoint_lost_by_medium_alarms_.size();
@@ -410,6 +440,9 @@ class BasePcpHandler : public PcpHandler,
// Pass Reject notification to client.
void LocalEndpointRejectedConnection(const std::string& endpoint_id);
// Check for a pending connection to |endpoint_id|.
bool HasPendingConnectionToEndpoint(const std::string& endpoint_id);
// Client state tracker to report events to. Never changes. Always valid.
ClientProxy* client = nullptr;
// Peer endpoint info, or empty, if not discovered yet. May change.
@@ -421,6 +454,10 @@ class BasePcpHandler : public PcpHandler,
ConnectionListener listener;
ConnectionOptions connection_options;
// Result of authentication via the DeviceProvider, if available. Only used
// for `RequestConnectionV3()`.
AuthenticationStatus authentication_status = AuthenticationStatus::kUnknown;
// Only set for outgoing connections. If set, we must call
// result->Set() when connection is established, or rejected.
std::weak_ptr<Future<Status>> result;
@@ -428,7 +465,10 @@ class BasePcpHandler : public PcpHandler,
// Only (possibly) vector for incoming connections.
std::vector<location::nearby::proto::connections::Medium> supported_mediums;
// Keep track of a channel before we pass it to EndpointChannelManager.
// Keep track of a channel before we pass it to EndpointChannelManager. This
// is owned until the call to OnEncryptionSuccessRunnableV3 or
// OnEncryptionSuccessRunnable when ownership is transferred to the
// EndpointManager.
std::unique_ptr<EndpointChannel> channel;
// Crypto context; initially empty; established first thing after channel
@@ -441,6 +481,9 @@ class BasePcpHandler : public PcpHandler,
// Used in AnalyticsRecorder for devices connection tracking.
std::string connection_token;
// The medium that the connection was established on.
location::nearby::proto::connections::Medium medium;
};
// @EncryptionRunnerThread
@@ -456,13 +499,28 @@ class BasePcpHandler : public PcpHandler,
EndpointChannel* channel);
EncryptionRunner::ResultListener GetResultListener();
EncryptionRunner::ResultListener GetResultListenerV3(
const NearbyDeviceProvider& device_provider,
const NearbyDevice& remote_device,
const EndpointChannel& endpoint_channel);
void OnEncryptionSuccessRunnable(
const std::string& endpoint_id,
std::unique_ptr<securegcm::UKey2Handshake> ukey2,
const std::string& auth_token, const ByteArray& raw_auth_token);
void OnEncryptionSuccessRunnableV3(
const NearbyDevice& remote_device,
std::unique_ptr<::securegcm::UKey2Handshake> ukey2,
absl::string_view auth_token, const ByteArray& raw_auth_token,
const EndpointChannel& endpoint_channel,
const NearbyDeviceProvider& device_provider);
void OnEncryptionFailureRunnable(const std::string& endpoint_id,
EndpointChannel* endpoint_channel);
void RegisterDeviceAfterEncryptionSuccess(
std::string_view endpoint_id,
std::unique_ptr<::securegcm::UKey2Handshake> ukey2,
std::string_view auth_token, const ByteArray& raw_auth_token,
BasePcpHandler::PendingConnectionInfo& connection_info);
static Exception WriteConnectionRequestFrame(
NearbyDevice::Type device_type, absl::string_view device_proto_bytes,
@@ -497,6 +555,9 @@ class BasePcpHandler : public PcpHandler,
const DiscoveryOptions& local_discovery_options)
ABSL_LOCKS_EXCLUDED(discovered_endpoint_mutex_);
Status VerifyConnectionRequest(const std::string& endpoint_id,
ClientProxy* client);
// Returns true if the webrtc endpoint is created and appended into
// discovered_endpoints_ with key endpoint_id.
bool AppendWebRTCEndpoint(const std::string& endpoint_id,
@@ -571,6 +632,13 @@ class BasePcpHandler : public PcpHandler,
bool ShouldEnterHighVisibilityMode(
const AdvertisingOptions& advertising_options);
// Below cases should enter stable endpoint id mode:
// 1. When use stable endpoint id returns true.
// 2. When low power returns false.
// 3. Other cases return true.
bool ShouldEnterStableEndpointIdMode(
const AdvertisingOptions& advertising_options);
// Returns the intersection of supported mediums based on the mediums reported
// by the remote client and the local client's advertising options.
BooleanMediumSelector ComputeIntersectionOfSupportedMediums(
@@ -36,9 +36,12 @@
#include "connections/implementation/bwu_manager.h"
#include "connections/implementation/client_proxy.h"
#include "connections/implementation/encryption_runner.h"
#include "connections/implementation/endpoint_channel.h"
#include "connections/implementation/endpoint_channel_manager.h"
#include "connections/implementation/endpoint_manager.h"
#include "connections/implementation/flags/nearby_connections_feature_flags.h"
#include "connections/implementation/mediums/mediums.h"
#include "connections/implementation/mock_device.h"
#include "connections/implementation/offline_frames.h"
#include "connections/implementation/pcp.h"
#include "connections/implementation/proto/offline_wire_formats.pb.h"
@@ -50,16 +53,21 @@
#include "connections/strategy.h"
#include "connections/v3/connection_listening_options.h"
#include "internal/flags/nearby_flags.h"
#include "internal/interop/authentication_status.h"
#include "internal/interop/authentication_transport.h"
#include "internal/interop/device.h"
#include "internal/interop/device_provider.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/exception.h"
#include "internal/platform/feature_flags.h"
#include "internal/platform/future.h"
#include "internal/platform/input_stream.h"
#include "internal/platform/logging.h"
#include "internal/platform/medium_environment.h"
#include "internal/platform/output_stream.h"
#include "internal/platform/pipe.h"
#include "proto/connections_enums.pb.h"
#include "proto/connections_enums.proto.h"
namespace nearby {
namespace connections {
@@ -71,9 +79,12 @@ using ::testing::_;
using ::testing::AtLeast;
using ::testing::Invoke;
using ::testing::MockFunction;
using ::testing::NiceMock;
using ::testing::Return;
using ::testing::StrictMock;
constexpr absl::string_view kTestEndpointId = "REMOTETEST";
constexpr std::array<char, 6> kFakeMacAddress = {'a', 'b', 'c', 'd', 'e', 'f'};
constexpr BooleanMediumSelector kTestCases[] = {
@@ -108,17 +119,32 @@ constexpr BooleanMediumSelector kTestCases[] = {
class FakePresenceDevice : public NearbyDevice {
public:
std::string GetEndpointId() const override { return "TEST"; }
std::string GetEndpointId() const override { return "LOCALTEST"; }
MOCK_METHOD(std::vector<ConnectionInfoVariant>, GetConnectionInfos, (),
(const override));
MOCK_METHOD(NearbyDevice::Type, GetType, (), (const override));
MOCK_METHOD(std::string, ToProtoBytes, (), (const override));
(const, override));
MOCK_METHOD(NearbyDevice::Type, GetType, (), (const, override));
MOCK_METHOD(std::string, ToProtoBytes, (), (const, override));
};
class FakePresenceDeviceProvider : public NearbyDeviceProvider {
public:
const NearbyDevice* GetLocalDevice() override { return &local_device_; }
AuthenticationStatus AuthenticateAsInitiator(
const NearbyDevice& remote_device, absl::string_view shared_secret,
const AuthenticationTransport& authentication_transport) const override {
authenticate_as_initiator_called_ = true;
return authentication_status_;
}
void SetAuthenticationStatus(AuthenticationStatus status) {
authentication_status_ = status;
}
FakePresenceDevice local_device_;
mutable bool authenticate_as_initiator_called_ = false;
private:
AuthenticationStatus authentication_status_ = AuthenticationStatus::kSuccess;
};
class MockEndpointChannel : public BaseEndpointChannel {
@@ -145,13 +171,13 @@ class MockEndpointChannel : public BaseEndpointChannel {
MOCK_METHOD(Exception, Write, (const ByteArray& data), (override));
MOCK_METHOD(void, CloseImpl, (), (override));
MOCK_METHOD(location::nearby::proto::connections::Medium, GetMedium, (),
(const override));
MOCK_METHOD(std::string, GetType, (), (const override));
MOCK_METHOD(std::string, GetName, (), (const override));
MOCK_METHOD(bool, IsPaused, (), (const override));
(const, override));
MOCK_METHOD(std::string, GetType, (), (const, override));
MOCK_METHOD(std::string, GetName, (), (const, override));
MOCK_METHOD(bool, IsPaused, (), (const, override));
MOCK_METHOD(void, Pause, (), (override));
MOCK_METHOD(void, Resume, (), (override));
MOCK_METHOD(absl::Time, GetLastReadTimestamp, (), (const override));
MOCK_METHOD(absl::Time, GetLastReadTimestamp, (), (const, override));
bool broken_write_{false};
@@ -173,8 +199,8 @@ class MockPcpHandler : public BasePcpHandler {
using BasePcpHandler::DiscoveredEndpoint;
using BasePcpHandler::StartOperationResult;
MOCK_METHOD(Strategy, GetStrategy, (), (const override));
MOCK_METHOD(Pcp, GetPcp, (), (const override));
MOCK_METHOD(Strategy, GetStrategy, (), (const, override));
MOCK_METHOD(Pcp, GetPcp, (), (const, override));
MOCK_METHOD(bool, HasOutgoingConnections, (ClientProxy * client),
(const, override));
@@ -241,6 +267,12 @@ class MockPcpHandler : public BasePcpHandler {
ABSL_NO_THREAD_SAFETY_ANALYSIS {
BasePcpHandler::OnEndpointLost(client, endpoint);
}
void OnInstantLost(ClientProxy* client,
std::shared_ptr<DiscoveredEndpoint> endpoint)
ABSL_NO_THREAD_SAFETY_ANALYSIS {
BasePcpHandler::OnInstantLost(client, endpoint->endpoint_id,
endpoint->endpoint_info);
}
BasePcpHandler::DiscoveredEndpoint* GetDiscoveredEndpoint(
const std::string& endpoint_id) {
return BasePcpHandler::GetDiscoveredEndpoint(endpoint_id);
@@ -396,6 +428,13 @@ class BasePcpHandlerTest
endpoint_distance_changed_cb;
};
void SetUp() override {
// Disable instant on lost for all tests by default.
NearbyFlags::GetInstance().OverrideBoolFlagValue(
config_package_nearby::nearby_connections_feature::kEnableInstantOnLost,
false);
}
void StartAdvertising(ClientProxy* client, MockPcpHandler* pcp_handler,
BooleanMediumSelector allowed = GetParam()) {
AdvertisingOptions advertising_options{
@@ -467,7 +506,7 @@ class BasePcpHandlerTest
pcp_handler->GetMediumsFromSelector(discovery_options.allowed),
}));
EXPECT_EQ(pcp_handler->StartDiscovery(client, service_id, discovery_options,
discovery_listener_),
GetDiscoveryListener()),
Status{Status::kSuccess});
EXPECT_TRUE(client->IsDiscovering());
for (const auto& discovered_medium :
@@ -498,6 +537,10 @@ class BasePcpHandlerTest
std::move(output_b));
auto channel_b = std::make_unique<MockEndpointChannel>(std::move(input_b),
std::move(output_a));
ON_CALL(mock_device_, GetType)
.WillByDefault(Return(NearbyDevice::Type::kUnknownDevice));
ON_CALL(mock_device_, GetEndpointId)
.WillByDefault(Return(std::string(kTestEndpointId)));
// On initiator (A) side, we drop the first write, since this is a
// connection establishment packet, and we don't have the peer entity, just
// the peer channel. The rest of the exchange must happen for the benefit of
@@ -530,6 +573,46 @@ class BasePcpHandlerTest
return std::make_pair(std::move(channel_a), std::move(channel_b));
}
std::pair<std::unique_ptr<MockEndpointChannel>,
std::unique_ptr<MockEndpointChannel>>
SetupConnectionForConnectFailure(
location::nearby::proto::connections::Medium medium) { // NOLINT
auto [input_a, output_a] = CreatePipe();
auto [input_b, output_b] = CreatePipe();
auto channel_a = std::make_unique<MockEndpointChannel>(std::move(input_a),
std::move(output_b));
auto channel_b = std::make_unique<MockEndpointChannel>(std::move(input_b),
std::move(output_a));
ON_CALL(mock_device_, GetType)
.WillByDefault(Return(NearbyDevice::Type::kUnknownDevice));
ON_CALL(mock_device_, GetEndpointId)
.WillByDefault(Return(std::string(kTestEndpointId)));
// On initiator (A) side, we drop the first write, since this is a
// connection establishment packet, and we don't have the peer entity, just
// the peer channel. The rest of the exchange must happen for the benefit of
// DH key exchange.
EXPECT_CALL(*channel_a, Read())
.WillRepeatedly(Invoke(
[channel = channel_a.get()]() { return channel->DoRead(); }));
EXPECT_CALL(*channel_a, GetMedium).WillRepeatedly(Return(medium));
EXPECT_CALL(*channel_a, GetLastReadTimestamp)
.WillRepeatedly(Return(absl::Now()));
EXPECT_CALL(*channel_a, IsPaused).WillRepeatedly(Return(false));
EXPECT_CALL(*channel_b, Read())
.WillRepeatedly(Invoke(
[channel = channel_b.get()]() { return channel->DoRead(); }));
EXPECT_CALL(*channel_b, Write(_))
.WillRepeatedly(
Invoke([channel = channel_b.get()](const ByteArray& data) {
return channel->DoWrite(data);
}));
EXPECT_CALL(*channel_b, GetMedium).WillRepeatedly(Return(medium));
EXPECT_CALL(*channel_b, GetLastReadTimestamp)
.WillRepeatedly(Return(absl::Now()));
EXPECT_CALL(*channel_b, IsPaused).WillRepeatedly(Return(false));
return std::make_pair(std::move(channel_a), std::move(channel_b));
}
void RequestConnection(
const std::string& endpoint_id,
std::unique_ptr<MockEndpointChannel> channel_a,
@@ -598,7 +681,87 @@ class BasePcpHandlerTest
EXPECT_EQ(pcp_handler->RequestConnection(client, endpoint_id, info,
connection_options),
expected_result);
NEARBY_LOG(INFO, "Stopping Encryption Runner");
NEARBY_LOGS(INFO) << "Stopping Encryption Runner";
}
void RequestConnectionV3(
const NearbyDevice& remote_device,
std::unique_ptr<MockEndpointChannel> channel_a,
MockEndpointChannel* channel_b, ClientProxy* client,
MockPcpHandler* pcp_handler,
location::nearby::proto::connections::Medium connect_medium,
FakePresenceDeviceProvider* fake_presence_device_provider,
std::atomic_int* flag = nullptr,
Status expected_result = {Status::kSuccess},
AuthenticationStatus expected_authentication_status =
AuthenticationStatus::kSuccess) {
ConnectionRequestInfo info{
.endpoint_info = ByteArray{"ABCD"},
.listener = connection_listener_,
};
ConnectionOptions connection_options{
.remote_bluetooth_mac_address = ByteArray{"\x12\x34\x56\x78\x9a\xbc"},
.keep_alive_interval_millis =
FeatureFlags::GetInstance().GetFlags().keep_alive_interval_millis,
.keep_alive_timeout_millis =
FeatureFlags::GetInstance().GetFlags().keep_alive_timeout_millis,
};
EXPECT_CALL(mock_discovery_listener_.endpoint_found_cb, Call);
EXPECT_CALL(*pcp_handler, CanSendOutgoingConnection)
.WillRepeatedly(Return(true));
EXPECT_CALL(*pcp_handler, GetStrategy)
.WillRepeatedly(Return(Strategy::kP2pCluster));
if (expected_result == Status{Status::kSuccess}) {
EXPECT_CALL(mock_connection_listener_.initiated_cb, Call)
.WillOnce([&](const std::string& endpoint_id,
const ConnectionResponseInfo& info) {
EXPECT_EQ(info.authentication_status,
expected_authentication_status);
EXPECT_TRUE(fake_presence_device_provider
->authenticate_as_initiator_called_);
});
}
// Simulate successful discovery.
auto encryption_runner = std::make_unique<EncryptionRunner>();
auto allowed_mediums = pcp_handler->GetDiscoveryMediums(client);
EXPECT_CALL(*pcp_handler, ConnectImpl)
.WillRepeatedly(
Invoke([&channel_a, connect_medium](
ClientProxy* client,
MockPcpHandler::DiscoveredEndpoint* endpoint) {
return MockPcpHandler::ConnectImplResult{
.medium = connect_medium,
.status = {Status::kSuccess},
.endpoint_channel = std::move(channel_a),
};
}));
for (const auto& discovered_medium : allowed_mediums) {
pcp_handler->OnEndpointFound(
client,
std::make_shared<MockDiscoveredEndpoint>(MockDiscoveredEndpoint{
{
remote_device.GetEndpointId(),
info.endpoint_info,
"service",
discovered_medium,
WebRtcState::kUndefined,
},
MockContext{flag},
}));
}
auto other_client = std::make_unique<ClientProxy>();
// Run peer crypto in advance, if channel_b is provided.
// Otherwise stay in not-encrypted state.
if (channel_b != nullptr) {
encryption_runner->StartServer(
other_client.get(), remote_device.GetEndpointId(), channel_b, {});
}
EXPECT_EQ(pcp_handler->RequestConnectionV3(client, remote_device, info,
connection_options),
expected_result);
}
void RequestConnectionWifiLanFail(
@@ -681,7 +844,7 @@ class BasePcpHandlerTest
EXPECT_EQ(pcp_handler->RequestConnection(client, endpoint_id, info,
connection_options),
expected_result);
NEARBY_LOG(INFO, "Stopping Encryption Runner");
NEARBY_LOGS(INFO) << "Stopping Encryption Runner";
}
MockConnectionListener mock_connection_listener_;
MockDiscoveryListener mock_discovery_listener_;
@@ -694,16 +857,28 @@ class BasePcpHandlerTest
.bandwidth_changed_cb =
mock_connection_listener_.bandwidth_changed_cb.AsStdFunction(),
};
DiscoveryListener discovery_listener_{
.endpoint_found_cb =
mock_discovery_listener_.endpoint_found_cb.AsStdFunction(),
.endpoint_lost_cb =
mock_discovery_listener_.endpoint_lost_cb.AsStdFunction(),
.endpoint_distance_changed_cb =
mock_discovery_listener_.endpoint_distance_changed_cb.AsStdFunction(),
};
DiscoveryListener GetDiscoveryListener() {
return DiscoveryListener{
.endpoint_found_cb =
mock_discovery_listener_.endpoint_found_cb.AsStdFunction(),
.endpoint_lost_cb =
mock_discovery_listener_.endpoint_lost_cb.AsStdFunction(),
.endpoint_distance_changed_cb =
mock_discovery_listener_.endpoint_distance_changed_cb
.AsStdFunction(),
};
}
void EnableInstantOnLostFeature() {
NearbyFlags::GetInstance().OverrideBoolFlagValue(
connections::config_package_nearby::nearby_connections_feature::
kEnableInstantOnLost,
true);
}
SetSafeToDisconnect set_safe_to_disconnect_{true};
MediumEnvironment& env_ = MediumEnvironment::Instance();
NiceMock<MockNearbyDevice> mock_device_;
};
TEST_P(BasePcpHandlerTest, ConstructorDestructorWorks) {
@@ -783,7 +958,7 @@ TEST_P(BasePcpHandlerTest, StartDiscoveryFails) {
.mediums = {},
}));
EXPECT_EQ(pcp_handler.StartDiscovery(&client, "service", discovery_options,
discovery_listener_),
GetDiscoveryListener()),
Status{Status::kError});
bwu.Shutdown();
env_.Stop();
@@ -837,6 +1012,77 @@ TEST_P(BasePcpHandlerTest, StartStopStartDiscoveryClearsEndpoints) {
env_.Stop();
}
TEST_F(BasePcpHandlerTest, ShouldLostEndpointWhenReportInstantLost) {
EnableInstantOnLostFeature();
env_.Start({.use_simulated_clock = true});
BooleanMediumSelector allowed{
.bluetooth = true,
.ble = true,
.wifi_lan = true,
};
auto endpoint = std::make_shared<MockDiscoveredEndpoint>(
MockDiscoveredEndpoint{{"ABCD", ByteArray("1234"), "service", Medium::BLE,
WebRtcState::kUndefined},
MockContext{nullptr}});
ClientProxy client;
Mediums m;
EndpointChannelManager ecm;
EndpointManager em(&ecm);
BwuManager bwu(m, em, ecm, {}, {});
MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
StartDiscovery(&client, &pcp_handler, allowed);
EXPECT_CALL(mock_discovery_listener_.endpoint_found_cb, Call);
pcp_handler.OnEndpointFound(&client, endpoint);
EXPECT_EQ(pcp_handler.GetDiscoveredEndpoints("ABCD").size(), 1);
EXPECT_CALL(mock_discovery_listener_.endpoint_lost_cb, Call);
pcp_handler.OnInstantLost(&client, endpoint);
EXPECT_EQ(pcp_handler.GetDiscoveredEndpoints("ABCD").size(), 0);
EXPECT_CALL(pcp_handler, StopDiscoveryImpl(&client)).Times(1);
pcp_handler.StopDiscovery(&client);
bwu.Shutdown();
env_.Stop();
}
TEST_F(BasePcpHandlerTest, ShouldLostAllEndpointsWhenReportInstantLost) {
EnableInstantOnLostFeature();
env_.Start({.use_simulated_clock = true});
BooleanMediumSelector allowed{
.bluetooth = true,
.ble = true,
.wifi_lan = true,
};
auto endpoint = std::make_shared<MockDiscoveredEndpoint>(
MockDiscoveredEndpoint{{"ABCD", ByteArray("1234"), "service", Medium::BLE,
WebRtcState::kUndefined},
MockContext{nullptr}});
auto endpoint_bluetooth = std::make_shared<MockDiscoveredEndpoint>(
MockDiscoveredEndpoint{{"ABCD", ByteArray("1234"), "service",
Medium::BLUETOOTH, WebRtcState::kUndefined},
MockContext{nullptr}});
ClientProxy client;
Mediums m;
EndpointChannelManager ecm;
EndpointManager em(&ecm);
BwuManager bwu(m, em, ecm, {}, {});
MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
StartDiscovery(&client, &pcp_handler, allowed);
EXPECT_CALL(mock_discovery_listener_.endpoint_found_cb, Call);
pcp_handler.OnEndpointFound(&client, endpoint);
pcp_handler.OnEndpointFound(&client, endpoint_bluetooth);
EXPECT_EQ(pcp_handler.GetDiscoveredEndpoints("ABCD").size(), 2);
EXPECT_CALL(mock_discovery_listener_.endpoint_lost_cb, Call);
pcp_handler.OnInstantLost(&client, endpoint);
EXPECT_EQ(pcp_handler.GetDiscoveredEndpoints("ABCD").size(), 0);
EXPECT_CALL(pcp_handler, StopDiscoveryImpl(&client)).Times(1);
pcp_handler.StopDiscovery(&client);
bwu.Shutdown();
env_.Stop();
}
TEST_F(BasePcpHandlerTest, WifiMediumFailFallBackToBT) {
env_.Start();
std::string service_id{"service"};
@@ -866,7 +1112,7 @@ TEST_F(BasePcpHandlerTest, WifiMediumFailFallBackToBT) {
}));
EXPECT_EQ(pcp_handler.StartDiscovery(&client, service_id, discovery_options,
discovery_listener_),
GetDiscoveryListener()),
Status{Status::kSuccess});
EXPECT_TRUE(client.IsDiscovering());
@@ -880,7 +1126,7 @@ TEST_F(BasePcpHandlerTest, WifiMediumFailFallBackToBT) {
EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
RequestConnectionWifiLanFail(endpoint_id, std::move(channel_a),
channel_b.get(), &client, &pcp_handler);
NEARBY_LOG(INFO, "RequestConnection complete");
NEARBY_LOGS(INFO) << "RequestConnection complete";
channel_b->Close();
bwu.Shutdown();
pcp_handler.DisconnectFromEndpointManager();
@@ -906,7 +1152,7 @@ TEST_P(BasePcpHandlerTest, RequestConnectionChangesState) {
EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
RequestConnection("1234", std::move(channel_a), channel_b.get(), &client,
&pcp_handler, connect_medium);
NEARBY_LOG(INFO, "RequestConnection complete");
NEARBY_LOGS(INFO) << "RequestConnection complete";
channel_b->Close();
bwu.Shutdown();
pcp_handler.DisconnectFromEndpointManager();
@@ -951,11 +1197,10 @@ TEST_P(BasePcpHandlerTest, CanRequestConnectionPresence) {
EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
RequestConnection("1234", std::move(channel_a), channel_b.get(), &client,
&pcp_handler, connect_medium);
NEARBY_LOG(INFO, "RequestConnection complete");
NEARBY_LOGS(INFO) << "RequestConnection complete";
channel_b->Close();
bwu.Shutdown();
pcp_handler.DisconnectFromEndpointManager();
env_.Stop();
}
TEST_P(BasePcpHandlerTest, CanRequestConnectionLegacy) {
@@ -982,7 +1227,252 @@ TEST_P(BasePcpHandlerTest, CanRequestConnectionLegacy) {
EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
RequestConnection("1234", std::move(channel_a), channel_b.get(), &client,
&pcp_handler, connect_medium);
NEARBY_LOG(INFO, "RequestConnection complete");
NEARBY_LOGS(INFO) << "RequestConnection complete";
channel_b->Close();
bwu.Shutdown();
pcp_handler.DisconnectFromEndpointManager();
env_.Stop();
}
TEST_P(BasePcpHandlerTest, RequestConnectionV3) {
env_.Start();
ClientProxy client;
FakePresenceDeviceProvider provider;
EXPECT_CALL(provider.local_device_, GetType)
.WillRepeatedly(Return(NearbyDevice::Type::kUnknownDevice));
EXPECT_CALL(provider.local_device_, ToProtoBytes);
client.RegisterDeviceProvider(&provider);
Mediums m;
EndpointChannelManager ecm;
EndpointManager em(&ecm);
BwuManager bwu(m, em, ecm, {}, {});
MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
StartDiscovery(&client, &pcp_handler);
auto mediums = pcp_handler.GetDiscoveryMediums(&client);
auto connect_medium = mediums[mediums.size() - 1];
auto channel_pair = SetupConnection(connect_medium);
auto& channel_a = channel_pair.first;
const auto& channel_b = channel_pair.second;
EXPECT_CALL(*channel_a, CloseImpl).Times(1);
EXPECT_CALL(*channel_b, CloseImpl).Times(1);
EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
RequestConnectionV3(mock_device_, std::move(channel_a), channel_b.get(),
&client, &pcp_handler, connect_medium, &provider);
NEARBY_LOGS(INFO) << "RequestConnectionV3 complete";
channel_b->Close();
bwu.Shutdown();
pcp_handler.DisconnectFromEndpointManager();
env_.Stop();
}
TEST_P(BasePcpHandlerTest, RequestConnectionV3_AuthenticationFailure) {
env_.Start();
ClientProxy client;
FakePresenceDeviceProvider provider;
provider.SetAuthenticationStatus(AuthenticationStatus::kFailure);
EXPECT_CALL(provider.local_device_, GetType)
.WillRepeatedly(Return(NearbyDevice::Type::kUnknownDevice));
EXPECT_CALL(provider.local_device_, ToProtoBytes);
client.RegisterDeviceProvider(&provider);
Mediums m;
EndpointChannelManager ecm;
EndpointManager em(&ecm);
BwuManager bwu(m, em, ecm, {}, {});
MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
StartDiscovery(&client, &pcp_handler);
auto mediums = pcp_handler.GetDiscoveryMediums(&client);
auto connect_medium = mediums[mediums.size() - 1];
auto channel_pair = SetupConnection(connect_medium);
auto& channel_a = channel_pair.first;
const auto& channel_b = channel_pair.second;
EXPECT_CALL(*channel_a, CloseImpl).Times(1);
EXPECT_CALL(*channel_b, CloseImpl).Times(1);
EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
RequestConnectionV3(
mock_device_, std::move(channel_a), channel_b.get(), &client,
&pcp_handler, connect_medium, &provider, /*flag=*/nullptr,
/*expected_result=*/{Status::kSuccess},
/*expected_authentication_status=*/AuthenticationStatus::kFailure);
NEARBY_LOGS(INFO) << "RequestConnectionV3 complete";
channel_b->Close();
bwu.Shutdown();
pcp_handler.DisconnectFromEndpointManager();
env_.Stop();
}
TEST_P(BasePcpHandlerTest, RequestConnectionV3_ConnectImplFailure) {
env_.Start();
ClientProxy client;
FakePresenceDeviceProvider provider;
EXPECT_CALL(provider.local_device_, GetType)
.WillRepeatedly(Return(NearbyDevice::Type::kUnknownDevice));
client.RegisterDeviceProvider(&provider);
Mediums m;
EndpointChannelManager ecm;
EndpointManager em(&ecm);
BwuManager bwu(m, em, ecm, {}, {});
MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
StartDiscovery(&client, &pcp_handler);
auto mediums = pcp_handler.GetDiscoveryMediums(&client);
auto connect_medium = mediums[mediums.size() - 1];
auto channel_pair = SetupConnectionForConnectFailure(connect_medium);
const auto& channel_b = channel_pair.second;
EXPECT_CALL(*channel_b, CloseImpl).Times(1);
EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
ConnectionRequestInfo info{
.endpoint_info = ByteArray{"ABCD"},
.listener = connection_listener_,
};
ConnectionOptions connection_options{
.remote_bluetooth_mac_address = ByteArray{"\x12\x34\x56\x78\x9a\xbc"},
.keep_alive_interval_millis =
FeatureFlags::GetInstance().GetFlags().keep_alive_interval_millis,
.keep_alive_timeout_millis =
FeatureFlags::GetInstance().GetFlags().keep_alive_timeout_millis,
};
EXPECT_CALL(mock_discovery_listener_.endpoint_found_cb, Call);
EXPECT_CALL(pcp_handler, CanSendOutgoingConnection)
.WillRepeatedly(Return(true));
EXPECT_CALL(pcp_handler, GetStrategy)
.WillRepeatedly(Return(Strategy::kP2pCluster));
// Simulate successful discovery.
auto encryption_runner = std::make_unique<EncryptionRunner>();
auto allowed_mediums = pcp_handler.GetDiscoveryMediums(&client);
EXPECT_CALL(pcp_handler, ConnectImpl)
.WillRepeatedly(Invoke(
[connect_medium](ClientProxy* client,
MockPcpHandler::DiscoveredEndpoint* endpoint) {
return MockPcpHandler::ConnectImplResult{
.medium = connect_medium,
.status = {Status::kError},
.endpoint_channel = nullptr,
};
}));
for (const auto& discovered_medium : allowed_mediums) {
pcp_handler.OnEndpointFound(
&client,
std::make_shared<MockDiscoveredEndpoint>(MockDiscoveredEndpoint{
{
mock_device_.GetEndpointId(),
info.endpoint_info,
"service",
discovered_medium,
WebRtcState::kUndefined,
},
MockContext{nullptr},
}));
}
Status expected_result = {Status::kError};
EXPECT_EQ(pcp_handler.RequestConnectionV3(&client, mock_device_, info,
connection_options),
expected_result);
NEARBY_LOGS(INFO) << "RequestConnectionV3 complete";
channel_b->Close();
bwu.Shutdown();
pcp_handler.DisconnectFromEndpointManager();
env_.Stop();
}
TEST_P(BasePcpHandlerTest, RequestConnection_ConnectImplFailure) {
env_.Start();
ClientProxy client;
FakePresenceDeviceProvider provider;
EXPECT_CALL(provider.local_device_, GetType)
.WillRepeatedly(Return(NearbyDevice::Type::kUnknownDevice));
client.RegisterDeviceProvider(&provider);
Mediums m;
EndpointChannelManager ecm;
EndpointManager em(&ecm);
BwuManager bwu(m, em, ecm, {}, {});
MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
StartDiscovery(&client, &pcp_handler);
auto mediums = pcp_handler.GetDiscoveryMediums(&client);
auto connect_medium = mediums[mediums.size() - 1];
auto channel_pair = SetupConnectionForConnectFailure(connect_medium);
const auto& channel_b = channel_pair.second;
EXPECT_CALL(*channel_b, CloseImpl).Times(1);
EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
ConnectionRequestInfo info{
.endpoint_info = ByteArray{"ABCD"},
.listener = connection_listener_,
};
ConnectionOptions connection_options{
.remote_bluetooth_mac_address = ByteArray{"\x12\x34\x56\x78\x9a\xbc"},
.keep_alive_interval_millis =
FeatureFlags::GetInstance().GetFlags().keep_alive_interval_millis,
.keep_alive_timeout_millis =
FeatureFlags::GetInstance().GetFlags().keep_alive_timeout_millis,
};
EXPECT_CALL(mock_discovery_listener_.endpoint_found_cb, Call);
EXPECT_CALL(pcp_handler, CanSendOutgoingConnection)
.WillRepeatedly(Return(true));
EXPECT_CALL(pcp_handler, GetStrategy)
.WillRepeatedly(Return(Strategy::kP2pCluster));
// Simulate successful discovery.
auto encryption_runner = std::make_unique<EncryptionRunner>();
auto allowed_mediums = pcp_handler.GetDiscoveryMediums(&client);
EXPECT_CALL(pcp_handler, ConnectImpl)
.WillRepeatedly(Invoke(
[connect_medium](ClientProxy* client,
MockPcpHandler::DiscoveredEndpoint* endpoint) {
return MockPcpHandler::ConnectImplResult{
.medium = connect_medium,
.status = {Status::kError},
.endpoint_channel = nullptr,
};
}));
for (const auto& discovered_medium : allowed_mediums) {
pcp_handler.OnEndpointFound(
&client,
std::make_shared<MockDiscoveredEndpoint>(MockDiscoveredEndpoint{
{
std::string(kTestEndpointId),
info.endpoint_info,
"service",
discovered_medium,
WebRtcState::kUndefined,
},
MockContext{nullptr},
}));
}
Status expected_result = {Status::kError};
EXPECT_EQ(pcp_handler.RequestConnection(&client, std::string(kTestEndpointId),
info, connection_options),
expected_result);
NEARBY_LOGS(INFO) << "RequestConnection complete";
channel_b->Close();
bwu.Shutdown();
pcp_handler.DisconnectFromEndpointManager();
env_.Stop();
}
TEST_P(BasePcpHandlerTest, IoError_RequestConnectionV3Fails) {
env_.Start();
ClientProxy client;
Mediums m;
EndpointChannelManager ecm;
EndpointManager em(&ecm);
BwuManager bwu(m, em, ecm, {}, {});
MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
StartDiscovery(&client, &pcp_handler);
auto mediums = pcp_handler.GetDiscoveryMediums(&client);
auto connect_medium = mediums[mediums.size() - 1];
auto channel_pair = SetupConnection(connect_medium);
auto& channel_a = channel_pair.first;
auto& channel_b = channel_pair.second;
EXPECT_CALL(*channel_a, CloseImpl).Times(AtLeast(1));
EXPECT_CALL(*channel_b, CloseImpl).Times(AtLeast(1));
channel_b->broken_write_ = true;
EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
RequestConnectionV3(mock_device_, std::move(channel_a), channel_b.get(),
&client, &pcp_handler, connect_medium, nullptr, nullptr,
{Status::kEndpointIoError});
NEARBY_LOGS(INFO) << "RequestConnectionV3 complete";
channel_b->Close();
bwu.Shutdown();
pcp_handler.DisconnectFromEndpointManager();
@@ -1011,7 +1501,7 @@ TEST_P(BasePcpHandlerTest, IoError_RequestConnectionFails) {
RequestConnection(endpoint_id, std::move(channel_a), channel_b.get(), &client,
&pcp_handler, connect_medium, nullptr,
{Status::kEndpointIoError});
NEARBY_LOG(INFO, "RequestConnection complete");
NEARBY_LOGS(INFO) << "RequestConnection complete";
channel_b->Close();
bwu.Shutdown();
pcp_handler.DisconnectFromEndpointManager();
@@ -1037,8 +1527,7 @@ TEST_P(BasePcpHandlerTest, AcceptConnectionChangesState) {
EXPECT_CALL(*channel_b, CloseImpl).Times(1);
RequestConnection(endpoint_id, std::move(channel_a), channel_b.get(), &client,
&pcp_handler, connect_medium);
NEARBY_LOG(INFO, "Attempting to accept connection: id=%s",
endpoint_id.c_str());
NEARBY_LOGS(INFO) << "Attempting to accept connection: id=" << endpoint_id;
EXPECT_EQ(pcp_handler.AcceptConnection(&client, endpoint_id, {}),
Status{Status::kSuccess});
EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
@@ -1102,10 +1591,10 @@ TEST_P(BasePcpHandlerTest, OnIncomingFrameChangesState) {
.Times(AtLeast(0));
EXPECT_EQ(pcp_handler.AcceptConnection(&client, endpoint_id, {}),
Status{Status::kSuccess});
NEARBY_LOG(INFO, "Simulating remote accept: id=%s", endpoint_id.c_str());
NEARBY_LOGS(INFO) << "Simulating remote accept: id=" << endpoint_id;
OsInfo os_info;
auto frame = parser::FromBytes(
parser::ForConnectionResponse(Status::kSuccess, os_info));
auto frame = parser::FromBytes(parser::ForConnectionResponse(
Status::kSuccess, os_info, /*multiplex_socket_bitmask=*/0));
EXPECT_CALL(mock_connection_listener_.bandwidth_changed_cb, Call).Times(1);
pcp_handler.OnIncomingFrame(frame.result(), endpoint_id, &client,
connect_medium, packet_meta_data);
@@ -1139,12 +1628,11 @@ TEST_P(BasePcpHandlerTest, DestructorIsCalledOnProtocolEndpoint) {
RequestConnection(endpoint_id, std::move(channel_a), channel_b.get(),
&client, &pcp_handler, connect_medium, &destroyed_flag);
mediums_count = mediums.size();
NEARBY_LOG(INFO, "Attempting to accept connection: id=%s",
endpoint_id.c_str());
NEARBY_LOGS(INFO) << "Attempting to accept connection: id=" << endpoint_id;
EXPECT_EQ(pcp_handler.AcceptConnection(&client, endpoint_id, {}),
Status{Status::kSuccess});
EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
NEARBY_LOG(INFO, "Closing connection: id=%s", endpoint_id.c_str());
NEARBY_LOGS(INFO) << "Closing connection: id=" << endpoint_id;
channel_b->Close();
bwu.Shutdown();
pcp_handler.DisconnectFromEndpointManager();
@@ -1184,8 +1672,7 @@ TEST_P(BasePcpHandlerTest, MultipleMediumsProduceSingleEndpointLostEvent) {
&client, &pcp_handler, connect_medium, &destroyed_flag);
auto allowed_mediums = pcp_handler.GetDiscoveryMediums(&client);
mediums_count = allowed_mediums.size();
NEARBY_LOG(INFO, "Attempting to accept connection: id=%s",
endpoint_id.c_str());
NEARBY_LOGS(INFO) << "Attempting to accept connection: id=" << endpoint_id;
EXPECT_EQ(pcp_handler.AcceptConnection(&client, endpoint_id, {}),
Status{Status::kSuccess});
EXPECT_CALL(mock_connection_listener_.rejected_cb, Call).Times(AtLeast(0));
@@ -1198,7 +1685,7 @@ TEST_P(BasePcpHandlerTest, MultipleMediumsProduceSingleEndpointLostEvent) {
}
EXPECT_EQ(pcp_handler.GetDiscoveredEndpoint(endpoint_id), nullptr);
EXPECT_FALSE(client.IsConnectedToEndpoint(endpoint_id));
NEARBY_LOG(INFO, "Closing connection: id=%s", endpoint_id.c_str());
NEARBY_LOGS(INFO) << "Closing connection: id=" << endpoint_id;
channel_b->Close();
bwu.Shutdown();
pcp_handler.DisconnectFromEndpointManager();
@@ -1238,7 +1725,7 @@ TEST_F(BasePcpHandlerTest, InjectEndpoint) {
.mediums = allowed.GetMediums(true),
}));
EXPECT_EQ(pcp_handler.StartDiscovery(&client, service_id, discovery_options,
discovery_listener_),
GetDiscoveryListener()),
Status{Status::kSuccess});
EXPECT_TRUE(client.IsDiscovering());
@@ -1270,6 +1757,122 @@ TEST_F(BasePcpHandlerTest, InjectEndpoint) {
env_.Stop();
}
TEST_F(BasePcpHandlerTest,
TestEndpointInfoChangedWhenEndpointDiscoveredOnMultipleMediums) {
env_.Start();
std::string service_id{"service"};
std::string endpoint_id{"ABCD"};
ClientProxy client;
Mediums m;
EndpointChannelManager ecm;
EndpointManager em(&ecm);
BwuManager bwu(m, em, ecm, {}, {});
MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
BooleanMediumSelector allowed{
.bluetooth = true,
.ble = true,
};
DiscoveryOptions discovery_options{
{
Strategy::kP2pPointToPoint,
allowed,
},
false, // auto_upgrade_bandwidth;
false, // enforce_topology_constraints;
};
EXPECT_CALL(pcp_handler, StartDiscoveryImpl)
.WillOnce(Return(MockPcpHandler::StartOperationResult{
.status = {Status::kSuccess},
.mediums = allowed.GetMediums(true),
}));
EXPECT_EQ(pcp_handler.StartDiscovery(&client, service_id, discovery_options,
GetDiscoveryListener()),
Status{Status::kSuccess});
EXPECT_TRUE(client.IsDiscovering());
::testing::InSequence seq;
EXPECT_CALL(mock_discovery_listener_.endpoint_found_cb, Call)
.WillOnce(Invoke([id = endpoint_id](const std::string& endpoint_id,
const ByteArray& endpoint_info,
const std::string& service_id) {
EXPECT_EQ(endpoint_id, id);
EXPECT_EQ(endpoint_info, ByteArray{"ABCD"});
}));
EXPECT_CALL(mock_discovery_listener_.endpoint_lost_cb, Call)
.WillOnce(Invoke([id = endpoint_id](const std::string& endpoint_id) {
EXPECT_EQ(endpoint_id, id);
}));
EXPECT_CALL(mock_discovery_listener_.endpoint_found_cb, Call)
.WillOnce(Invoke([id = endpoint_id](const std::string& endpoint_id,
const ByteArray& endpoint_info,
const std::string& service_id) {
EXPECT_EQ(endpoint_id, id);
EXPECT_EQ(endpoint_info, ByteArray{"ABCDEF"});
}));
EXPECT_CALL(mock_discovery_listener_.endpoint_lost_cb, Call)
.WillOnce(Invoke([id = endpoint_id](const std::string& endpoint_id) {
EXPECT_EQ(endpoint_id, id);
}));
// Found endpoint on Bluetooth
pcp_handler.OnEndpointFound(
&client, std::make_shared<MockDiscoveredEndpoint>(MockDiscoveredEndpoint{
{
endpoint_id,
/*endpoint_info=*/ByteArray{"ABCD"},
service_id,
Medium::BLUETOOTH,
WebRtcState::kUndefined,
},
MockContext{nullptr},
}));
// Found endpoint on BLE
pcp_handler.OnEndpointFound(
&client, std::make_shared<MockDiscoveredEndpoint>(MockDiscoveredEndpoint{
{
endpoint_id,
/*endpoint_info=*/ByteArray{"ABCD"},
service_id,
Medium::BLE,
WebRtcState::kUndefined,
},
MockContext{nullptr},
}));
// Endpoint info changed on BLE
pcp_handler.OnEndpointFound(
&client, std::make_shared<MockDiscoveredEndpoint>(MockDiscoveredEndpoint{
{
endpoint_id,
/*endpoint_info=*/ByteArray{"ABCDEF"},
service_id,
Medium::BLE,
WebRtcState::kUndefined,
},
MockContext{nullptr},
}));
pcp_handler.OnEndpointLost(&client,
MockDiscoveredEndpoint{
{
endpoint_id,
/*endpoint_info=*/ByteArray{"ABCDEF"},
service_id,
Medium::BLE,
WebRtcState::kUndefined,
},
MockContext{nullptr},
});
env_.Sync(false);
env_.Stop();
}
TEST_F(BasePcpHandlerTest, TestStartStopEndpointLostAlarm) {
env_.Start();
std::string service_id{"service"};
@@ -1891,6 +2494,56 @@ TEST_F(BasePcpHandlerTest, TestDeviceFilterForConnectionsWithPresence) {
env_.Stop();
}
TEST_F(BasePcpHandlerTest, IncomingConnectionFailsWithEmptyEndpointId) {
env_.Start();
ClientProxy client;
Mediums m;
EndpointChannelManager ecm;
EndpointManager em(&ecm);
BwuManager bwu(m, em, ecm, {}, {});
MockPcpHandler pcp_handler(&m, &em, &ecm, &bwu);
v3::ConnectionListeningOptions options = {
.strategy = Strategy::kP2pCluster,
.enable_ble_listening = true,
.enable_bluetooth_listening = true,
.enable_wlan_listening = true,
.listening_endpoint_type = NearbyDevice::Type::kConnectionsDevice};
EXPECT_CALL(pcp_handler, StartListeningForIncomingConnectionsImpl)
.WillOnce(Return(
MockPcpHandler::StartOperationResult{.status = {Status::kSuccess}}));
EXPECT_CALL(pcp_handler, CanReceiveIncomingConnection)
.WillRepeatedly(Return(true));
EXPECT_TRUE(
pcp_handler
.StartListeningForIncomingConnections(&client, "service", options, {})
.first.Ok());
ASSERT_TRUE(client.IsListeningForIncomingConnections());
ASSERT_TRUE(pcp_handler.CanReceiveIncomingConnection(&client));
auto channel_pair = SetupConnection(Medium::BLUETOOTH);
ByteArray serialized_frame = parser::ForConnectionRequestConnections(
{}, {
.local_endpoint_id = "",
.local_endpoint_info = ByteArray("local endpoint"),
});
// At this point the connection request doesn't have an endpoint ID field
// set, so we do that here.
location::nearby::connections::OfflineFrame frame;
frame.ParseFromString(serialized_frame.AsStringView());
frame.mutable_v1()->mutable_connection_request()->set_endpoint_id("");
ASSERT_TRUE(frame.v1().connection_request().has_endpoint_id());
// do a dummy write to get to the actual write.
channel_pair.first->Write(ByteArray());
channel_pair.first->Write(ByteArray(frame.SerializeAsString()));
EXPECT_EQ(pcp_handler
.OnIncomingConnection(&client, ByteArray("remote endpoint"),
std::move(channel_pair.second),
Medium::BLUETOOTH,
NearbyDevice::Type::kConnectionsDevice)
.value,
Exception::Value::kIo);
env_.Stop();
}
TEST_F(BasePcpHandlerTest, TestNeedsToTurnOffAdvertisingMedium) {
Mediums m;
EndpointChannelManager ecm;
+69 -60
View File
@@ -16,9 +16,15 @@
#include <inttypes.h>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "connections/implementation/base_pcp_handler.h"
#include "connections/implementation/pcp.h"
#include "internal/platform/base_input_stream.h"
#include "internal/platform/bluetooth_utils.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/logging.h"
namespace nearby {
@@ -87,26 +93,22 @@ void BleAdvertisement::DoInitialize(bool fast_advertisement, Version version,
}
}
BleAdvertisement::BleAdvertisement(bool fast_advertisement,
const ByteArray& ble_advertisement_bytes) {
fast_advertisement_ = fast_advertisement;
absl::StatusOr<BleAdvertisement> BleAdvertisement::CreateBleAdvertisement(
bool fast_advertisement, const ByteArray& ble_advertisement_bytes) {
if (ble_advertisement_bytes.Empty()) {
NEARBY_LOG(ERROR,
"Cannot deserialize BleAdvertisement: null bytes passed in.");
return;
return absl::InvalidArgumentError(
"Cannot deserialize BleAdvertisement: null bytes passed in.");
}
int min_advertisement_length = fast_advertisement_
int min_advertisement_length = fast_advertisement
? kMinFastAdvertisementLength
: kMinAdvertisementLength;
if (ble_advertisement_bytes.size() < min_advertisement_length) {
NEARBY_LOG(ERROR,
"Cannot deserialize BleAdvertisement: expecting min %d raw "
"bytes, got %" PRIu64,
kMinAdvertisementLength, ble_advertisement_bytes.size());
return;
return absl::InvalidArgumentError(
absl::StrCat("Cannot deserialize BleAdvertisement: expecting min ",
min_advertisement_length, " raw bytes, got ",
ble_advertisement_bytes.size()));
}
ByteArray advertisement_bytes{ble_advertisement_bytes};
@@ -114,98 +116,105 @@ BleAdvertisement::BleAdvertisement(bool fast_advertisement,
// The first 1 byte is supposed to be the version and pcp.
auto version_and_pcp_byte = static_cast<char>(base_input_stream.ReadUint8());
// The upper 3 bits are supposed to be the version.
version_ =
Version version =
static_cast<Version>((version_and_pcp_byte & kVersionBitmask) >> 5);
if (version_ != Version::kV1) {
NEARBY_LOG(INFO,
"Cannot deserialize BleAdvertisement: unsupported Version %d",
version_);
return;
if (version != Version::kV1) {
return absl::InvalidArgumentError(absl::StrCat(
"Cannot deserialize BleAdvertisement: unsupported Version: ", version));
}
// The lower 5 bits are supposed to be the Pcp.
pcp_ = static_cast<Pcp>(version_and_pcp_byte & kPcpBitmask);
switch (pcp_) {
Pcp pcp = static_cast<Pcp>(version_and_pcp_byte & kPcpBitmask);
switch (pcp) {
case Pcp::kP2pCluster: // Fall through
case Pcp::kP2pStar: // Fall through
case Pcp::kP2pPointToPoint:
break;
default:
NEARBY_LOG(INFO,
"Cannot deserialize BleAdvertisement: unsupported V1 PCP %d",
pcp_);
return absl::InvalidArgumentError(absl::StrCat(
"Cannot deserialize BleAdvertisement: unsupported V1 PCP ", pcp));
}
// The next 3 bytes are supposed to be the service_id_hash if not fast
// advertisement.
if (!fast_advertisement_)
service_id_hash_ = base_input_stream.ReadBytes(kServiceIdHashLength);
ByteArray service_id_hash;
if (!fast_advertisement) {
service_id_hash = base_input_stream.ReadBytes(kServiceIdHashLength);
}
// The next 4 bytes are supposed to be the endpoint_id.
endpoint_id_ = std::string{base_input_stream.ReadBytes(kEndpointIdLength)};
std::string endpoint_id =
std::string{base_input_stream.ReadBytes(kEndpointIdLength)};
// The next 1 byte is supposed to be the length of the endpoint_info.
std::uint32_t expected_endpoint_info_length = base_input_stream.ReadUint8();
auto expected_endpoint_info_length = base_input_stream.ReadUint8();
// The next x bytes are the endpoint info. (Max length is 131 bytes or 17
// bytes as fast_advertisement being true).
endpoint_info_ = base_input_stream.ReadBytes(expected_endpoint_info_length);
auto endpoint_info =
base_input_stream.ReadBytes(expected_endpoint_info_length);
const int max_endpoint_info_length =
fast_advertisement_ ? kMaxFastEndpointInfoLength : kMaxEndpointInfoLength;
if (endpoint_info_.Empty() ||
endpoint_info_.size() != expected_endpoint_info_length ||
endpoint_info_.size() > max_endpoint_info_length) {
NEARBY_LOG(INFO,
"Cannot deserialize BleAdvertisement(fast advertisement=%d): "
"expected endpointInfo to be %d bytes, got %" PRIu64,
fast_advertisement_, expected_endpoint_info_length,
endpoint_info_.size());
// Clear endpoint_id for validity.
endpoint_id_.clear();
return;
fast_advertisement ? kMaxFastEndpointInfoLength : kMaxEndpointInfoLength;
if (endpoint_info.Empty() ||
endpoint_info.size() != expected_endpoint_info_length ||
endpoint_info.size() > max_endpoint_info_length) {
return absl::InvalidArgumentError(absl::StrCat(
"Cannot deserialize BleAdvertisement(fast advertisement=",
fast_advertisement, "): expected endpointInfo to be ",
expected_endpoint_info_length, " bytes, got ", endpoint_info.size()));
}
// The next 6 bytes are the bluetooth mac address if not fast advertisement.
if (!fast_advertisement_) {
std::string bluetooth_mac_address;
if (!fast_advertisement) {
auto bluetooth_mac_address_bytes =
base_input_stream.ReadBytes(BluetoothUtils::kBluetoothMacAddressLength);
bluetooth_mac_address_ =
bluetooth_mac_address =
BluetoothUtils::ToString(bluetooth_mac_address_bytes);
}
// The next 1 byte is supposed to be the length of the uwb_address. If the
// next byte is not available then it should be a fast advertisement and skip
// it for remaining bytes.
ByteArray uwb_address;
BleAdvertisement ble_advertisement;
if (base_input_stream.IsAvailable(1)) {
std::uint32_t expected_uwb_address_length = base_input_stream.ReadUint8();
auto expected_uwb_address_length = base_input_stream.ReadUint8();
// If the length of uwb_address is not zero, then retrieve it.
if (expected_uwb_address_length != 0) {
uwb_address_ = base_input_stream.ReadBytes(expected_uwb_address_length);
if (uwb_address_.Empty() ||
uwb_address_.size() != expected_uwb_address_length) {
NEARBY_LOG(INFO,
"Cannot deserialize BleAdvertisement: "
"expected uwbAddress size to be %d bytes, got %" PRIu64,
expected_uwb_address_length, uwb_address_.size());
// Clear endpoint_id for validity.
endpoint_id_.clear();
return;
uwb_address = base_input_stream.ReadBytes(expected_uwb_address_length);
if (uwb_address.Empty() ||
uwb_address.size() != expected_uwb_address_length) {
return absl::InvalidArgumentError(absl::StrCat(
"Cannot deserialize BleAdvertisement: expected uwbAddress size to "
"be ",
expected_uwb_address_length, " bytes, got ", uwb_address.size()));
}
}
// The next 1 byte is extra field.
if (!fast_advertisement_) {
if (!fast_advertisement) {
if (base_input_stream.IsAvailable(kExtraFieldLength)) {
auto extra_field = static_cast<char>(base_input_stream.ReadUint8());
web_rtc_state_ = (extra_field & kWebRtcConnectableFlagBitmask) == 1
? WebRtcState::kConnectable
: WebRtcState::kUnconnectable;
ble_advertisement.web_rtc_state_ =
(extra_field & kWebRtcConnectableFlagBitmask) == 1
? WebRtcState::kConnectable
: WebRtcState::kUnconnectable;
}
}
}
base_input_stream.Close();
ble_advertisement.fast_advertisement_ = fast_advertisement;
ble_advertisement.version_ = version;
ble_advertisement.pcp_ = pcp;
ble_advertisement.service_id_hash_ = service_id_hash;
ble_advertisement.endpoint_id_ = endpoint_id;
ble_advertisement.endpoint_info_ = endpoint_info;
ble_advertisement.bluetooth_mac_address_ = bluetooth_mac_address;
ble_advertisement.uwb_address_ = uwb_address;
return ble_advertisement;
}
BleAdvertisement::operator ByteArray() const {
@@ -15,6 +15,7 @@
#ifndef CORE_INTERNAL_BLE_ADVERTISEMENT_H_
#define CORE_INTERNAL_BLE_ADVERTISEMENT_H_
#include "absl/status/statusor.h"
#include "connections/implementation/base_pcp_handler.h"
#include "connections/implementation/pcp.h"
#include "internal/platform/bluetooth_utils.h"
@@ -77,8 +78,8 @@ class BleAdvertisement {
const ByteArray& endpoint_info,
const std::string& bluetooth_mac_address,
const ByteArray& uwb_address, WebRtcState web_rtc_state);
BleAdvertisement(bool fast_advertisement,
const ByteArray& ble_advertisement_bytes);
static absl::StatusOr<BleAdvertisement> CreateBleAdvertisement(
bool fast_advertisement, const ByteArray& ble_advertisement_bytes);
BleAdvertisement(const BleAdvertisement&) = default;
BleAdvertisement& operator=(const BleAdvertisement&) = default;
BleAdvertisement(BleAdvertisement&&) = default;
@@ -14,8 +14,12 @@
#include "connections/implementation/ble_advertisement.h"
#include "gmock/gmock.h"
#include "protobuf-matchers/protocol-buffer-matchers.h"
#include "gtest/gtest.h"
#include "absl/status/status.h"
#include "connections/implementation/base_pcp_handler.h"
#include "internal/platform/byte_array.h"
namespace nearby {
namespace connections {
@@ -31,6 +35,9 @@ constexpr absl::string_view kFastAdvertisementEndpointName{"Fast Advertise"};
constexpr absl::string_view kBluetoothMacAddress{"00:00:E6:88:64:13"};
constexpr WebRtcState kWebRtcState = WebRtcState::kConnectable;
using ::absl::StatusCode::kInvalidArgument;
using ::testing::status::StatusIs;
// TODO(b/169550050): Implement UWBAddress.
TEST(BleAdvertisementTest, ConstructionWorks) {
ByteArray service_id_hash{std::string(kServiceIdHashBytes)};
@@ -269,7 +276,10 @@ TEST(BleAdvertisementTest, ConstructionFromBytesWorks) {
ByteArray{}, kWebRtcState};
ByteArray ble_advertisement_bytes(org_ble_advertisement);
BleAdvertisement ble_advertisement{false, ble_advertisement_bytes};
auto ble_status_or =
BleAdvertisement::CreateBleAdvertisement(false, ble_advertisement_bytes);
ASSERT_OK(ble_status_or.status());
auto ble_advertisement = ble_status_or.value();
EXPECT_TRUE(ble_advertisement.IsValid());
EXPECT_FALSE(ble_advertisement.IsFastAdvertisement());
@@ -290,7 +300,10 @@ TEST(BleAdvertisementTest, ConstructionFromBytesWorksForFastAdvertisement) {
fast_endpoint_info, ByteArray{}};
ByteArray ble_advertisement_bytes(org_ble_advertisement);
BleAdvertisement ble_advertisement{true, ble_advertisement_bytes};
auto ble_status_or =
BleAdvertisement::CreateBleAdvertisement(true, ble_advertisement_bytes);
ASSERT_OK(ble_status_or.status());
auto ble_advertisement = ble_status_or.value();
EXPECT_TRUE(ble_advertisement.IsValid());
EXPECT_TRUE(ble_advertisement.IsFastAdvertisement());
@@ -322,7 +335,10 @@ TEST(BleAdvertisementTest, ConstructionFromLongLengthBytesWorks) {
memcpy(long_ble_advertisement_bytes.data(), ble_advertisement_bytes.data(),
ble_advertisement_bytes.size());
BleAdvertisement long_ble_advertisement{false, long_ble_advertisement_bytes};
auto ble_status_or = BleAdvertisement::CreateBleAdvertisement(
false, long_ble_advertisement_bytes);
ASSERT_OK(ble_status_or.status());
auto long_ble_advertisement = ble_status_or.value();
EXPECT_TRUE(long_ble_advertisement.IsValid());
EXPECT_EQ(kVersion, long_ble_advertisement.GetVersion());
@@ -336,15 +352,13 @@ TEST(BleAdvertisementTest, ConstructionFromLongLengthBytesWorks) {
}
TEST(BleAdvertisementTest, ConstructionFromNullBytesFails) {
BleAdvertisement ble_advertisement{false, ByteArray{}};
EXPECT_FALSE(ble_advertisement.IsValid());
EXPECT_THAT(BleAdvertisement::CreateBleAdvertisement(false, ByteArray()),
StatusIs(kInvalidArgument));
}
TEST(BleAdvertisementTest, ConstructionFromNullBytesFailsForFastAdvertisement) {
BleAdvertisement ble_advertisement{true, ByteArray{}};
EXPECT_FALSE(ble_advertisement.IsValid());
EXPECT_THAT(BleAdvertisement::CreateBleAdvertisement(true, ByteArray()),
StatusIs(kInvalidArgument));
}
TEST(BleAdvertisementTest, ConstructionFromShortLengthBytesFails) {
@@ -363,10 +377,9 @@ TEST(BleAdvertisementTest, ConstructionFromShortLengthBytesFails) {
ble_advertisement_bytes.data(),
BleAdvertisement::kMinAdvertisementLength - 1};
BleAdvertisement short_ble_advertisement{false,
short_ble_advertisement_bytes};
EXPECT_FALSE(short_ble_advertisement.IsValid());
EXPECT_THAT(BleAdvertisement::CreateBleAdvertisement(
false, short_ble_advertisement_bytes),
StatusIs(kInvalidArgument));
}
TEST(BleAdvertisementTest,
@@ -382,9 +395,9 @@ TEST(BleAdvertisementTest,
ble_advertisement_bytes.data(),
BleAdvertisement::kMinAdvertisementLength - 1};
BleAdvertisement short_ble_advertisement{true, short_ble_advertisement_bytes};
EXPECT_FALSE(short_ble_advertisement.IsValid());
EXPECT_THAT(BleAdvertisement::CreateBleAdvertisement(
true, short_ble_advertisement_bytes),
StatusIs(kInvalidArgument));
}
TEST(BleAdvertisementTest,
@@ -404,10 +417,9 @@ TEST(BleAdvertisementTest,
corrupt_ble_advertisement_string[8] ^= 0x0FF;
ByteArray corrupt_ble_advertisement_bytes(corrupt_ble_advertisement_string);
BleAdvertisement corrupt_ble_advertisement{false,
corrupt_ble_advertisement_bytes};
EXPECT_FALSE(corrupt_ble_advertisement.IsValid());
EXPECT_THAT(BleAdvertisement::CreateBleAdvertisement(
false, corrupt_ble_advertisement_bytes),
StatusIs(kInvalidArgument));
}
TEST(BleAdvertisementTest,
@@ -423,10 +435,9 @@ TEST(BleAdvertisementTest,
corrupt_ble_advertisement_string[5] ^= 0x0FF;
ByteArray corrupt_ble_advertisement_bytes(corrupt_ble_advertisement_string);
BleAdvertisement corrupt_ble_advertisement{true,
corrupt_ble_advertisement_bytes};
EXPECT_FALSE(corrupt_ble_advertisement.IsValid());
EXPECT_THAT(BleAdvertisement::CreateBleAdvertisement(
true, corrupt_ble_advertisement_bytes),
StatusIs(kInvalidArgument));
}
} // namespace
@@ -21,6 +21,7 @@
#include "connections/implementation/bluetooth_endpoint_channel.h"
#include "connections/implementation/client_proxy.h"
#include "connections/implementation/offline_frames.h"
#include "internal/platform/logging.h"
// Manages the Bluetooth-specific methods needed to upgrade an {@link
// EndpointChannel}.
@@ -44,18 +45,18 @@ BluetoothBwuHandler::CreateUpgradedEndpointChannel(
upgrade_path_info.bluetooth_credentials();
if (!bluetooth_credentials.has_service_name() ||
!bluetooth_credentials.has_mac_address()) {
NEARBY_LOG(ERROR, "BluetoothBwuHandler failed to parse UpgradePathInfo.");
NEARBY_LOGS(ERROR)
<< "BluetoothBwuHandler failed to parse UpgradePathInfo.";
return nullptr;
}
const std::string& service_name = bluetooth_credentials.service_name();
const std::string& mac_address = bluetooth_credentials.mac_address();
NEARBY_LOGS(VERBOSE) << "BluetoothBwuHandler is attempting to connect to "
"available Bluetooth device ("
<< service_name << ", " << mac_address
<< ") for endpoint " << endpoint_id << " and service ID "
<< service_id;
NEARBY_VLOG(1) << "BluetoothBwuHandler is attempting to connect to "
"available Bluetooth device ("
<< service_name << ", " << mac_address << ") for endpoint "
<< endpoint_id << " and service ID " << service_id;
BluetoothDevice device = bluetooth_medium_.GetRemoteDevice(mac_address);
if (!device.IsValid()) {
@@ -76,7 +77,7 @@ BluetoothBwuHandler::CreateUpgradedEndpointChannel(
return nullptr;
}
NEARBY_LOGS(VERBOSE)
NEARBY_VLOG(1)
<< "BluetoothBwuHandler successfully connected to Bluetooth device ("
<< service_id << ", " << mac_address << ") while upgrading endpoint "
<< endpoint_id;
@@ -93,6 +94,7 @@ BluetoothBwuHandler::CreateUpgradedEndpointChannel(
return nullptr;
}
client->SetBluetoothMacAddress(endpoint_id, mac_address);
return channel;
}
@@ -122,7 +124,7 @@ ByteArray BluetoothBwuHandler::HandleInitializeUpgradedMediumForEndpoint(
return {};
}
NEARBY_LOGS(VERBOSE)
NEARBY_VLOG(1)
<< "BluetoothBwuHandler successfully started listening for incoming "
"Bluetooth connections on service_id="
<< upgrade_service_id << " while upgrading endpoint " << endpoint_id;
@@ -134,8 +136,8 @@ ByteArray BluetoothBwuHandler::HandleInitializeUpgradedMediumForEndpoint(
void BluetoothBwuHandler::HandleRevertInitiatorStateForService(
const std::string& upgrade_service_id) {
bluetooth_medium_.StopAcceptingConnections(upgrade_service_id);
NEARBY_LOG(INFO,
"BluetoothBwuHandler successfully reverted all Bluetooth state.");
NEARBY_LOGS(INFO)
<< "BluetoothBwuHandler successfully reverted all Bluetooth state.";
}
// Accept Connection Callback.
@@ -0,0 +1,126 @@
// 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 "gtest/gtest.h"
#include "absl/time/time.h"
#include "connections/implementation/bwu_handler.h"
#include "connections/implementation/bluetooth_bwu_handler.h"
#include "connections/implementation/client_proxy.h"
#include "connections/implementation/endpoint_channel.h"
#include "connections/implementation/mediums/mediums.h"
#include "connections/implementation/offline_frames.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/count_down_latch.h"
#include "internal/platform/exception.h"
#include "internal/platform/feature_flags.h"
#include "internal/platform/logging.h"
#include "internal/platform/medium_environment.h"
#include "internal/platform/single_thread_executor.h"
namespace nearby {
namespace connections {
namespace {
using ::location::nearby::connections::OfflineFrame;
constexpr absl::Duration kWaitDuration = absl::Milliseconds(1000);
} // namespace
class BluetoothBwuTest : public testing::Test {
protected:
BluetoothBwuTest() { env_.Start(); }
~BluetoothBwuTest() override { env_.Stop(); }
MediumEnvironment& env_{MediumEnvironment::Instance()};
};
TEST_F(BluetoothBwuTest, CanCreateBwuHandler) {
ClientProxy client;
Mediums mediums;
auto handler = std::make_unique<BluetoothBwuHandler>(mediums, nullptr);
handler->InitializeUpgradedMediumForEndpoint(&client, /*service_id=*/"B",
/*endpoint_id=*/"2");
handler->RevertInitiatorState();
SUCCEED();
handler.reset();
}
TEST_F(BluetoothBwuTest, SoftAPBWUInit_STACreateEndpointChannel) {
CountDownLatch start_latch(1);
CountDownLatch accept_latch(1);
CountDownLatch end_latch(1);
ClientProxy client_1, client_2;
Mediums mediums_1, mediums_2;
ExceptionOr<OfflineFrame> upgrade_frame;
auto handler_1 = std::make_unique<BluetoothBwuHandler>(
mediums_1, [&](ClientProxy* client,
std::unique_ptr<BwuHandler::IncomingSocketConnection>
mutable_connection) {
NEARBY_LOGS(WARNING) << "Server socket connection accept call back";
accept_latch.CountDown();
EXPECT_TRUE(end_latch.Await(kWaitDuration).result());
});
// client_1 works as Bluetooth Server Device
SingleThreadExecutor server_executor;
server_executor.Execute([&]() {
ByteArray upgrade_path_available_frame =
handler_1->InitializeUpgradedMediumForEndpoint(&client_1,
/*service_id=*/"A",
/*endpoint_id=*/"1");
EXPECT_FALSE(upgrade_path_available_frame.Empty());
upgrade_frame = parser::FromBytes(upgrade_path_available_frame);
start_latch.CountDown();
});
// client_2 works as Bluetooth Client Device which will connect to client_1
SingleThreadExecutor client_executor;
// Wait till client_1 started as Bluetooth and then connect to it
EXPECT_TRUE(start_latch.Await(kWaitDuration).result());
std::unique_ptr<BwuHandler> handler_2 =
std::make_unique<BluetoothBwuHandler>(mediums_2, nullptr);
client_executor.Execute([&]() {
auto bwu_frame =
upgrade_frame.result().v1().bandwidth_upgrade_negotiation();
std::unique_ptr<EndpointChannel> new_channel =
handler_2->CreateUpgradedEndpointChannel(&client_2, /*service_id=*/"A",
/*endpoint_id=*/"1",
bwu_frame.upgrade_path_info());
if (!FeatureFlags::GetInstance().GetFlags().enable_cancellation_flag) {
EXPECT_TRUE(accept_latch.Await(kWaitDuration).result());
EXPECT_EQ(new_channel->GetMedium(),
location::nearby::proto::connections::Medium::BLUETOOTH);
} else {
accept_latch.CountDown();
EXPECT_EQ(new_channel, nullptr);
}
EXPECT_FALSE(mediums_2.GetBluetoothClassic().GetMacAddress().empty());
handler_2->RevertResponderState(/*service_id=*/"A");
end_latch.CountDown();
});
EXPECT_TRUE(accept_latch.Await(kWaitDuration).result());
EXPECT_TRUE(end_latch.Await(kWaitDuration).result());
}
} // namespace connections
} // namespace nearby
@@ -66,11 +66,10 @@ BluetoothDeviceName::BluetoothDeviceName(
}
if (bluetooth_device_name_bytes.size() < kMinBluetoothDeviceNameLength) {
NEARBY_LOG(INFO,
"Cannot deserialize BluetoothDeviceName: expecting min %d raw "
"bytes, got %" PRIu64,
kMinBluetoothDeviceNameLength,
bluetooth_device_name_bytes.size());
NEARBY_LOGS(INFO)
<< "Cannot deserialize BluetoothDeviceName: expecting min "
<< kMinBluetoothDeviceNameLength << " raw bytes, got "
<< bluetooth_device_name_bytes.size();
return;
}
@@ -81,9 +80,9 @@ BluetoothDeviceName::BluetoothDeviceName(
version_ =
static_cast<Version>((version_and_pcp_byte & kVersionBitmask) >> 5);
if (version_ != Version::kV1) {
NEARBY_LOG(INFO,
"Cannot deserialize BluetoothDeviceName: unsupported version=%d",
version_);
NEARBY_LOGS(INFO)
<< "Cannot deserialize BluetoothDeviceName: unsupported version="
<< static_cast<int>(version_);
return;
}
// The lower 5 bits are supposed to be the Pcp.
@@ -94,9 +93,9 @@ BluetoothDeviceName::BluetoothDeviceName(
case Pcp::kP2pPointToPoint:
break;
default:
NEARBY_LOG(
INFO, "Cannot deserialize BluetoothDeviceName: unsupported V1 PCP %d",
pcp_);
NEARBY_LOGS(INFO)
<< "Cannot deserialize BluetoothDeviceName: unsupported V1 PCP "
<< static_cast<int>(pcp_);
return;
}
@@ -123,10 +122,10 @@ BluetoothDeviceName::BluetoothDeviceName(
endpoint_info_ = base_input_stream.ReadBytes(expected_endpoint_info_length);
if (endpoint_info_.Empty() ||
endpoint_info_.size() != expected_endpoint_info_length) {
NEARBY_LOG(INFO,
"Cannot deserialize BluetoothDeviceName: expected "
"endpoint info to be %d bytes, got %" PRIu64,
expected_endpoint_info_length, endpoint_info_.size());
NEARBY_LOGS(INFO) << "Cannot deserialize BluetoothDeviceName: expected "
"endpoint info to be "
<< expected_endpoint_info_length << " bytes, got "
<< endpoint_info_.size();
// Clear endpoint_id for validity.
endpoint_id_.clear();
@@ -144,10 +143,10 @@ BluetoothDeviceName::BluetoothDeviceName(
uwb_address_ = base_input_stream.ReadBytes(expected_uwb_address_length);
if (uwb_address_.Empty() ||
uwb_address_.size() != expected_uwb_address_length) {
NEARBY_LOG(INFO,
"Cannot deserialize BluetoothDeviceName: "
"expected uwbAddress size to be %d bytes, got %" PRIu64,
expected_uwb_address_length, uwb_address_.size());
NEARBY_LOGS(INFO) << "Cannot deserialize BluetoothDeviceName: expected "
"uwbAddress size to be "
<< expected_uwb_address_length << " bytes, got "
<< uwb_address_.size();
// Clear endpoint_id for validity.
endpoint_id_.clear();
@@ -179,11 +178,11 @@ BluetoothDeviceName::operator std::string() const {
ByteArray usable_endpoint_info(endpoint_info_);
if (endpoint_info_.size() > kMaxEndpointInfoLength) {
NEARBY_LOG(INFO,
"While serializing Advertisement, truncating Endpoint Name %s "
"(%lu bytes) down to %d bytes",
absl::BytesToHexString(endpoint_info_.data()).c_str(),
endpoint_info_.size(), kMaxEndpointInfoLength);
NEARBY_LOGS(INFO)
<< "While serializing Advertisement, truncating Endpoint Name "
<< absl::BytesToHexString(endpoint_info_.data()) << " ("
<< endpoint_info_.size() << " bytes) down to " << kMaxEndpointInfoLength
<< " bytes";
usable_endpoint_info.SetData(endpoint_info_.data(), kMaxEndpointInfoLength);
}
@@ -62,5 +62,12 @@ void BluetoothEndpointChannel::CloseImpl() {
}
}
bool BluetoothEndpointChannel::EnableMultiplexSocket() {
NEARBY_LOGS(INFO) << "BluetoothEndpointChannel MultiplexSocket will be "
"enabled if the Bluetooth MultiplexSocket is valid";
bluetooth_socket_.EnableMultiplexSocket();
return true;
}
} // namespace connections
} // namespace nearby
@@ -33,6 +33,7 @@ class BluetoothEndpointChannel final : public BaseEndpointChannel {
location::nearby::proto::connections::Medium GetMedium() const override;
int GetMaxTransmitPacketSize() const override;
bool EnableMultiplexSocket() override;
private:
static constexpr int kDefaultBTMaxTransmitPacketSize = 1980; // 990 * 2 Bytes
+138 -92
View File
@@ -15,17 +15,22 @@
#include "connections/implementation/bwu_manager.h"
#include <algorithm>
#include <cassert>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/functional/bind_front.h"
#include "absl/time/time.h"
#include "connections/implementation/analytics/connection_attempt_metadata_params.h"
#include "connections/implementation/bluetooth_bwu_handler.h"
#include "connections/implementation/bwu_handler.h"
#include "connections/implementation/client_proxy.h"
#include "connections/implementation/endpoint_channel.h"
#include "connections/implementation/endpoint_channel_manager.h"
#include "connections/implementation/endpoint_manager.h"
#include "connections/implementation/offline_frames.h"
#include "connections/implementation/service_id_constants.h"
#ifdef NO_WEBRTC
@@ -36,10 +41,15 @@
#include "connections/implementation/wifi_direct_bwu_handler.h"
#include "connections/implementation/wifi_hotspot_bwu_handler.h"
#include "connections/implementation/wifi_lan_bwu_handler.h"
#include "connections/medium_selector.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/cancelable_alarm.h"
#include "internal/platform/count_down_latch.h"
#include "internal/platform/feature_flags.h"
#include "internal/platform/implementation/system_clock.h"
#include "internal/platform/logging.h"
#include "internal/platform/runnable.h"
#include "proto/connections_enums.pb.h"
namespace nearby {
namespace connections {
@@ -349,7 +359,7 @@ void BwuManager::OnEndpointDisconnect(ClientProxy* client,
DisconnectionReason reason) {
NEARBY_LOGS(INFO)
<< "BwuManager has processed endpoint disconnection for endpoint "
<< endpoint_id;
<< endpoint_id << " with reason " << DisconnectionReason_Name(reason);
RunOnBwuManagerThread("bwu-on-endpoint-disconnect", [this, client, service_id,
endpoint_id,
barrier]() mutable {
@@ -466,10 +476,27 @@ BwuHandler* BwuManager::GetHandlerForMedium(Medium medium) const {
void BwuManager::OnBwuNegotiationFrame(ClientProxy* client,
const BwuNegotiationFrame frame,
const string& endpoint_id) {
const std::string& endpoint_id) {
NEARBY_LOGS(INFO) << "OnBwuNegotiationFrame: processing incoming "
<< BwuNegotiationFrame::EventType_Name(frame.event_type())
<< " frame for endpoint " << endpoint_id;
if (!client->IsConnectedToEndpoint(endpoint_id)) {
NEARBY_LOGS(WARNING)
<< "BwuManager skips the process BANDWIDTH_UPGRADE_NEGOTIATION before "
"PCP connected, "
<< frame.event_type();
// For the case discover side not yet get the local accept from client, but
// advertise side already get, discover side should inform advertise side
// the upgrade failed, so the advertise side could have chance to initialize
// another upgrade flow again.
if (frame.event_type() == BwuNegotiationFrame::UPGRADE_PATH_AVAILABLE) {
RunUpgradeFailedProtocol(client, endpoint_id, frame.upgrade_path_info());
}
return;
}
switch (frame.event_type()) {
case BwuNegotiationFrame::UPGRADE_PATH_AVAILABLE:
ProcessBwuPathAvailableEvent(client, endpoint_id,
@@ -501,90 +528,95 @@ void BwuManager::OnIncomingConnection(
NEARBY_LOGS(INFO) << "BwuManager process incoming connection";
std::shared_ptr<BwuHandler::IncomingSocketConnection> connection(
mutable_connection.release());
RunOnBwuManagerThread(
"bwu-on-incoming-connection", [this, client, connection]() {
absl::Time connection_attempt_start_time =
SystemClock::ElapsedRealtime();
EndpointChannel* channel = connection->channel.get();
if (channel == nullptr) {
NEARBY_LOGS(ERROR)
<< "BwuManager failed to create new EndpointChannel for incoming "
"socket.";
connection->socket->Close();
AttemptToRecordBandwidthUpgradeErrorForUnknownEndpoint(
location::nearby::proto::connections::MEDIUM_ERROR,
location::nearby::proto::connections::SOCKET_CREATION);
return;
}
RunOnBwuManagerThread("bwu-on-incoming-connection", [this, client,
connection]() {
absl::Time connection_attempt_start_time = SystemClock::ElapsedRealtime();
EndpointChannel* channel = connection->channel.get();
if (channel == nullptr) {
NEARBY_LOGS(ERROR)
<< "BwuManager failed to create new EndpointChannel for incoming "
"socket.";
connection->socket->Close();
AttemptToRecordBandwidthUpgradeErrorForUnknownEndpoint(
location::nearby::proto::connections::MEDIUM_ERROR,
location::nearby::proto::connections::SOCKET_CREATION);
return;
}
NEARBY_LOGS(VERBOSE)
<< "BwuManager successfully created new EndpointChannel for "
"incoming socket";
NEARBY_VLOG(1) << "BwuManager successfully created new EndpointChannel for "
"incoming socket";
ClientIntroduction introduction;
if (!ReadClientIntroductionFrame(channel, introduction)) {
// This was never a fully EstablishedConnection, no need to provide a
// closure reason.
channel->Close();
NEARBY_LOGS(ERROR)
<< "BwuManager failed to read "
"BWU_NEGOTIATION.CLIENT_INTRODUCTION OfflineFrame from "
"newly-created EndpointChannel "
<< channel->GetName()
<< ", so the EndpointChannel was discarded.";
return;
}
ClientIntroduction introduction;
if (!ReadClientIntroductionFrame(channel, introduction)) {
// This was never a fully EstablishedConnection, no need to provide a
// closure reason.
channel->Close();
NEARBY_LOGS(ERROR)
<< "BwuManager failed to read "
"BWU_NEGOTIATION.CLIENT_INTRODUCTION OfflineFrame from "
"newly-created EndpointChannel "
<< channel->GetName() << ", so the EndpointChannel was discarded.";
return;
}
if (!WriteClientIntroductionAckFrame(channel)) {
// This was never a fully EstablishedConnection, no need to provide a
// closure reason.
channel->Close();
return;
}
NEARBY_VLOG(1) << "BwuManager successfully received "
"BWU_NEGOTIATION.CLIENT_INTRODUCTION "
"OfflineFrame on EndpointChannel "
<< channel->GetName();
NEARBY_LOGS(VERBOSE) << "BwuManager successfully received "
"BWU_NEGOTIATION.CLIENT_INTRODUCTION "
"OfflineFrame on EndpointChannel "
<< channel->GetName();
if (!WriteClientIntroductionAckFrame(channel)) {
// This was never a fully EstablishedConnection, no need to provide a
// closure reason.
NEARBY_LOGS(ERROR) << "BwuManager failed to write"
"BWU_NEGOTIATION.CLIENT_INTRODUCTION_ACK "
"OfflineFrame on EndpointChannel "
<< channel->GetName();
channel->Close();
return;
}
const std::string& endpoint_id = introduction.endpoint_id();
ClientProxy* mapped_client;
const auto item = in_progress_upgrades_.find(endpoint_id);
if (item == in_progress_upgrades_.end()) return;
mapped_client = item->second;
CancelRetryUpgradeAlarm(endpoint_id);
if (mapped_client == nullptr) {
// This was never a fully EstablishedConnection, no need to provide a
// closure reason.
channel->Close();
return;
}
NEARBY_VLOG(1) << "BwuManager successfully wrote "
"BWU_NEGOTIATION.CLIENT_INTRODUCTION_ACK "
"OfflineFrame on EndpointChannel "
<< channel->GetName();
CHECK(client == mapped_client);
const std::string& endpoint_id = introduction.endpoint_id();
ClientProxy* mapped_client;
const auto item = in_progress_upgrades_.find(endpoint_id);
if (item == in_progress_upgrades_.end()) return;
mapped_client = item->second;
CancelRetryUpgradeAlarm(endpoint_id);
if (mapped_client == nullptr) {
// This was never a fully EstablishedConnection, no need to provide a
// closure reason.
channel->Close();
return;
}
// The ConnectionAttempt has now succeeded, so record it as such.
std::unique_ptr<ConnectionAttemptMetadataParams>
connections_attempt_metadata_params;
if (channel != nullptr) {
connections_attempt_metadata_params =
client->GetAnalyticsRecorder()
.BuildConnectionAttemptMetadataParams(
channel->GetTechnology(), channel->GetBand(),
channel->GetFrequency(), channel->GetTryCount());
}
client->GetAnalyticsRecorder().OnIncomingConnectionAttempt(
location::nearby::proto::connections::UPGRADE, channel->GetMedium(),
location::nearby::proto::connections::RESULT_SUCCESS,
SystemClock::ElapsedRealtime() - connection_attempt_start_time,
client->GetConnectionToken(endpoint_id),
connections_attempt_metadata_params.get());
CHECK(client == mapped_client);
// Use the introductory client information sent over to run the upgrade
// protocol.
RunUpgradeProtocol(mapped_client, endpoint_id,
std::move(connection->channel),
!introduction.supports_disabling_encryption());
});
// The ConnectionAttempt has now succeeded, so record it as such.
std::unique_ptr<ConnectionAttemptMetadataParams>
connections_attempt_metadata_params;
if (channel != nullptr) {
connections_attempt_metadata_params =
client->GetAnalyticsRecorder().BuildConnectionAttemptMetadataParams(
channel->GetTechnology(), channel->GetBand(),
channel->GetFrequency(), channel->GetTryCount());
}
client->GetAnalyticsRecorder().OnIncomingConnectionAttempt(
location::nearby::proto::connections::UPGRADE, channel->GetMedium(),
location::nearby::proto::connections::RESULT_SUCCESS,
SystemClock::ElapsedRealtime() - connection_attempt_start_time,
client->GetConnectionToken(endpoint_id),
connections_attempt_metadata_params.get());
// Use the introductory client information sent over to run the upgrade
// protocol.
RunUpgradeProtocol(mapped_client, endpoint_id,
std::move(connection->channel),
!introduction.supports_disabling_encryption());
});
}
void BwuManager::RunOnBwuManagerThread(const std::string& name,
@@ -642,10 +674,10 @@ void BwuManager::RunUpgradeProtocol(
location::nearby::proto::connections::LAST_WRITE_TO_PRIOR_CHANNEL);
return;
}
NEARBY_LOGS(VERBOSE) << "BwuManager successfully wrote "
"BWU_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL "
"OfflineFrame while upgrading endpoint "
<< endpoint_id;
NEARBY_VLOG(1) << "BwuManager successfully wrote "
"BWU_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL "
"OfflineFrame while upgrading endpoint "
<< endpoint_id;
// The remainder of this clean shutdown for the previous EndpointChannel will
// continue when we receive a corresponding
@@ -663,7 +695,7 @@ void BwuManager::RunUpgradeProtocol(
// Outgoing BWU session.
void BwuManager::ProcessBwuPathAvailableEvent(
ClientProxy* client, const string& endpoint_id,
ClientProxy* client, const std::string& endpoint_id,
const UpgradePathInfo& upgrade_path_info) {
Medium upgrade_medium =
parser::UpgradePathInfoMediumToMedium(upgrade_path_info.medium());
@@ -686,6 +718,12 @@ void BwuManager::ProcessBwuPathAvailableEvent(
return;
}
if (client->IsIncomingConnection(endpoint_id)) {
NEARBY_LOGS(INFO)
<< "ProcessBandwidthUpgradePathAvailableEvent ignored by Advertiser";
return;
}
if (in_progress_upgrades_.contains(endpoint_id)) {
NEARBY_LOGS(ERROR)
<< "BwuManager received a duplicate bandwidth upgrade for endpoint "
@@ -1068,10 +1106,10 @@ void BwuManager::ProcessLastWriteToPriorChannelEvent(
location::nearby::proto::connections::SAFE_TO_CLOSE_PRIOR_CHANNEL);
return;
}
NEARBY_LOGS(VERBOSE) << "BwuManager successfully wrote "
"BWU_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL "
"OfflineFrame while trying to upgrade endpoint "
<< endpoint_id;
NEARBY_VLOG(1) << "BwuManager successfully wrote "
"BWU_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL "
"OfflineFrame while trying to upgrade endpoint "
<< endpoint_id;
// The upgrade protocol's clean shutdown of the prior EndpointChannel will
// conclude when we receive a corresponding
@@ -1129,7 +1167,7 @@ void BwuManager::ProcessSafeToClosePriorChannelEvent(
previous_endpoint_channel->Read();
previous_endpoint_channel->Close(DisconnectionReason::UPGRADED);
NEARBY_LOGS(VERBOSE)
NEARBY_VLOG(1)
<< "BwuManager cleanly shut down prior "
<< previous_endpoint_channel->GetType()
<< " EndpointChannel to conclude upgrade protocol for endpoint "
@@ -1157,7 +1195,15 @@ void BwuManager::ProcessSafeToClosePriorChannelEvent(
channel->Resume();
// Report the success to the client
client->OnBandwidthChanged(endpoint_id, channel->GetMedium());
Medium medium = channel->GetMedium();
if (FeatureFlags::GetInstance()
.GetFlags()
.support_web_rtc_non_cellular_medium) {
if (medium == Medium::WEB_RTC && !mediums_->GetWebRtc().IsUsingCellular()) {
medium = Medium::WEB_RTC_NON_CELLULAR;
}
}
client->OnBandwidthChanged(endpoint_id, medium);
in_progress_upgrades_.erase(endpoint_id);
}
@@ -1238,9 +1284,9 @@ void BwuManager::TryNextBestUpgradeMediums(
auto channel = channel_manager_->GetChannelForEndpoint(endpoint_id);
Medium current_medium =
channel ? channel->GetMedium() : Medium::UNKNOWN_MEDIUM;
NEARBY_LOGS(VERBOSE) << "current_medium: "
<< location::nearby::proto::connections::Medium_Name(
current_medium);
NEARBY_VLOG(1) << "current_medium: "
<< location::nearby::proto::connections::Medium_Name(
current_medium);
if (current_medium != Medium::WIFI_LAN &&
(next_medium == current_medium || next_medium == Medium::UNKNOWN_MEDIUM ||
upgrade_mediums.empty())) {
+116 -31
View File
@@ -20,16 +20,22 @@
#include "gtest/gtest.h"
#include "absl/strings/string_view.h"
#include "connections/connection_options.h"
#include "connections/implementation/client_proxy.h"
#include "connections/implementation/endpoint_channel.h"
#include "connections/implementation/endpoint_channel_manager.h"
#include "connections/implementation/endpoint_manager.h"
#include "connections/implementation/fake_bwu_handler.h"
#include "connections/implementation/fake_endpoint_channel.h"
#include "connections/implementation/flags/nearby_connections_feature_flags.h"
#include "connections/implementation/mediums/mediums.h"
#include "connections/implementation/offline_frames.h"
#include "connections/implementation/service_id_constants.h"
#include "connections/listeners.h"
#include "internal/flags/nearby_flags.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/exception.h"
#include "internal/platform/feature_flags.h"
#include "internal/proto/analytics/connections_log.pb.h"
#include "proto/connections_enums.pb.h"
@@ -89,9 +95,15 @@ class BwuManagerTest : public ::testing::Test {
// Create the initial device-to-device connection, before bandwidth upgrade.
// Typically |medium| will be Bluetooth.
FakeEndpointChannel* CreateInitialEndpoint(absl::string_view service_id,
FakeEndpointChannel* CreateInitialEndpoint(ClientProxy* client,
absl::string_view service_id,
absl::string_view endpoint_id,
Medium medium) {
client->OnConnectionInitiated(
std::string(endpoint_id),
{.remote_endpoint_info = ByteArray("remote endpoint")},
{.auto_upgrade_bandwidth = false}, {}, "");
client->OnConnectionAccepted(std::string(endpoint_id));
auto channel =
std::make_unique<FakeEndpointChannel>(medium, std::string(service_id));
FakeEndpointChannel* channel_raw = channel.get();
@@ -235,8 +247,8 @@ class BwuManagerTestParam : public BwuManagerTest,
TEST_P(BwuManagerTestParam, InitiateBwu_Success) {
// Create the initial device-to-device Bluetooth connection.
FakeEndpointChannel* initial_channel =
CreateInitialEndpoint(kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
FakeEndpointChannel* initial_channel = CreateInitialEndpoint(
&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
// Initiate BWU, and send BANDWIDTH_UPGRADE_NEGOTIATION.UPGRADE_PATH_AVAILABLE
// to the Responder over the initial Bluetooth channel.
@@ -298,7 +310,7 @@ TEST_P(BwuManagerTestParam, InitiateBwu_Success) {
TEST_P(BwuManagerTestParam,
InitiateBwu_Error_DontUpgradeIfAlreadyConenctedOverTheRequestedMedium) {
CreateInitialEndpoint(kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
FullyUpgradeEndpoint(kEndpointId1, /*initial_medium=*/Medium::BLUETOOTH,
/*upgrade_medium=*/Medium::WEB_RTC);
EXPECT_EQ(1u, fake_web_rtc_bwu_handler_->handle_initialize_calls().size());
@@ -312,7 +324,7 @@ TEST_P(BwuManagerTestParam,
TEST_P(BwuManagerTestParam,
InitiateBwu_Error_DontUpgradeFromWIFI_LANToWIFI_HOTSPOT) {
CreateInitialEndpoint(kServiceIdA, kEndpointId1, Medium::WIFI_LAN);
CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::WIFI_LAN);
// Ignore request to upgrade to WebRTC if we're already connected.
bwu_manager_->InitiateBwuForEndpoint(&client_, std::string(kEndpointId1),
@@ -336,7 +348,7 @@ TEST_P(BwuManagerTestParam, InitiateBwu_Error_NoInitialMedium) {
}
TEST_P(BwuManagerTestParam, InitiateBwu_Error_UpgradeAlreadyInProgress) {
CreateInitialEndpoint(kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
bwu_manager_->InitiateBwuForEndpoint(&client_, std::string(kEndpointId1),
Medium::WEB_RTC);
@@ -357,8 +369,8 @@ TEST_P(BwuManagerTestParam, InitiateBwu_Error_UpgradeAlreadyInProgress) {
TEST_P(BwuManagerTestParam,
InitiateBwu_Error_FailedToWriteUpgradePathAvailableFrame) {
// Create the initial device-to-device Bluetooth connection.
FakeEndpointChannel* initial_channel =
CreateInitialEndpoint(kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
FakeEndpointChannel* initial_channel = CreateInitialEndpoint(
&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
// Make the initial endpoint channel fail when writing the
// UPGRADE_PATH_AVAILABLE frame.
@@ -391,8 +403,8 @@ TEST_F(BwuManagerTest,
FeatureFlags::GetMutableFlagsForTesting().support_multiple_bwu_mediums = true;
// Say we have two already upgraded WebRTC connections for the same service.
CreateInitialEndpoint(kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
CreateInitialEndpoint(kServiceIdA, kEndpointId2, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId2, Medium::BLUETOOTH);
FullyUpgradeEndpoint(kEndpointId1, /*initial_medium=*/Medium::BLUETOOTH,
/*upgrade_medium=*/Medium::WEB_RTC);
FullyUpgradeEndpoint(kEndpointId2, /*initial_medium=*/Medium::BLUETOOTH,
@@ -441,8 +453,8 @@ TEST_F(BwuManagerTest,
false;
// Say we have two already upgraded WebRTC connections for the same service.
CreateInitialEndpoint(kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
CreateInitialEndpoint(kServiceIdA, kEndpointId2, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId2, Medium::BLUETOOTH);
FullyUpgradeEndpoint(kEndpointId1, /*initial_medium=*/Medium::BLUETOOTH,
/*upgrade_medium=*/Medium::WEB_RTC);
FullyUpgradeEndpoint(kEndpointId2, /*initial_medium=*/Medium::BLUETOOTH,
@@ -497,8 +509,8 @@ TEST_F(BwuManagerTest,
FeatureFlags::GetMutableFlagsForTesting().support_multiple_bwu_mediums = true;
// Say we have two already upgraded WLAN connections for different services.
CreateInitialEndpoint(kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
CreateInitialEndpoint(kServiceIdB, kEndpointId2, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdB, kEndpointId2, Medium::BLUETOOTH);
FullyUpgradeEndpoint(kEndpointId1, /*initial_medium=*/Medium::BLUETOOTH,
/*upgrade_medium=*/Medium::WIFI_LAN);
FullyUpgradeEndpoint(kEndpointId2, /*initial_medium=*/Medium::BLUETOOTH,
@@ -552,8 +564,8 @@ TEST_F(BwuManagerTest,
false;
// Say we have two already upgraded WLAN connections for different services.
CreateInitialEndpoint(kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
CreateInitialEndpoint(kServiceIdB, kEndpointId2, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdB, kEndpointId2, Medium::BLUETOOTH);
FullyUpgradeEndpoint(kEndpointId1, /*initial_medium=*/Medium::BLUETOOTH,
/*upgrade_medium=*/Medium::WIFI_LAN);
FullyUpgradeEndpoint(kEndpointId2, /*initial_medium=*/Medium::BLUETOOTH,
@@ -611,11 +623,11 @@ TEST_F(
// Say we have three upgraded connections for two different services and two
// different mediums.
CreateInitialEndpoint(kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
CreateInitialEndpoint(kServiceIdA, kEndpointId2, Medium::BLUETOOTH);
CreateInitialEndpoint(kServiceIdB, kEndpointId3, Medium::BLUETOOTH);
CreateInitialEndpoint(kServiceIdB, kEndpointId4, Medium::BLUETOOTH);
CreateInitialEndpoint(kServiceIdB, kEndpointId5, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId2, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdB, kEndpointId3, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdB, kEndpointId4, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdB, kEndpointId5, Medium::BLUETOOTH);
FullyUpgradeEndpoint(kEndpointId1, /*initial_medium=*/Medium::BLUETOOTH,
/*upgrade_medium=*/Medium::WEB_RTC);
FullyUpgradeEndpoint(kEndpointId4, /*initial_medium=*/Medium::BLUETOOTH,
@@ -759,15 +771,15 @@ TEST_F(BwuManagerTest, InitiateBwu_Revert_OnUpgradeFailure_FlagEnabled) {
FeatureFlags::GetMutableFlagsForTesting().support_multiple_bwu_mediums = true;
// Say we have two already upgraded WebRTC connections for service A.
CreateInitialEndpoint(kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
CreateInitialEndpoint(kServiceIdA, kEndpointId2, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId2, Medium::BLUETOOTH);
FullyUpgradeEndpoint(kEndpointId1, /*initial_medium=*/Medium::BLUETOOTH,
/*upgrade_medium=*/Medium::WEB_RTC);
FullyUpgradeEndpoint(kEndpointId2, /*initial_medium=*/Medium::BLUETOOTH,
/*upgrade_medium=*/Medium::WEB_RTC);
// Service B has an initial Bluetooth connection that it tries to upgrade.
CreateInitialEndpoint(kServiceIdB, kEndpointId3, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdB, kEndpointId3, Medium::BLUETOOTH);
bwu_manager_->InitiateBwuForEndpoint(&client_, std::string(kEndpointId3),
Medium::WEB_RTC);
fake_web_rtc_bwu_handler_->NotifyBwuManagerOfIncomingConnection(
@@ -797,15 +809,15 @@ TEST_F(BwuManagerTest, InitiateBwu_Revert_OnUpgradeFailure_FlagDisabled) {
false;
// Say we have two already upgraded WebRTC connections for service A.
CreateInitialEndpoint(kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
CreateInitialEndpoint(kServiceIdA, kEndpointId2, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId2, Medium::BLUETOOTH);
FullyUpgradeEndpoint(kEndpointId1, /*initial_medium=*/Medium::BLUETOOTH,
/*upgrade_medium=*/Medium::WEB_RTC);
FullyUpgradeEndpoint(kEndpointId2, /*initial_medium=*/Medium::BLUETOOTH,
/*upgrade_medium=*/Medium::WEB_RTC);
// Service B has an initial Bluetooth connection that it tries to upgrade.
CreateInitialEndpoint(kServiceIdB, kEndpointId3, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdB, kEndpointId3, Medium::BLUETOOTH);
bwu_manager_->InitiateBwuForEndpoint(&client_, std::string(kEndpointId3),
Medium::WEB_RTC);
fake_web_rtc_bwu_handler_->NotifyBwuManagerOfIncomingConnection(
@@ -832,7 +844,7 @@ TEST_F(BwuManagerTest, InitiateBwu_Revert_OnUpgradeFailure_FlagDisabled) {
TEST_F(BwuManagerTest, InitiateBwu_Revert_OnDisconnect_WifiDirect) {
FeatureFlags::GetMutableFlagsForTesting().support_multiple_bwu_mediums = true;
OfflineFrame frame;
CreateInitialEndpoint(kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
ByteArray bytes = parser::ForBwuWifiDirectPathAvailable(
/*ssid=*/"Direct-12345678", /*password=*/"87654321", /*port=*/2143,
@@ -865,12 +877,13 @@ TEST_F(BwuManagerTest, InitiateBwu_Revert_OnDisconnect_WifiDirect) {
TEST_F(BwuManagerTest, InitiateBwu_Revert_OnDisconnect_Hotspot) {
FeatureFlags::GetMutableFlagsForTesting().support_multiple_bwu_mediums = true;
CreateInitialEndpoint(kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
ExceptionOr<OfflineFrame> hotspot_path_available_frame =
parser::FromBytes(parser::ForBwuWifiHotspotPathAvailable(
/*ssid=*/"Direct-357a2d8c", /*password=*/"b592f7d3",
/*port=*/1234, /*gateway=*/"123.234.23.1", false));
/*port=*/1234, /*frequency=*/2412, /*gateway=*/"123.234.23.1",
false));
OfflineFrame frame = hotspot_path_available_frame.result();
frame.set_version(OfflineFrame::V1);
auto* v1_frame = frame.mutable_v1();
@@ -894,7 +907,7 @@ TEST_F(BwuManagerTest, InitiateBwu_Revert_OnDisconnect_Hotspot) {
TEST_F(BwuManagerTest, InitiateBwu_Revert_OnDisconnect_Wlan) {
FeatureFlags::GetMutableFlagsForTesting().support_multiple_bwu_mediums = true;
CreateInitialEndpoint(kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
CreateInitialEndpoint(&client_, kServiceIdA, kEndpointId1, Medium::BLUETOOTH);
ExceptionOr<OfflineFrame> wlan_path_available_frame = parser::FromBytes(
parser::ForBwuWifiLanPathAvailable(/*ip_address=*/"ABCD",
@@ -927,6 +940,78 @@ TEST_F(BwuManagerTest, OnProcessBwuEvent) {
// TODO(b/235109434): Add more unit tests coverage for BWU module
}
TEST_F(BwuManagerTest, BlockBwuFrameBeforeAccept) {
auto channel = std::make_unique<FakeEndpointChannel>(
Medium::BLUETOOTH, std::string(kServiceIdA));
ecm_.RegisterChannelForEndpoint(&client_, std::string(kEndpointId2),
std::move(channel));
ExceptionOr<OfflineFrame> hotspot_path_available_frame2 =
parser::FromBytes(parser::ForBwuWifiHotspotPathAvailable(
/*ssid=*/"Direct-357a2d8c", /*password=*/"b592f7d3",
/*port=*/1234, /*frequency=*/2412, /*gateway=*/"123.234.23.1", true));
OfflineFrame frame2 = hotspot_path_available_frame2.result();
frame2.set_version(OfflineFrame::V1);
auto* v1_frame2 = frame2.mutable_v1();
auto* sub_frame2 = v1_frame2->mutable_bandwidth_upgrade_negotiation();
sub_frame2->set_event_type(
BandwidthUpgradeNegotiationFrame::UPGRADE_PATH_AVAILABLE);
auto* upgrade_path_info2 = sub_frame2->mutable_upgrade_path_info();
upgrade_path_info2->set_supports_client_introduction_ack(false);
upgrade_path_info2->set_supports_disabling_encryption(true);
bwu_manager_->OnIncomingFrame(frame2, std::string(kEndpointId2), &client_,
Medium::BLUETOOTH, packet_meta_data_);
CountDownLatch latch2(1);
// The BWU frame should be drop, so the inProgressUpgrades should be empty.
ASSERT_EQ(bwu_manager_->IsUpgradeOngoing(std::string(kEndpointId2)), false);
UnRegisterChannelForEndpoint(kEndpointId2);
}
TEST_F(BwuManagerTest, BlockBwuFrameFromAdvertiser) {
ExceptionOr<OfflineFrame> hotspot_path_available_frame =
parser::FromBytes(parser::ForBwuWifiHotspotPathAvailable(
/*ssid=*/"Direct-357a2d8c", /*password=*/"b592f7d3",
/*port=*/1234, /*frequency=*/2412, /*gateway=*/"123.234.23.1", true));
OfflineFrame frame = hotspot_path_available_frame.result();
frame.set_version(OfflineFrame::V1);
auto* v1_frame = frame.mutable_v1();
auto* sub_frame = v1_frame->mutable_bandwidth_upgrade_negotiation();
sub_frame->set_event_type(
BandwidthUpgradeNegotiationFrame::UPGRADE_PATH_AVAILABLE);
auto* upgrade_path_info = sub_frame->mutable_upgrade_path_info();
upgrade_path_info->set_supports_client_introduction_ack(false);
upgrade_path_info->set_supports_disabling_encryption(true);
ConnectionResponseInfo response_info{
.remote_endpoint_info = ByteArray{"endpoint_name"},
.authentication_token = "auth_token",
.raw_authentication_token = ByteArray{"auth_token"},
.is_incoming_connection = true,
};
ConnectionOptions connection_options;
auto channel = std::make_unique<FakeEndpointChannel>(
Medium::BLUETOOTH, std::string(kServiceIdA));
ecm_.RegisterChannelForEndpoint(&client_, std::string(kEndpointId2),
std::move(channel));
client_.OnConnectionInitiated(std::string(kEndpointId2), response_info,
connection_options, {}, "token");
client_.LocalEndpointAcceptedConnection(std::string(kEndpointId2), {});
client_.RemoteEndpointAcceptedConnection(std::string(kEndpointId2));
EXPECT_TRUE(client_.IsConnectionAccepted(std::string(kEndpointId2)));
client_.OnConnectionAccepted(std::string(kEndpointId2));
EXPECT_TRUE(client_.IsConnectedToEndpoint(std::string(kEndpointId2)));
bwu_manager_->OnIncomingFrame(frame, std::string(kEndpointId2), &client_,
Medium::BLUETOOTH, packet_meta_data_);
CountDownLatch latch2(1);
// The BWU frame should be drop, so the IsUpgradeOngoing should be empty.
ASSERT_EQ(bwu_manager_->IsUpgradeOngoing(std::string(kEndpointId2)), false);
UnRegisterChannelForEndpoint(kEndpointId2);
}
INSTANTIATE_TEST_SUITE_P(BwuManagerTestParam, BwuManagerTestParam,
testing::Bool());
+276 -56
View File
@@ -15,27 +15,46 @@
#include "connections/implementation/client_proxy.h"
#include <cstdint>
#include <cstdlib>
#include <functional>
#include <ios>
#include <limits>
#include <memory>
#include <optional>
#include <ostream>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/functional/any_invocable.h"
#include "absl/strings/escaping.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "connections/advertising_options.h"
#include "connections/connection_options.h"
#include "connections/discovery_options.h"
#include "connections/implementation/analytics/analytics_recorder.h"
#include "connections/implementation/flags/nearby_connections_feature_flags.h"
#include "connections/listeners.h"
#include "connections/medium_selector.h"
#include "connections/payload.h"
#include "connections/status.h"
#include "connections/strategy.h"
#include "connections/v3/bandwidth_info.h"
#include "connections/v3/connection_listening_options.h"
#include "connections/v3/connection_result.h"
#include "connections/v3/connections_device.h"
#include "connections/v3/connections_device_provider.h"
#include "connections/v3/listeners.h"
#include "internal/analytics/event_logger.h"
#include "internal/flags/nearby_flags.h"
#include "internal/interop/device.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/cancelable_alarm.h"
#include "internal/platform/cancellation_flag.h"
#include "internal/platform/error_code_params.h"
#include "internal/platform/error_code_recorder.h"
#include "internal/platform/feature_flags.h"
#include "internal/platform/implementation/platform.h"
@@ -47,18 +66,26 @@
namespace nearby {
namespace connections {
namespace {
using ::location::nearby::connections::OsInfo;
// The definition is necessary before C++17.
constexpr absl::Duration
ClientProxy::kHighPowerAdvertisementEndpointIdCacheTimeout;
constexpr char kEndpointIdChars[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
bool IsFeatureUseStableEndpointIdEnabled() {
return NearbyFlags::GetInstance().GetBoolFlag(
connections::config_package_nearby::nearby_connections_feature::
kUseStableEndpointId);
}
} // namespace
// The definition is necessary before C++17.
constexpr absl::Duration
ClientProxy::kHighPowerAdvertisementEndpointIdCacheTimeout;
ClientProxy::ClientProxy(::nearby::analytics::EventLogger* event_logger)
: client_id_(Prng().NextInt64()) {
NEARBY_LOGS(INFO) << "ClientProxy ctor event_logger=" << event_logger;
@@ -73,9 +100,14 @@ ClientProxy::ClientProxy(::nearby::analytics::EventLogger* event_logger)
supports_safe_to_disconnect_ = NearbyFlags::GetInstance().GetBoolFlag(
config_package_nearby::nearby_connections_feature::
kEnableSafeToDisconnect);
support_auto_reconnect_ = NearbyFlags::GetInstance().GetBoolFlag(
config_package_nearby::nearby_connections_feature::kEnableAutoReconnect);
local_safe_to_disconnect_version_ = NearbyFlags::GetInstance().GetInt64Flag(
config_package_nearby::nearby_connections_feature::
kSafeToDisconnectVersion);
NEARBY_LOGS(INFO) << "[safe-to-disconnect]: Local enabled: "
<< supports_safe_to_disconnect_
<< "; Version: " << local_safe_to_disconnect_version_;
}
ClientProxy::~ClientProxy() { Reset(); }
@@ -85,13 +117,21 @@ std::int64_t ClientProxy::GetClientId() const { return client_id_; }
std::string ClientProxy::GetLocalEndpointId() {
MutexLock lock(&mutex_);
if (!local_endpoint_id_.empty()) {
NEARBY_LOGS(INFO) << __func__
<< ": Reusing cached endpoint id: " << local_endpoint_id_;
return local_endpoint_id_;
}
if (external_device_provider_ == nullptr) {
local_endpoint_id_ = GenerateLocalEndpointId();
NEARBY_LOGS(INFO) << __func__ << ": Locally generating endpoint id: "
<< local_endpoint_id_;
} else {
local_endpoint_id_ =
external_device_provider_->GetLocalDevice()->GetEndpointId();
NEARBY_LOGS(INFO)
<< __func__
<< ": From external device provider, populating endpoint id: "
<< local_endpoint_id_;
}
return local_endpoint_id_;
}
@@ -116,14 +156,39 @@ std::string ClientProxy::GetConnectionToken(const std::string& endpoint_id) {
return {};
}
std::optional<std::string> ClientProxy::GetBluetoothMacAddress(
const std::string& endpoint_id) {
auto item = bluetooth_mac_addresses_.find(endpoint_id);
if (item != bluetooth_mac_addresses_.end()) return item->second;
return std::nullopt;
}
void ClientProxy::SetBluetoothMacAddress(
const std::string& endpoint_id, const std::string& bluetooth_mac_address) {
bluetooth_mac_addresses_[endpoint_id] = bluetooth_mac_address;
}
std::string ClientProxy::GenerateLocalEndpointId() {
if (high_vis_mode_) {
if (!local_high_vis_mode_cache_endpoint_id_.empty()) {
NEARBY_LOGS(INFO)
<< "ClientProxy [Local Endpoint Re-using cached endpoint id]: client="
<< GetClientId() << "; local_high_vis_mode_cache_endpoint_id_="
<< local_high_vis_mode_cache_endpoint_id_;
return local_high_vis_mode_cache_endpoint_id_;
if (IsFeatureUseStableEndpointIdEnabled()) {
if (!cached_endpoint_id_.empty()) {
if (stable_endpoint_id_mode_) {
NEARBY_LOGS(INFO) << "ClientProxy [Local Endpoint Re-using cached "
"endpoint id due to in stable endpoint id mode]: "
"client="
<< GetClientId()
<< "; cached_endpoint_id_=" << cached_endpoint_id_;
return cached_endpoint_id_;
}
}
} else {
if (high_vis_mode_) {
if (!cached_endpoint_id_.empty()) {
NEARBY_LOGS(INFO) << "ClientProxy [Local Endpoint Re-using cached "
"endpoint id]: client="
<< GetClientId()
<< "; cached_endpoint_id_=" << cached_endpoint_id_;
return cached_endpoint_id_;
}
}
}
std::string id;
@@ -140,7 +205,11 @@ void ClientProxy::Reset() {
StoppedAdvertising();
StoppedDiscovery();
RemoveAllEndpoints();
ExitHighVisibilityMode();
if (IsFeatureUseStableEndpointIdEnabled()) {
ExitStableEndpointIdMode();
} else {
ExitHighVisibilityMode();
}
}
void ClientProxy::StartedAdvertising(
@@ -152,13 +221,22 @@ void ClientProxy::StartedAdvertising(
NEARBY_LOGS(INFO) << "ClientProxy [StartedAdvertising]: client="
<< GetClientId();
if (high_vis_mode_) {
local_high_vis_mode_cache_endpoint_id_ = local_endpoint_id_;
NEARBY_LOGS(INFO)
<< "ClientProxy [High Visibility Mode Adv, Cache EndpointId]: client="
<< GetClientId() << "; local_high_vis_mode_cache_endpoint_id_="
<< local_high_vis_mode_cache_endpoint_id_;
CancelClearLocalHighVisModeCacheEndpointIdAlarm();
if (IsFeatureUseStableEndpointIdEnabled()) {
if (stable_endpoint_id_mode_) {
cached_endpoint_id_ = local_endpoint_id_;
} else {
cached_endpoint_id_.clear();
}
CancelClearCachedEndpointIdAlarm();
} else {
if (high_vis_mode_) {
cached_endpoint_id_ = local_endpoint_id_;
NEARBY_LOGS(INFO)
<< "ClientProxy [High Visibility Mode Adv, Cache EndpointId]: client="
<< GetClientId() << "; cached_endpoint_id_=" << cached_endpoint_id_;
CancelClearCachedEndpointIdAlarm();
}
}
advertising_info_ = {service_id, listener};
@@ -182,7 +260,11 @@ void ClientProxy::StoppedAdvertising() {
// advertising_options_ is purposefully not cleared here.
OnSessionComplete();
ExitHighVisibilityMode();
if (IsFeatureUseStableEndpointIdEnabled()) {
ExitStableEndpointIdMode();
} else {
ExitHighVisibilityMode();
}
}
bool ClientProxy::IsAdvertising() const {
@@ -279,11 +361,11 @@ ConnectionListener ClientProxy::GetAdvertisingOrIncomingConnectionListener() {
void ClientProxy::StartedDiscovery(
const std::string& service_id, Strategy strategy,
const DiscoveryListener& listener,
DiscoveryListener listener,
absl::Span<location::nearby::proto::connections::Medium> mediums,
const DiscoveryOptions& discovery_options) {
MutexLock lock(&mutex_);
discovery_info_ = DiscoveryInfo{service_id, listener};
discovery_info_ = DiscoveryInfo{service_id, std::move(listener)};
discovery_options_ = discovery_options;
const std::vector<location::nearby::proto::connections::Medium> medium_vector(
@@ -360,10 +442,9 @@ void ClientProxy::OnEndpointLost(const std::string& service_id,
NEARBY_LOGS(INFO) << "ClientProxy [Endpoint Lost]: [enter] id=" << endpoint_id
<< "; service=" << service_id;
if (!IsDiscoveringServiceId(service_id)) {
NEARBY_LOG(INFO,
"ClientProxy [Endpoint Lost]: Ignoring event for id=%s because "
"this client is not discovering",
endpoint_id.c_str());
NEARBY_LOGS(INFO) << "ClientProxy [Endpoint Lost]: Ignoring event for id="
<< endpoint_id
<< " because this client is not discovering.";
return;
}
@@ -382,6 +463,7 @@ void ClientProxy::OnEndpointLost(const std::string& service_id,
void ClientProxy::OnRequestConnection(
const Strategy& strategy, const std::string& endpoint_id,
const ConnectionOptions& connection_options) {
NEARBY_LOGS(INFO) << "ClientProxy [RequestConnection]: id=" << endpoint_id;
analytics_recorder_->OnRequestConnection(strategy, endpoint_id);
}
@@ -433,6 +515,7 @@ void ClientProxy::OnConnectionInitiated(
}
void ClientProxy::OnConnectionAccepted(const std::string& endpoint_id) {
NEARBY_LOGS(INFO) << "ClientProxy [ConnectionAccepted]: id=" << endpoint_id;
MutexLock lock(&mutex_);
if (!HasPendingConnectionToEndpoint(endpoint_id)) {
@@ -452,6 +535,7 @@ void ClientProxy::OnConnectionAccepted(const std::string& endpoint_id) {
void ClientProxy::OnConnectionRejected(const std::string& endpoint_id,
const Status& status) {
NEARBY_LOGS(INFO) << "ClientProxy [ConnectionRejected]: id=" << endpoint_id;
MutexLock lock(&mutex_);
if (!HasPendingConnectionToEndpoint(endpoint_id)) {
@@ -471,6 +555,7 @@ void ClientProxy::OnConnectionRejected(const std::string& endpoint_id,
void ClientProxy::OnBandwidthChanged(const std::string& endpoint_id,
Medium new_medium) {
NEARBY_LOGS(INFO) << "ClientProxy [BandwidthChanged]: id=" << endpoint_id;
MutexLock lock(&mutex_);
const ConnectionPair* item = LookupConnection(endpoint_id);
@@ -483,6 +568,7 @@ void ClientProxy::OnBandwidthChanged(const std::string& endpoint_id,
}
void ClientProxy::OnDisconnected(const std::string& endpoint_id, bool notify) {
NEARBY_LOGS(INFO) << "ClientProxy [OnDisconnected]: id=" << endpoint_id;
MutexLock lock(&mutex_);
const ConnectionPair* item = LookupConnection(endpoint_id);
@@ -495,6 +581,12 @@ void ClientProxy::OnDisconnected(const std::string& endpoint_id, bool notify) {
}
CancelEndpoint(endpoint_id);
if (IsFeatureUseStableEndpointIdEnabled()) {
if (!stable_endpoint_id_mode_ && !HasOngoingConnection()) {
ScheduleClearCachedEndpointIdAlarm();
}
}
}
bool ClientProxy::ConnectionStatusMatches(const std::string& endpoint_id,
@@ -591,6 +683,11 @@ std::vector<std::string> ClientProxy::GetConnectedEndpoints() const {
});
}
bool ClientProxy::HasOngoingConnection() const {
return !GetPendingConnectedEndpoints().empty() ||
!GetConnectedEndpoints().empty();
}
std::int32_t ClientProxy::GetNumOutgoingConnections() const {
return GetMatchingEndpoints([](const Connection& connection) {
return connection.status == Connection::kConnected &&
@@ -607,6 +704,24 @@ std::int32_t ClientProxy::GetNumIncomingConnections() const {
.size();
}
bool ClientProxy::IsIncomingConnection(const std::string& endpoint_id) const {
MutexLock lock(&mutex_);
const ConnectionPair* item = LookupConnection(endpoint_id);
if (item != nullptr && item->first.status == Connection::kConnected) {
return item->first.is_incoming;
}
return false;
}
bool ClientProxy::IsOutgoingConnection(const std::string& endpoint_id) const {
MutexLock lock(&mutex_);
const ConnectionPair* item = LookupConnection(endpoint_id);
if (item != nullptr && item->first.status == Connection::kConnected) {
return !item->first.is_incoming;
}
return false;
}
bool ClientProxy::HasPendingConnectionToEndpoint(
const std::string& endpoint_id) const {
MutexLock lock(&mutex_);
@@ -641,15 +756,14 @@ bool ClientProxy::HasRemoteEndpointResponded(
void ClientProxy::LocalEndpointAcceptedConnection(
const std::string& endpoint_id, PayloadListener listener) {
MutexLock lock(&mutex_);
if (HasLocalEndpointResponded(endpoint_id)) {
NEARBY_LOGS(INFO)
<< "ClientProxy [Local Accepted]: local endpoint has responded; id="
<< endpoint_id;
return;
}
AppendConnectionStatus(endpoint_id, Connection::kLocalEndpointAccepted);
NEARBY_LOGS(INFO) << "ClientProxy [Local Accepted]: id=" << endpoint_id;
ConnectionPair* item = LookupConnection(endpoint_id);
if (item != nullptr) {
item->second = std::move(listener);
@@ -819,6 +933,7 @@ void ClientProxy::SetRemoteOsInfo(absl::string_view endpoint_id,
std::optional<std::int32_t> ClientProxy::GetRemoteSafeToDisconnectVersion(
absl::string_view endpoint_id) const {
MutexLock lock(&mutex_);
const ConnectionPair* item = LookupConnection(endpoint_id);
if (item != nullptr) {
return item->first.safe_to_disconnect_version;
@@ -829,6 +944,7 @@ std::optional<std::int32_t> ClientProxy::GetRemoteSafeToDisconnectVersion(
void ClientProxy::SetRemoteSafeToDisconnectVersion(
absl::string_view endpoint_id,
const std::int32_t& safe_to_disconnect_version) {
MutexLock lock(&mutex_);
ConnectionPair* item = LookupConnection(endpoint_id);
if (item != nullptr) {
item->first.safe_to_disconnect_version = safe_to_disconnect_version;
@@ -844,6 +960,15 @@ bool ClientProxy::IsSafeToDisconnectEnabled(absl::string_view endpoint_id) {
.min_nc_version_supports_safe_to_disconnect);
}
bool ClientProxy::IsAutoReconnectEnabled(absl::string_view endpoint_id) {
return IsSupportAutoReconnect() &&
GetRemoteSafeToDisconnectVersion(endpoint_id).has_value() &&
(GetRemoteSafeToDisconnectVersion(endpoint_id) >=
FeatureFlags::GetInstance()
.GetFlags()
.min_nc_version_supports_auto_reconnect);
}
bool ClientProxy::IsPayloadReceivedAckEnabled(absl::string_view endpoint_id) {
return IsSupportSafeToDisconnect() &&
GetRemoteSafeToDisconnectVersion(endpoint_id).has_value() &&
@@ -853,7 +978,6 @@ bool ClientProxy::IsPayloadReceivedAckEnabled(absl::string_view endpoint_id) {
.min_nc_version_supports_payload_received_ack);
}
void ClientProxy::CancelAllEndpoints() {
for (const auto& item : cancellation_flags_) {
CancellationFlag* cancellation_flag = item.second.get();
@@ -902,11 +1026,10 @@ void ClientProxy::OnPayloadProgress(const std::string& endpoint_id,
item->second.payload_progress_cb(endpoint_id, info);
if (info.status == PayloadProgressInfo::Status::kInProgress) {
NEARBY_LOGS(VERBOSE)
<< "ClientProxy [reporting onPayloadProgress]: client="
<< GetClientId() << "; endpoint_id=" << endpoint_id
<< "; payload_id=" << info.payload_id
<< ", payload_status=" << ToString(info.status);
NEARBY_VLOG(1) << "ClientProxy [reporting onPayloadProgress]: client="
<< GetClientId() << "; endpoint_id=" << endpoint_id
<< "; payload_id=" << info.payload_id
<< ", payload_status=" << ToString(info.status);
} else {
NEARBY_LOGS(INFO)
<< "ClientProxy [reporting onPayloadProgress]: client="
@@ -926,13 +1049,14 @@ void ClientProxy::RemoveAllEndpoints() {
// just remove without notifying.
connections_.clear();
cancellation_flags_.clear();
bluetooth_mac_addresses_.clear();
OnSessionComplete();
}
void ClientProxy::OnSessionComplete() {
MutexLock lock(&mutex_);
if (connections_.empty() && !IsAdvertising() && !IsDiscovering()) {
if (connections_.empty() && !IsAdvertising()) {
local_endpoint_id_.clear();
analytics_recorder_->LogSession();
@@ -984,16 +1108,40 @@ void ClientProxy::ExitHighVisibilityMode() {
<< GetClientId();
high_vis_mode_ = false;
ScheduleClearLocalHighVisModeCacheEndpointIdAlarm();
ScheduleClearCachedEndpointIdAlarm();
}
void ClientProxy::ScheduleClearLocalHighVisModeCacheEndpointIdAlarm() {
CancelClearLocalHighVisModeCacheEndpointIdAlarm();
void ClientProxy::EnterStableEndpointIdMode() {
MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << "ClientProxy [EnterStableEndpointIdMode]: client="
<< GetClientId();
if (local_high_vis_mode_cache_endpoint_id_.empty()) {
NEARBY_LOGS(VERBOSE) << "ClientProxy [There is no cached local high power "
"advertising endpoint Id]: client="
<< GetClientId();
stable_endpoint_id_mode_ = true;
}
void ClientProxy::ExitStableEndpointIdMode() {
MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << "ClientProxy [ExitStableEndpointIdMode]: client="
<< GetClientId();
stable_endpoint_id_mode_ = false;
ScheduleClearCachedEndpointIdAlarm();
}
void ClientProxy::ScheduleClearCachedEndpointIdAlarm() {
CancelClearCachedEndpointIdAlarm();
if (cached_endpoint_id_.empty()) {
NEARBY_VLOG(1) << "ClientProxy [There is no cached local high power "
"advertising endpoint Id]: client="
<< GetClientId();
return;
}
if (IsFeatureUseStableEndpointIdEnabled() && HasOngoingConnection()) {
NEARBY_VLOG(1) << "ClientProxy [Handle clearing cached endpoint ID "
"during disconnection]: client="
<< GetClientId();
return;
}
@@ -1002,9 +1150,8 @@ void ClientProxy::ScheduleClearLocalHighVisModeCacheEndpointIdAlarm() {
NEARBY_LOGS(INFO) << "ClientProxy [High Visibility Mode Adv, Schedule to "
"Clear Cache EndpointId]: client="
<< GetClientId()
<< "; local_high_vis_mode_cache_endpoint_id_="
<< local_high_vis_mode_cache_endpoint_id_;
clear_local_high_vis_mode_cache_endpoint_id_alarm_ =
<< "; cached_endpoint_id_=" << cached_endpoint_id_;
cached_endpoint_id_alarm_ =
std::make_unique<CancelableAlarm>(
"clear_high_power_endpoint_id_cache",
[this]() {
@@ -1012,19 +1159,18 @@ void ClientProxy::ScheduleClearLocalHighVisModeCacheEndpointIdAlarm() {
NEARBY_LOGS(INFO)
<< "ClientProxy [Cleared cached local high power advertising "
"endpoint Id.]: client="
<< GetClientId() << "; local_high_vis_mode_cache_endpoint_id_="
<< local_high_vis_mode_cache_endpoint_id_;
local_high_vis_mode_cache_endpoint_id_.clear();
<< GetClientId()
<< "; cached_endpoint_id_=" << cached_endpoint_id_;
cached_endpoint_id_.clear();
},
kHighPowerAdvertisementEndpointIdCacheTimeout,
&single_thread_executor_);
}
void ClientProxy::CancelClearLocalHighVisModeCacheEndpointIdAlarm() {
if (clear_local_high_vis_mode_cache_endpoint_id_alarm_ &&
clear_local_high_vis_mode_cache_endpoint_id_alarm_->IsValid()) {
clear_local_high_vis_mode_cache_endpoint_id_alarm_->Cancel();
clear_local_high_vis_mode_cache_endpoint_id_alarm_.reset();
void ClientProxy::CancelClearCachedEndpointIdAlarm() {
if (cached_endpoint_id_alarm_ && cached_endpoint_id_alarm_->IsValid()) {
cached_endpoint_id_alarm_->Cancel();
cached_endpoint_id_alarm_.reset();
}
}
@@ -1043,6 +1189,80 @@ OsInfo::OsType ClientProxy::OSNameToOsInfoType(api::OSName osName) {
}
}
std::int32_t ClientProxy::GetLocalMultiplexSocketBitmask() const {
if (NearbyFlags::GetInstance().GetBoolFlag(
config_package_nearby::nearby_connections_feature::
kEnableMultiplex)) {
NEARBY_LOGS(INFO) << "ClientProxy [GetLocalMultiplexSocketBitmask]: "
<< kBtMultiplexEnabled;
return kBtMultiplexEnabled;
}
return 0;
}
void ClientProxy::SetRemoteMultiplexSocketBitmask(
absl::string_view endpoint_id, int remote_multiplex_socket_bitmask) {
ConnectionPair* item = LookupConnection(endpoint_id);
if (item != nullptr) {
item->first.remote_multiplex_socket_bitmask =
remote_multiplex_socket_bitmask;
NEARBY_LOGS(INFO) << "ClientProxy [SetRemoteMultiplexSocketBitmask]: "
<< remote_multiplex_socket_bitmask;
}
}
bool ClientProxy::IsLocalMultiplexSocketSupported(Medium medium) {
int bitmask = GetLocalMultiplexSocketBitmask();
switch (medium) {
case Medium::BLUETOOTH:
NEARBY_LOGS(INFO) << "ClientProxy [IsLocalMultiplexSocketSupported]: "
<< (bitmask & kBtMultiplexEnabled);
return (bitmask & kBtMultiplexEnabled) != 0;
case Medium::WIFI_LAN:
return (bitmask & kWifiLanMultiplexEnabled) != 0;
default:
return false;
}
}
std::optional<std::int32_t> ClientProxy::GetRemoteMultiplexSocketBitmask(
absl::string_view endpoint_id) const {
const ConnectionPair* item = LookupConnection(endpoint_id);
if (item != nullptr) {
return item->first.remote_multiplex_socket_bitmask;
}
return std::nullopt;
}
bool ClientProxy::IsMultiplexSocketSupported(absl::string_view endpoint_id,
Medium medium) {
ConnectionPair* item = LookupConnection(endpoint_id);
if (item == nullptr) {
return false;
}
int combined_result = GetLocalMultiplexSocketBitmask() &
item->first.remote_multiplex_socket_bitmask;
switch (medium) {
case Medium::BLUETOOTH:
return (combined_result & kBtMultiplexEnabled) != 0;
case Medium::WIFI_LAN:
return (combined_result & kWifiLanMultiplexEnabled) != 0;
default:
return false;
}
}
bool ClientProxy::GetWebRtcNonCellular() { return webrtc_non_cellular_; }
void ClientProxy::SetWebRtcNonCellular(bool webrtc_non_cellular) {
std::string allow_webrtc_cellular_str =
webrtc_non_cellular ? "disallow" : "allow";
NEARBY_LOGS(INFO) << "ClientProxy: client=" << GetClientId()
<< allow_webrtc_cellular_str << " to use mobile data.",
webrtc_non_cellular_ = webrtc_non_cellular;
}
std::string ClientProxy::ToString(PayloadProgressInfo::Status status) const {
switch (status) {
case PayloadProgressInfo::Status::kSuccess:
+80 -14
View File
@@ -23,11 +23,16 @@
#include <vector>
#include "absl/functional/any_invocable.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "connections/advertising_options.h"
#include "connections/connection_options.h"
#include "connections/discovery_options.h"
#include "connections/implementation/analytics/analytics_recorder.h"
#include "connections/implementation/proto/offline_wire_formats.pb.h"
#include "connections/listeners.h"
#include "connections/medium_selector.h"
#include "connections/payload.h"
#include "connections/status.h"
#include "connections/strategy.h"
#include "connections/v3/connection_listening_options.h"
@@ -46,6 +51,8 @@
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/types/span.h"
#include "internal/platform/os_name.h"
#include "internal/platform/scheduled_executor.h"
namespace nearby {
namespace connections {
@@ -74,6 +81,10 @@ class ClientProxy final {
}
std::string GetConnectionToken(const std::string& endpoint_id);
std::optional<std::string> GetBluetoothMacAddress(
const std::string& endpoint_id);
void SetBluetoothMacAddress(const std::string& endpoint_id,
const std::string& bluetooth_mac_address);
const NearbyDevice* GetLocalDevice();
NearbyDeviceProvider* GetLocalDeviceProvider() {
if (external_device_provider_ != nullptr) {
@@ -110,7 +121,7 @@ class ClientProxy final {
// Marks this client as discovering with the given callback.
void StartedDiscovery(
const std::string& service_id, Strategy strategy,
const DiscoveryListener& discovery_listener,
DiscoveryListener discovery_listener,
absl::Span<location::nearby::proto::connections::Medium> mediums,
const DiscoveryOptions& discovery_options = DiscoveryOptions{});
// Marks this client as not discovering at all.
@@ -184,10 +195,17 @@ class ClientProxy final {
std::vector<std::string> GetConnectedEndpoints() const;
// Returns all endpoints that are still awaiting acceptance.
std::vector<std::string> GetPendingConnectedEndpoints() const;
// Returns true if there is at least one connected connection or one pending
// connection.
bool HasOngoingConnection() const;
// Returns the number of endpoints that are connected and outgoing.
std::int32_t GetNumOutgoingConnections() const;
// Returns the number of endpoints that are connected and incoming.
std::int32_t GetNumIncomingConnections() const;
// Returns true if endpoint is incoming connection.
bool IsIncomingConnection(const std::string& endpoint_id) const;
// Returns true if endpoint is outgoing connection.
bool IsOutgoingConnection(const std::string& endpoint_id) const;
// If true, then we're in the process of approving (or rejecting) a
// connection. No payloads should be sent until isConnectedToEndpoint()
// returns true.
@@ -249,6 +267,12 @@ class ClientProxy final {
// rotates.
void ExitHighVisibilityMode();
// Enters stable endpoint ID mode.
void EnterStableEndpointIdMode();
// Cleans up any modifications in stable endpoint ID mode. The endpoint id
// always rotates.
void ExitStableEndpointIdMode();
std::string Dump();
const location::nearby::connections::OsInfo& GetLocalOsInfo() const;
@@ -270,6 +294,9 @@ class ClientProxy final {
const bool& IsSupportSafeToDisconnect() const {
return supports_safe_to_disconnect_;
}
bool IsSupportAutoReconnect() const { return support_auto_reconnect_; }
const std::int32_t& GetLocalSafeToDisconnectVersion() const {
return local_safe_to_disconnect_version_;
}
@@ -279,8 +306,41 @@ class ClientProxy final {
absl::string_view endpoint_id,
const std::int32_t& safe_to_disconnect_version);
bool IsSafeToDisconnectEnabled(absl::string_view endpoint_id);
bool IsAutoReconnectEnabled(absl::string_view endpoint_id);
bool IsPayloadReceivedAckEnabled(absl::string_view endpoint_id);
// Returns the multiplex socket supports status for local device.
std::int32_t GetLocalMultiplexSocketBitmask() const;
// Sets the multiplex socket supports status for remote device.
void SetRemoteMultiplexSocketBitmask(absl::string_view endpoint_id,
int remote_multiplex_socket_bitmask);
// Returns true if the multiplex socket is supported for the given medium.
bool IsLocalMultiplexSocketSupported(Medium medium);
// Gets the multiplex socket supports status for remote device.
std::optional<std::int32_t> GetRemoteMultiplexSocketBitmask(
absl::string_view endpoint_id) const;
// Returns true if the multiplex socket is supported for the given medium.
bool IsMultiplexSocketSupported(absl::string_view endpoint_id, Medium medium);
// Gets the WebRTC non cellular network status.
bool GetWebRtcNonCellular();
// Sets the WebRTC non cellular network status.
void SetWebRtcNonCellular(bool webrtc_non_cellular);
/** Bitmask for bt multiplex connection support. */
// Note. Deprecates the first and second bit of BT_MULTIPLEX_ENABLED and
// WIFI_LAN_MULTIPLEX_ENABLED and shift them to the third and the forth bit.
// The reason is we need to escape the (0, 1) bit which has been set in some
// devices without salt enabled. If accompany with the devices with salted
// enabled, the frames passed cannot be decrypted and the connection shall be
// failed. Please refer to b/295925531#comment#14 for the details.
enum MultiplexSocketBitmask : uint32_t {
kBtMultiplexEnabled = 1 << 2,
kWifiLanMultiplexEnabled = 1 << 3,
};
private:
struct Connection {
// Status: may be either:
@@ -311,6 +371,7 @@ class ClientProxy final {
std::string connection_token;
std::optional<location::nearby::connections::OsInfo> os_info;
std::int32_t safe_to_disconnect_version;
std::int32_t remote_multiplex_socket_bitmask;
};
using ConnectionPair = std::pair<Connection, PayloadListener>;
@@ -356,8 +417,8 @@ class ClientProxy final {
absl::AnyInvocable<bool(const Connection&)> pred) const;
std::string GenerateLocalEndpointId();
void ScheduleClearLocalHighVisModeCacheEndpointIdAlarm();
void CancelClearLocalHighVisModeCacheEndpointIdAlarm();
void ScheduleClearCachedEndpointIdAlarm();
void CancelClearCachedEndpointIdAlarm();
location::nearby::connections::OsInfo::OsType OSNameToOsInfoType(
api::OSName osName);
@@ -373,18 +434,17 @@ class ClientProxy final {
// id is stable for 30s. When high_visibility_mode_ is false, the endpoint id
// always rotates.
bool high_vis_mode_ = false;
// Caches the endpoint id when it is in high visibility mode advertisement for
// 30s. Currently, Nearby Connections keeps rotating endpoint id. The client
// (Nearby Share) treats different endpoints as different receivers, duplicate
// share targets for same devices occur on share sheet in this case.
// Therefore, we remember the high visibility mode advertisement endpoint id
// here. empty if 1) There is no high power advertisement before 2) The
// endpoint id cached here in previous high visibility mode advertisement
// expires.
std::string local_high_vis_mode_cache_endpoint_id_;
// If advertising is in stable endpoint ID mode, the endpoint ID is stable
// for 30s after advertising or disconnection. When stable_endpoint_id_mode_
// is false, the endpoint id always rotates.
bool stable_endpoint_id_mode_ = false;
// Caches the endpoint id for stable endpoint ID mode.
std::string cached_endpoint_id_;
ScheduledExecutor single_thread_executor_;
std::unique_ptr<CancelableAlarm>
clear_local_high_vis_mode_cache_endpoint_id_alarm_;
std::unique_ptr<CancelableAlarm> cached_endpoint_id_alarm_;
// If not empty, we are currently advertising and accepting connection
// requests for the given service_id.
@@ -415,6 +475,9 @@ class ClientProxy final {
// Maps endpoint_id to endpoint connection state.
absl::flat_hash_map<std::string, ConnectionPair> connections_;
// Maps endpoint_id to Bluetooth Mac Addresses.
absl::flat_hash_map<std::string, std::string> bluetooth_mac_addresses_;
// A cache of endpoint ids that we've already notified the discoverer of. We
// check this cache before calling onEndpointFound() so that we don't notify
// the client multiple times for the same endpoint. This would otherwise
@@ -443,7 +506,10 @@ class ClientProxy final {
// For Nearby Connections' own device provider.
std::unique_ptr<v3::ConnectionsDeviceProvider> connections_device_provider_;
bool supports_safe_to_disconnect_;
bool support_auto_reconnect_;
std::int32_t local_safe_to_disconnect_version_;
// Allowed to use WebRTC over non-cellular networks.
bool webrtc_non_cellular_ = false;
};
} // namespace connections
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More