mirror of
https://github.com/kidfromjupiter/nearby.git
synced 2026-09-16 15:36:12 -04:00
nearby: snapshot as of cl/296436629
Signed-off-by: Alexey Polyudov <apolyudov@google.com> Change-Id: I2cf5bf225b76f4c1541954651f3a7544a14e0cec
This commit is contained in:
@@ -0,0 +1,107 @@
|
||||
cc_library(
|
||||
name = "mediums",
|
||||
srcs = [
|
||||
"ble_advertisement.cc",
|
||||
"ble_advertisement_header.cc",
|
||||
"ble_packet.cc",
|
||||
"ble_peripheral.cc",
|
||||
"utils.cc",
|
||||
"utils.h",
|
||||
],
|
||||
hdrs = [
|
||||
"advertisement_read_result.cc",
|
||||
"advertisement_read_result.h",
|
||||
"ble.cc",
|
||||
"ble.h",
|
||||
"ble_advertisement.h",
|
||||
"ble_advertisement_header.h",
|
||||
"ble_packet.h",
|
||||
"ble_peripheral.h",
|
||||
"ble_v2.cc",
|
||||
"ble_v2.h",
|
||||
"bloom_filter.cc",
|
||||
"bloom_filter.h",
|
||||
"bluetooth_classic.cc",
|
||||
"bluetooth_classic.h",
|
||||
"bluetooth_radio.cc",
|
||||
"bluetooth_radio.h",
|
||||
"discovered_peripheral_callback.h",
|
||||
"discovered_peripheral_tracker.cc",
|
||||
"discovered_peripheral_tracker.h",
|
||||
"lost_entity_tracker.cc",
|
||||
"lost_entity_tracker.h",
|
||||
"mediums.cc",
|
||||
"mediums.h",
|
||||
"uuid.cc",
|
||||
"uuid.h",
|
||||
],
|
||||
visibility = ["//core/internal:__pkg__"],
|
||||
deps = [
|
||||
"//platform:logging",
|
||||
"//platform:types",
|
||||
"//platform:utils",
|
||||
"//platform/api",
|
||||
"//platform/port:string",
|
||||
"//absl/numeric:int128",
|
||||
"//absl/strings",
|
||||
"//smhasher:libmurmur3",
|
||||
],
|
||||
)
|
||||
|
||||
cc_test(
|
||||
name = "advertisement_read_result_test",
|
||||
srcs = ["advertisement_read_result_test.cc"],
|
||||
deps = [
|
||||
":mediums",
|
||||
"//platform/impl/default",
|
||||
"//testing/base/public:gunit_main",
|
||||
"//absl/time",
|
||||
],
|
||||
)
|
||||
|
||||
cc_test(
|
||||
name = "ble_advertisement_header_test",
|
||||
srcs = ["ble_advertisement_header_test.cc"],
|
||||
deps = [
|
||||
":mediums",
|
||||
"//platform:utils",
|
||||
"//testing/base/public:gunit_main",
|
||||
],
|
||||
)
|
||||
|
||||
cc_test(
|
||||
name = "ble_advertisement_test",
|
||||
srcs = ["ble_advertisement_test.cc"],
|
||||
deps = [
|
||||
":mediums",
|
||||
"//testing/base/public:gunit_main",
|
||||
],
|
||||
)
|
||||
|
||||
cc_test(
|
||||
name = "ble_packet_test",
|
||||
srcs = ["ble_packet_test.cc"],
|
||||
deps = [
|
||||
":mediums",
|
||||
"//testing/base/public:gunit_main",
|
||||
],
|
||||
)
|
||||
|
||||
cc_test(
|
||||
name = "bloom_filter_test",
|
||||
srcs = ["bloom_filter_test.cc"],
|
||||
deps = [
|
||||
":mediums",
|
||||
"//testing/base/public:gunit_main",
|
||||
],
|
||||
)
|
||||
|
||||
cc_test(
|
||||
name = "lost_entity_tracker_test",
|
||||
srcs = ["lost_entity_tracker_test.cc"],
|
||||
deps = [
|
||||
":mediums",
|
||||
"//platform/impl/default",
|
||||
"//testing/base/public:gunit_main",
|
||||
],
|
||||
)
|
||||
@@ -0,0 +1,186 @@
|
||||
#include "core/internal/mediums/advertisement_read_result.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include "platform/synchronized.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
namespace {
|
||||
|
||||
template <typename K, typename V>
|
||||
void eraseOwnedPtrFromMap(std::map<K, ConstPtr<V> >& m, const K& k) {
|
||||
typename std::map<K, ConstPtr<V> >::iterator it = m.find(k);
|
||||
if (it != m.end()) {
|
||||
it->second.destroy();
|
||||
m.erase(it);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// How much to multiply the backoff duration by with every failure to read
|
||||
// from the advertisement GATT server. This should never be below 1!
|
||||
template <typename Platform>
|
||||
const float AdvertisementReadResult<Platform>::kAdvertisementBackoffMultiplier =
|
||||
2.0;
|
||||
|
||||
// The initial backoff duration when we fail to read from an advertisement
|
||||
// GATT server.
|
||||
template <typename Platform>
|
||||
const std::int64_t
|
||||
AdvertisementReadResult<Platform>::kAdvertisementBaseBackoffDurationMillis =
|
||||
1 * 1000; // 1 second
|
||||
|
||||
// The maximum backoff duration allowed between advertisement GATT server
|
||||
// reads.
|
||||
template <typename Platform>
|
||||
const std::int64_t
|
||||
AdvertisementReadResult<Platform>::kAdvertisementMaxBackoffDurationMillis =
|
||||
5 * 60 * 1000; // 5 minutes
|
||||
|
||||
template <typename Platform>
|
||||
AdvertisementReadResult<Platform>::AdvertisementReadResult()
|
||||
: lock_(Platform::createLock()),
|
||||
system_clock_(Platform::createSystemClock()),
|
||||
advertisements_(),
|
||||
backoff_duration_millis_(kAdvertisementBaseBackoffDurationMillis),
|
||||
// We need a long enough duration such that we always trigger a read
|
||||
// retry AND we always connect to it without delay. The former case
|
||||
// helps us initialize an AdvertisementReadResult so that we
|
||||
// unconditionally try reading on the first sighting. And the latter
|
||||
// case helps us connect immediately when we initialize a dummy read
|
||||
// result for fast advertisements (which don't use the GATT server).
|
||||
last_read_timestamp_millis_(system_clock_->elapsedRealtime() -
|
||||
kAdvertisementMaxBackoffDurationMillis),
|
||||
result_(Result::Value::UNKNOWN) {}
|
||||
|
||||
template <typename Platform>
|
||||
AdvertisementReadResult<Platform>::~AdvertisementReadResult() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
for (AdvertisementMap::iterator it = advertisements_.begin();
|
||||
it != advertisements_.end(); ++it) {
|
||||
it->second.destroy();
|
||||
}
|
||||
advertisements_.clear();
|
||||
}
|
||||
|
||||
// Adds a successfully read advertisement for the specified slot to this read
|
||||
// result. This is fundamentally different from
|
||||
// {@link #recordLastReadStatus(boolean)} because we can report a read
|
||||
// failure, but still manage to read some advertisements.
|
||||
// Note: advertisement should be passed in as a RefCounted Ptr. It is not the
|
||||
// responsibility of AdvertisementReadResult to make it RefCounted.
|
||||
template <typename Platform>
|
||||
void AdvertisementReadResult<Platform>::addAdvertisement(
|
||||
std::int32_t slot, /* RefCounted */ ConstPtr<ByteArray> advertisement) {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray>> scoped_advertisement(advertisement);
|
||||
|
||||
// Blindly remove from the advertisements map to make sure any existing
|
||||
// key-value pair is destroyed.
|
||||
eraseOwnedPtrFromMap(advertisements_, slot);
|
||||
|
||||
advertisements_.insert(std::make_pair(slot, scoped_advertisement.release()));
|
||||
}
|
||||
|
||||
// Determines whether or not an advertisement was successfully read at the
|
||||
// specified slot.
|
||||
template <typename Platform>
|
||||
bool AdvertisementReadResult<Platform>::hasAdvertisement(std::int32_t slot) {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
return advertisements_.find(slot) != advertisements_.end();
|
||||
}
|
||||
|
||||
// Retrieves all raw advertisements that were successfully read.
|
||||
template <typename Platform>
|
||||
std::set<ConstPtr<ByteArray>>
|
||||
AdvertisementReadResult<Platform>::getAdvertisements() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
std::set<ConstPtr<ByteArray>> all_advertisements;
|
||||
for (AdvertisementMap::iterator it = advertisements_.begin();
|
||||
it != advertisements_.end(); ++it) {
|
||||
all_advertisements.insert(it->second);
|
||||
}
|
||||
|
||||
return all_advertisements;
|
||||
}
|
||||
|
||||
// Determines what stage we're in for retrying a read from an advertisement
|
||||
// GATT server.
|
||||
template <typename Platform>
|
||||
typename AdvertisementReadResult<Platform>::RetryStatus::Value
|
||||
AdvertisementReadResult<Platform>::evaluateRetryStatus() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
// Check if we have already succeeded reading this advertisement.
|
||||
if (result_ == Result::SUCCESS) {
|
||||
return RetryStatus::PREVIOUSLY_SUCCEEDED;
|
||||
}
|
||||
|
||||
// Check if we have recently failed to read this advertisement.
|
||||
if (getDurationSinceReadMillis() < backoff_duration_millis_) {
|
||||
return RetryStatus::TOO_SOON;
|
||||
}
|
||||
|
||||
return RetryStatus::RETRY;
|
||||
}
|
||||
|
||||
// Records the status of the latest read, and updates the next backoff
|
||||
// duration for subsequent reads. Be sure to also call
|
||||
// {@link #addAdvertisement(int, byte[])} if any advertisements were read.
|
||||
template <typename Platform>
|
||||
void AdvertisementReadResult<Platform>::recordLastReadStatus(bool is_success) {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
// Update the last read timestamp.
|
||||
last_read_timestamp_millis_ = system_clock_->elapsedRealtime();
|
||||
|
||||
// Update the backoff duration.
|
||||
if (is_success) {
|
||||
// Reset the backoff duration now that we had a successful read.
|
||||
backoff_duration_millis_ = kAdvertisementBaseBackoffDurationMillis;
|
||||
} else {
|
||||
// Determine whether or not we were already failing before. If we were, we
|
||||
// should increase the backoff duration.
|
||||
if (result_ == Result::FAILURE) {
|
||||
// Use exponential backoff to determine the next backoff duration. This
|
||||
// simply involves multiplying our current backoff duration by some
|
||||
// multiplier.
|
||||
std::int64_t next_backoff_duration =
|
||||
kAdvertisementBackoffMultiplier * backoff_duration_millis_;
|
||||
// Update the backoff duration, making sure not to blow past the
|
||||
// ceiling.
|
||||
backoff_duration_millis_ = std::min(
|
||||
next_backoff_duration, kAdvertisementMaxBackoffDurationMillis);
|
||||
} else {
|
||||
// This is our first time failing, so we should only backoff for the
|
||||
// initial duration.
|
||||
backoff_duration_millis_ = kAdvertisementBaseBackoffDurationMillis;
|
||||
}
|
||||
}
|
||||
|
||||
// Update the internal result.
|
||||
result_ = is_success ? Result::SUCCESS : Result::FAILURE;
|
||||
}
|
||||
|
||||
// Returns how much time has passed since we last tried reading from an
|
||||
// advertisement GATT server.
|
||||
template <typename Platform>
|
||||
std::int64_t AdvertisementReadResult<Platform>::getDurationSinceReadMillis() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
return system_clock_->elapsedRealtime() - last_read_timestamp_millis_;
|
||||
}
|
||||
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
@@ -0,0 +1,73 @@
|
||||
#ifndef CORE_INTERNAL_MEDIUMS_ADVERTISEMENT_READ_RESULT_H_
|
||||
#define CORE_INTERNAL_MEDIUMS_ADVERTISEMENT_READ_RESULT_H_
|
||||
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <set>
|
||||
|
||||
#include "platform/api/lock.h"
|
||||
#include "platform/api/system_clock.h"
|
||||
#include "platform/byte_array.h"
|
||||
#include "platform/ptr.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
// Representation of a GATT advertisement read result. This object helps us
|
||||
// determine whether or not we need to retry GATT reads.
|
||||
template <typename Platform>
|
||||
class AdvertisementReadResult {
|
||||
public:
|
||||
AdvertisementReadResult();
|
||||
~AdvertisementReadResult();
|
||||
|
||||
struct RetryStatus {
|
||||
enum Value {
|
||||
UNKNOWN = 0,
|
||||
RETRY = 1,
|
||||
PREVIOUSLY_SUCCEEDED = 2,
|
||||
TOO_SOON = 3,
|
||||
};
|
||||
};
|
||||
|
||||
void addAdvertisement(std::int32_t slot, ConstPtr<ByteArray> advertisement);
|
||||
bool hasAdvertisement(std::int32_t slot);
|
||||
std::set<ConstPtr<ByteArray>> getAdvertisements();
|
||||
typename RetryStatus::Value evaluateRetryStatus();
|
||||
void recordLastReadStatus(bool is_success);
|
||||
std::int64_t getDurationSinceReadMillis();
|
||||
|
||||
private:
|
||||
struct Result {
|
||||
enum Value { UNKNOWN = 0, SUCCESS = 1, FAILURE = 2 };
|
||||
};
|
||||
|
||||
static const float kAdvertisementBackoffMultiplier;
|
||||
static const std::int64_t kAdvertisementBaseBackoffDurationMillis;
|
||||
static const std::int64_t kAdvertisementMaxBackoffDurationMillis;
|
||||
|
||||
// ------------ GENERAL ------------
|
||||
ScopedPtr<Ptr<Lock>> lock_;
|
||||
ScopedPtr<Ptr<SystemClock>> system_clock_;
|
||||
|
||||
// ------ ADVERTISEMENTREADRESULT STATE ------
|
||||
// Maps slot numbers to the GATT advertisement found in that slot.
|
||||
typedef std::map<std::int32_t, /* RefCounted */ ConstPtr<ByteArray>>
|
||||
AdvertisementMap;
|
||||
AdvertisementMap advertisements_;
|
||||
|
||||
std::int64_t backoff_duration_millis_;
|
||||
std::int64_t last_read_timestamp_millis_;
|
||||
typename Result::Value result_;
|
||||
};
|
||||
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
|
||||
#include "core/internal/mediums/advertisement_read_result.cc"
|
||||
|
||||
#endif // CORE_INTERNAL_MEDIUMS_ADVERTISEMENT_READ_RESULT_H_
|
||||
@@ -0,0 +1,148 @@
|
||||
#include "core/internal/mediums/advertisement_read_result.h"
|
||||
|
||||
#include "platform/impl/default/default_platform.h"
|
||||
#include "gtest/gtest.h"
|
||||
#include "absl/time/clock.h"
|
||||
#include "absl/time/time.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
namespace {
|
||||
|
||||
class SampleSystemClock : public SystemClock {
|
||||
public:
|
||||
SampleSystemClock() {}
|
||||
~SampleSystemClock() override {}
|
||||
|
||||
std::int64_t elapsedRealtime() override {
|
||||
return absl::ToUnixMillis(absl::Now());
|
||||
}
|
||||
};
|
||||
|
||||
class SamplePlatform {
|
||||
public:
|
||||
static Ptr<Lock> createLock() { return DefaultPlatform::createLock(); }
|
||||
static Ptr<SystemClock> createSystemClock() {
|
||||
return MakePtr(new SampleSystemClock());
|
||||
}
|
||||
};
|
||||
|
||||
// We keep a copy of these constants because this is an old-school test (so we
|
||||
// can't delare it as a friend class of AdvertisementReadResult).
|
||||
const absl::Duration kAdvertisementBaseBackoffDuration =
|
||||
absl::Milliseconds(1000); // 1 second
|
||||
const absl::Duration kAdvertisementMaxBackoffDuration =
|
||||
absl::Milliseconds(6000); // 6 seconds
|
||||
const char kAdvertisementBytes[] = {0x0A, 0x0B, 0x0C};
|
||||
|
||||
TEST(AdvertisementReadResultTest, AdvertisementExists) {
|
||||
AdvertisementReadResult<SamplePlatform> advertisement_read_result;
|
||||
advertisement_read_result.recordLastReadStatus(/* is_success= */ true);
|
||||
|
||||
std::int32_t slot = 6;
|
||||
advertisement_read_result.addAdvertisement(
|
||||
slot,
|
||||
MakeConstPtr(new ByteArray(kAdvertisementBytes,
|
||||
sizeof(kAdvertisementBytes) / sizeof(char))));
|
||||
|
||||
ASSERT_TRUE(advertisement_read_result.hasAdvertisement(slot));
|
||||
}
|
||||
|
||||
TEST(AdvertisementReadResultTest, AdvertisementNonExistent) {
|
||||
AdvertisementReadResult<SamplePlatform> advertisement_read_result;
|
||||
advertisement_read_result.recordLastReadStatus(/* is_success= */ true);
|
||||
|
||||
std::int32_t slot = 6;
|
||||
|
||||
ASSERT_FALSE(advertisement_read_result.hasAdvertisement(slot));
|
||||
}
|
||||
|
||||
TEST(AdvertisementReadResultTest, EvaluateRetryStatusInitialized) {
|
||||
AdvertisementReadResult<SamplePlatform> advertisement_read_result;
|
||||
|
||||
ASSERT_EQ(advertisement_read_result.evaluateRetryStatus(),
|
||||
AdvertisementReadResult<SamplePlatform>::RetryStatus::RETRY);
|
||||
}
|
||||
|
||||
TEST(AdvertisementReadResultTest, EvaluateRetryStatusSuccess) {
|
||||
AdvertisementReadResult<SamplePlatform> advertisement_read_result;
|
||||
advertisement_read_result.recordLastReadStatus(/* is_success= */ true);
|
||||
|
||||
ASSERT_EQ(advertisement_read_result.evaluateRetryStatus(),
|
||||
AdvertisementReadResult<
|
||||
SamplePlatform>::RetryStatus::PREVIOUSLY_SUCCEEDED);
|
||||
}
|
||||
|
||||
TEST(AdvertisementReadResultTest, EvaluateRetryStatusTooSoon) {
|
||||
AdvertisementReadResult<SamplePlatform> advertisement_read_result;
|
||||
advertisement_read_result.recordLastReadStatus(/* is_success= */ false);
|
||||
|
||||
// Sleep for some time, but not long enough to warrant a retry.
|
||||
absl::SleepFor(absl::Milliseconds(
|
||||
absl::ToInt64Milliseconds(kAdvertisementBaseBackoffDuration) / 2));
|
||||
|
||||
ASSERT_EQ(advertisement_read_result.evaluateRetryStatus(),
|
||||
AdvertisementReadResult<SamplePlatform>::RetryStatus::TOO_SOON);
|
||||
}
|
||||
|
||||
TEST(AdvertisementReadResultTest, EvaluateRetryStatusRetry) {
|
||||
AdvertisementReadResult<SamplePlatform> advertisement_read_result;
|
||||
advertisement_read_result.recordLastReadStatus(/* is_success= */ false);
|
||||
|
||||
// Sleep long enough to warrant a retry.
|
||||
absl::SleepFor(kAdvertisementBaseBackoffDuration);
|
||||
|
||||
ASSERT_EQ(advertisement_read_result.evaluateRetryStatus(),
|
||||
AdvertisementReadResult<SamplePlatform>::RetryStatus::RETRY);
|
||||
}
|
||||
|
||||
TEST(AdvertisementReadResultTest, ReportStatusExponentialBackoff) {
|
||||
AdvertisementReadResult<SamplePlatform> advertisement_read_result;
|
||||
advertisement_read_result.recordLastReadStatus(/* is_success= */ false);
|
||||
|
||||
// Record an additional failure so our backoff duration increases.
|
||||
advertisement_read_result.recordLastReadStatus(/* is_success= */ false);
|
||||
|
||||
// Sleep for the backoff duration. We shouldn't trigger a retry because the
|
||||
// backoff should have increased from failing a second time.
|
||||
absl::SleepFor(kAdvertisementBaseBackoffDuration);
|
||||
|
||||
ASSERT_EQ(advertisement_read_result.evaluateRetryStatus(),
|
||||
AdvertisementReadResult<SamplePlatform>::RetryStatus::TOO_SOON);
|
||||
}
|
||||
|
||||
TEST(AdvertisementReadResultTest, ReportStatusExponentialBackoffMax) {
|
||||
AdvertisementReadResult<SamplePlatform> advertisement_read_result;
|
||||
advertisement_read_result.recordLastReadStatus(/* is_success= */ false);
|
||||
|
||||
// Record an absurd amount of failures so we hit the maximum backoff duration.
|
||||
for (std::int32_t i = 0; i < 1000; i++) {
|
||||
advertisement_read_result.recordLastReadStatus(/* is_success= */ false);
|
||||
}
|
||||
|
||||
// Sleep for the maximum backoff duration. This should be enough to warrant a
|
||||
// retry.
|
||||
absl::SleepFor(kAdvertisementMaxBackoffDuration);
|
||||
|
||||
ASSERT_EQ(advertisement_read_result.evaluateRetryStatus(),
|
||||
AdvertisementReadResult<SamplePlatform>::RetryStatus::RETRY);
|
||||
}
|
||||
|
||||
TEST(AdvertisementReadResultTest, GetDurationSinceRead) {
|
||||
AdvertisementReadResult<SamplePlatform> advertisement_read_result;
|
||||
advertisement_read_result.recordLastReadStatus(/* is_success= */ true);
|
||||
|
||||
std::int64_t sleepTime = 420;
|
||||
absl::SleepFor(absl::Milliseconds(sleepTime));
|
||||
|
||||
ASSERT_GE(advertisement_read_result.getDurationSinceReadMillis(), sleepTime);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
@@ -0,0 +1,281 @@
|
||||
#include "core/internal/mediums/ble.h"
|
||||
|
||||
#include "platform/synchronized.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
|
||||
template <typename Platform>
|
||||
const std::int32_t BLE<Platform>::kMaxAdvertisementLength = 512;
|
||||
|
||||
template <typename Platform>
|
||||
BLE<Platform>::BLE(Ptr<BluetoothRadio<Platform>> bluetooth_radio)
|
||||
: lock_(Platform::createLock()),
|
||||
bluetooth_radio_(bluetooth_radio),
|
||||
bluetooth_adapter_(Platform::createBluetoothAdapter()),
|
||||
ble_medium_(Platform::createBLEMedium()),
|
||||
scanning_info_(),
|
||||
advertising_info_(),
|
||||
accepting_connections_info_() {}
|
||||
|
||||
template <typename Platform>
|
||||
BLE<Platform>::~BLE() {
|
||||
stopAdvertising();
|
||||
stopAcceptingConnections();
|
||||
stopScanning();
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BLE<Platform>::isAvailable() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
return !ble_medium_.isNull() && !bluetooth_adapter_.isNull();
|
||||
}
|
||||
|
||||
// TODO(ahlee): Add fastPairData for phase 2 of C++ implementation.
|
||||
template <typename Platform>
|
||||
bool BLE<Platform>::startAdvertising(const string& service_id,
|
||||
ConstPtr<ByteArray> advertisement) {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
// Avoid leaks.
|
||||
ScopedPtr<ConstPtr<ByteArray>> scoped_advertisement(advertisement);
|
||||
if (scoped_advertisement.isNull() || service_id.empty()) {
|
||||
// TODO(ahlee): logger.atSevere().log("Refusing to start BLE advertising
|
||||
// because a null parameter was passed in.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (scoped_advertisement->size() > kMaxAdvertisementLength) {
|
||||
// TODO(ahlee): logger.atSevere().log("Refusing to start BLE advertising
|
||||
// because the advertisement was too long. Expected at most %d bytes but
|
||||
// received %d.", kMaxAdvertisementLength, advertisement->size());
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isAdvertising()) {
|
||||
// TODO(ahlee): logger.atSevere().log("Failed to BLE advertise because we're
|
||||
// already advertising.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!bluetooth_radio_->isEnabled()) {
|
||||
// TODO(ahlee): logger.atSevere().log("Can't start BLE advertising because
|
||||
// Bluetooth isn't enabled.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isAvailable()) {
|
||||
// TODO(ahlee): logger.atSevere().log("Can't start BLE advertising because
|
||||
// BLE isn't enabled.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!ble_medium_->startAdvertising(service_id,
|
||||
scoped_advertisement.release())) {
|
||||
// TODO(ahlee) logger.atSevere().log("Failed to start BLE advertising");
|
||||
return false;
|
||||
}
|
||||
|
||||
advertising_info_ = MakePtr(new AdvertisingInfo(service_id));
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
void BLE<Platform>::stopAdvertising() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
if (!isAdvertising()) {
|
||||
// TODO(ahlee): logger.atDebug().log("Can't turn off BLE advertising because
|
||||
// it never started.");
|
||||
return;
|
||||
}
|
||||
|
||||
ble_medium_->stopAdvertising(advertising_info_->service_id);
|
||||
// Reset our bundle of advertising state to mark that we're no longer
|
||||
// advertising.
|
||||
advertising_info_.destroy();
|
||||
|
||||
// TODO(ahlee): logger.atVerbose().log("Turned BLE advertising off");
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BLE<Platform>::isAdvertising() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
return !advertising_info_.isNull();
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BLE<Platform>::startScanning(
|
||||
const string& service_id,
|
||||
Ptr<DiscoveredPeripheralCallback> discovered_peripheral_callback) {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
// Avoid leaks.
|
||||
ScopedPtr<Ptr<DiscoveredPeripheralCallback>>
|
||||
scoped_discovered_peripheral_callback(discovered_peripheral_callback);
|
||||
if (scoped_discovered_peripheral_callback.isNull() || service_id.empty()) {
|
||||
// TODO(ahlee): logger.atSevere().log("Refusing to start BLE scanning
|
||||
// because a null parameter was passed in.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isScanning()) {
|
||||
// TODO(ahlee): logger.atSevere().log("Refusing to start BLE scanning
|
||||
// because we are already scanning.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!bluetooth_radio_->isEnabled()) {
|
||||
// TODO(ahlee): logger.atSevere().log("Can't start BLE scanning because
|
||||
// Bluetooth was never turned on");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isAvailable()) {
|
||||
// TODO(ahlee): logger.atSevere().log("Can't start BLE scanning because
|
||||
// BLE isn't available.");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Avoid leaks.
|
||||
ScopedPtr<Ptr<BLEDiscoveredPeripheralCallback>>
|
||||
scoped_ble_discovered_peripheral_callback(
|
||||
new BLEDiscoveredPeripheralCallback(
|
||||
scoped_discovered_peripheral_callback.release()));
|
||||
if (!ble_medium_->startScanning(
|
||||
service_id, scoped_ble_discovered_peripheral_callback.get())) {
|
||||
// TODO(ahlee): logger.atSevere().log("Failed to start BLE scanning.");
|
||||
return false;
|
||||
}
|
||||
|
||||
scanning_info_ = MakePtr(new ScanningInfo(
|
||||
service_id, scoped_ble_discovered_peripheral_callback.release()));
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
void BLE<Platform>::stopScanning() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
if (!isScanning()) {
|
||||
// TODO(ahlee): logger.atDebug().log("Can't turn off BLE scanning because we
|
||||
// never started scanning.");
|
||||
return;
|
||||
}
|
||||
|
||||
ble_medium_->stopScanning(scanning_info_->service_id);
|
||||
// Reset our bundle of scanning state to mark that we're no longer scanning.
|
||||
scanning_info_.destroy();
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BLE<Platform>::isScanning() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
return !scanning_info_.isNull();
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BLE<Platform>::startAcceptingConnections(
|
||||
const string& service_id,
|
||||
Ptr<AcceptedConnectionCallback> accepted_connection_callback) {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
// Avoid leaks.
|
||||
ScopedPtr<Ptr<AcceptedConnectionCallback>>
|
||||
scoped_accepted_connection_callback(accepted_connection_callback);
|
||||
if (scoped_accepted_connection_callback.isNull() || service_id.empty()) {
|
||||
// TODO(ahlee): logger.atSevere().log("Refusing to start accepting BLE
|
||||
// connections because a null parameter was passed in.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isAcceptingConnections()) {
|
||||
// TODO(ahlee): logger.atSevere().log("Refusing to start accepting BLE
|
||||
// connections for %s because another BLE server socket is already
|
||||
// in-progress.", service_id);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!bluetooth_radio_->isEnabled()) {
|
||||
// TODO(ahlee): logger.atSevere().log("Can't start accepting BLE connections
|
||||
// for %s because Bluetooth isn't enabled.", serviceId);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isAvailable()) {
|
||||
// TODO(ahlee): logger.atSevere().log("Can't start accepting BLE connections
|
||||
// for %s because BLE isn't available.", serviceId);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Avoid leaks.
|
||||
ScopedPtr<Ptr<BLEAcceptedConnectionCallback>>
|
||||
scoped_ble_accepted_connection_callback(new BLEAcceptedConnectionCallback(
|
||||
scoped_accepted_connection_callback.release()));
|
||||
if (!ble_medium_->startAcceptingConnections(
|
||||
service_id, scoped_ble_accepted_connection_callback.get())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
accepting_connections_info_ = MakePtr(new AcceptingConnectionsInfo(
|
||||
service_id, scoped_ble_accepted_connection_callback.release()));
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
void BLE<Platform>::stopAcceptingConnections() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
if (!isAcceptingConnections()) {
|
||||
// TODO(ahlee): logger.atDebug().log("Can't stop accepting BLE connections
|
||||
// because it was never started.");
|
||||
return;
|
||||
}
|
||||
|
||||
ble_medium_->stopAcceptingConnections(
|
||||
accepting_connections_info_->service_id);
|
||||
// Reset our bundle of accepting connections state to mark that we're no
|
||||
// longer accepting connections.
|
||||
accepting_connections_info_.destroy();
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BLE<Platform>::isAcceptingConnections() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
return !accepting_connections_info_.isNull();
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
Ptr<BLESocket> BLE<Platform>::connect(Ptr<BLEPeripheral> ble_peripheral,
|
||||
const string& service_id) {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
if (ble_peripheral.isNull() || service_id.empty()) {
|
||||
// TODO(ahlee): logger.atSevere().log("Refusing to create client BLE socket
|
||||
// because at least one of blePeripheral or serviceId is null.");
|
||||
return Ptr<BLESocket>();
|
||||
}
|
||||
|
||||
if (!bluetooth_radio_->isEnabled()) {
|
||||
// TODO(ahlee): logger.atSevere().log("Can't create client BLE socket to %s
|
||||
// because Bluetooth isn't enabled.", blePeripheral);
|
||||
return Ptr<BLESocket>();
|
||||
}
|
||||
|
||||
if (!isAvailable()) {
|
||||
// TODO(ahlee): logger.atSevere().log("Can't create client BLE socket to %s
|
||||
// because BLE isn't available.", blePeripheral);
|
||||
return Ptr<BLESocket>();
|
||||
}
|
||||
|
||||
return ble_medium_->connect(ble_peripheral, service_id);
|
||||
}
|
||||
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
@@ -0,0 +1,197 @@
|
||||
#ifndef CORE_INTERNAL_MEDIUMS_BLE_H_
|
||||
#define CORE_INTERNAL_MEDIUMS_BLE_H_
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "core/internal/mediums/bluetooth_radio.h"
|
||||
#include "platform/api/ble.h"
|
||||
#include "platform/api/bluetooth_adapter.h"
|
||||
#include "platform/api/lock.h"
|
||||
#include "platform/byte_array.h"
|
||||
#include "platform/port/string.h"
|
||||
#include "platform/ptr.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
|
||||
template <typename Platform>
|
||||
class BLE {
|
||||
public:
|
||||
explicit BLE(Ptr<BluetoothRadio<Platform>> bluetooth_radio);
|
||||
~BLE();
|
||||
|
||||
bool isAvailable();
|
||||
|
||||
bool startAdvertising(const string& service_id,
|
||||
ConstPtr<ByteArray> advertisement);
|
||||
void stopAdvertising();
|
||||
|
||||
class DiscoveredPeripheralCallback {
|
||||
public:
|
||||
virtual ~DiscoveredPeripheralCallback() {}
|
||||
|
||||
virtual void onPeripheralDiscovered(Ptr<BLEPeripheral> ble_peripheral,
|
||||
const string& service_id,
|
||||
ConstPtr<ByteArray> advertisement) = 0;
|
||||
virtual void onPeripheralLost(Ptr<BLEPeripheral> ble_peripheral,
|
||||
const string& service_id) = 0;
|
||||
};
|
||||
|
||||
bool startScanning(
|
||||
const string& service_id,
|
||||
Ptr<DiscoveredPeripheralCallback> discovered_peripheral_callback);
|
||||
void stopScanning();
|
||||
|
||||
class AcceptedConnectionCallback {
|
||||
public:
|
||||
virtual ~AcceptedConnectionCallback() {}
|
||||
|
||||
virtual void onConnectionAccepted(Ptr<BLESocket> socket,
|
||||
const string& service_id) = 0;
|
||||
};
|
||||
|
||||
bool startAcceptingConnections(
|
||||
const string& service_id,
|
||||
Ptr<AcceptedConnectionCallback> accepted_connection_callback);
|
||||
void stopAcceptingConnections();
|
||||
bool isAcceptingConnections();
|
||||
|
||||
Ptr<BLESocket> connect(Ptr<BLEPeripheral> ble_peripheral,
|
||||
const string& service_id);
|
||||
|
||||
private:
|
||||
// TODO(ahlee): Rename to DiscoveredPeripheralCallbackBridge
|
||||
class BLEDiscoveredPeripheralCallback
|
||||
: public BLEMedium::DiscoveredPeripheralCallback {
|
||||
public:
|
||||
explicit BLEDiscoveredPeripheralCallback(
|
||||
Ptr<BLE::DiscoveredPeripheralCallback> discovered_peripheral_callback)
|
||||
: discovered_peripheral_callback_(discovered_peripheral_callback) {}
|
||||
~BLEDiscoveredPeripheralCallback() override {
|
||||
// Nothing to do.
|
||||
}
|
||||
|
||||
void onPeripheralDiscovered(Ptr<BLEPeripheral> ble_peripheral,
|
||||
const string& service_id,
|
||||
ConstPtr<ByteArray> advertisement) override {
|
||||
discovered_peripheral_callback_->onPeripheralDiscovered(
|
||||
ble_peripheral, service_id, advertisement);
|
||||
}
|
||||
void onPeripheralLost(Ptr<BLEPeripheral> ble_peripheral,
|
||||
const string& service_id) override {
|
||||
discovered_peripheral_callback_->onPeripheralLost(ble_peripheral,
|
||||
service_id);
|
||||
}
|
||||
|
||||
private:
|
||||
ScopedPtr<Ptr<BLE::DiscoveredPeripheralCallback>>
|
||||
discovered_peripheral_callback_;
|
||||
};
|
||||
|
||||
// TODO(ahlee): Rename to AcceptedConnectionCallbackBridge
|
||||
class BLEAcceptedConnectionCallback
|
||||
: public BLEMedium::AcceptedConnectionCallback {
|
||||
public:
|
||||
explicit BLEAcceptedConnectionCallback(
|
||||
Ptr<BLE::AcceptedConnectionCallback> accepted_connection_callback)
|
||||
: accepted_connection_callback_(accepted_connection_callback) {}
|
||||
~BLEAcceptedConnectionCallback() override {
|
||||
// Nothing to do.
|
||||
}
|
||||
|
||||
void onConnectionAccepted(Ptr<BLESocket> ble_socket,
|
||||
const string& service_id) override {
|
||||
accepted_connection_callback_->onConnectionAccepted(ble_socket,
|
||||
service_id);
|
||||
}
|
||||
|
||||
private:
|
||||
ScopedPtr<Ptr<BLE::AcceptedConnectionCallback>>
|
||||
accepted_connection_callback_;
|
||||
};
|
||||
|
||||
struct ScanningInfo {
|
||||
ScanningInfo(
|
||||
const string& service_id,
|
||||
Ptr<BLEDiscoveredPeripheralCallback> ble_discovered_peripheral_callback)
|
||||
: service_id(service_id),
|
||||
ble_discovered_peripheral_callback(
|
||||
ble_discovered_peripheral_callback) {}
|
||||
~ScanningInfo() {
|
||||
// Nothing to do (the ScopedPtr members take care of themselves).
|
||||
}
|
||||
|
||||
const string service_id;
|
||||
ScopedPtr<Ptr<BLEDiscoveredPeripheralCallback>>
|
||||
ble_discovered_peripheral_callback;
|
||||
};
|
||||
|
||||
struct AdvertisingInfo {
|
||||
explicit AdvertisingInfo(const string& service_id)
|
||||
: service_id(service_id) {}
|
||||
~AdvertisingInfo() {}
|
||||
|
||||
const string service_id;
|
||||
};
|
||||
|
||||
struct AcceptingConnectionsInfo {
|
||||
AcceptingConnectionsInfo(
|
||||
const string& service_id,
|
||||
Ptr<BLEAcceptedConnectionCallback> ble_accepted_connection_callback)
|
||||
: service_id(service_id),
|
||||
ble_accepted_connection_callback(ble_accepted_connection_callback) {}
|
||||
~AcceptingConnectionsInfo() {
|
||||
// Nothing to do (the ScopedPtr members take care of themselves).
|
||||
}
|
||||
|
||||
const string service_id;
|
||||
ScopedPtr<Ptr<BLEAcceptedConnectionCallback>>
|
||||
ble_accepted_connection_callback;
|
||||
};
|
||||
|
||||
static const std::int32_t kMaxAdvertisementLength;
|
||||
|
||||
bool isAdvertising();
|
||||
bool isScanning();
|
||||
|
||||
// ------------ GENERAL ------------
|
||||
|
||||
ScopedPtr<Ptr<Lock>> lock_;
|
||||
|
||||
// ------------ CORE BLE ------------
|
||||
|
||||
Ptr<BluetoothRadio<Platform>> bluetooth_radio_;
|
||||
ScopedPtr<Ptr<BluetoothAdapter>> bluetooth_adapter_;
|
||||
// The underlying, per-platform implementation.
|
||||
ScopedPtr<Ptr<BLEMedium>> ble_medium_;
|
||||
|
||||
// ------------ DISCOVERY ------------
|
||||
|
||||
// A bundle of state required to start/stop BLE scanning. When non-null,
|
||||
// we are currently performing a BLE scan.
|
||||
// In the Java code this maps to the bleListener and
|
||||
// bleScanningMediumOperation.
|
||||
Ptr<ScanningInfo> scanning_info_;
|
||||
|
||||
// ------------ ADVERTISING ------------
|
||||
|
||||
// A bundle of state required to start/stop BLE advertising. When non-null,
|
||||
// we are currently advertising over BLE.
|
||||
// In the Java code this maps to bleAdvertiser, advertiseCallback, and
|
||||
// bleAdvertisingMediumOperation.
|
||||
Ptr<AdvertisingInfo> advertising_info_;
|
||||
|
||||
// A bundle of state required to start/stop accepting BLE connections. When
|
||||
// non-null, we are currently accepting BLE connections.
|
||||
// In the Java code this maps to the bleServerSocket.
|
||||
Ptr<AcceptingConnectionsInfo> accepting_connections_info_;
|
||||
};
|
||||
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
|
||||
#include "core/internal/mediums/ble.cc"
|
||||
|
||||
#endif // CORE_INTERNAL_MEDIUMS_BLE_H_
|
||||
@@ -0,0 +1,288 @@
|
||||
#include "core/internal/mediums/ble_advertisement.h"
|
||||
|
||||
#include "platform/logging.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
const std::uint32_t BLEAdvertisement::kServiceIdHashLength = 3;
|
||||
|
||||
const std::uint32_t BLEAdvertisement::kVersionLength = 1;
|
||||
// Length of one int. Be sure to re-evaluate how we compute data size in this
|
||||
// class if this constant ever changes!
|
||||
const std::uint32_t BLEAdvertisement::kDataSizeLength = 4;
|
||||
const std::uint32_t BLEAdvertisement::kMinAdvertisementLength =
|
||||
kVersionLength + kServiceIdHashLength + kDataSizeLength;
|
||||
// The maximum length for a GATT characteristic value is 512 bytes, so make sure
|
||||
// the entire advertisement is less than that. The data can take up whatever
|
||||
// space is remaining after the bytes preceding it.
|
||||
const std::uint32_t BLEAdvertisement::kMaxDataSize =
|
||||
512 - kMinAdvertisementLength;
|
||||
const std::uint16_t BLEAdvertisement::kVersionBitmask = 0x0E0;
|
||||
const std::uint16_t BLEAdvertisement::kSocketVersionBitmask = 0x01C;
|
||||
|
||||
ConstPtr<BLEAdvertisement> BLEAdvertisement::fromBytes(
|
||||
ConstPtr<ByteArray> ble_advertisement_bytes) {
|
||||
if (ble_advertisement_bytes.isNull()) {
|
||||
NEARBY_LOG(INFO,
|
||||
"Cannot deserialize BLEAdvertisement: null bytes passed in");
|
||||
return ConstPtr<BLEAdvertisement>();
|
||||
}
|
||||
|
||||
if (ble_advertisement_bytes->size() < kMinAdvertisementLength) {
|
||||
NEARBY_LOG(INFO,
|
||||
"Cannot deserialize BLEAdvertisement: expecting min %u raw "
|
||||
"bytes, got %zu",
|
||||
kMinAdvertisementLength, ble_advertisement_bytes->size());
|
||||
return ConstPtr<BLEAdvertisement>();
|
||||
}
|
||||
|
||||
// Now, time to read the bytes!
|
||||
const char *ble_advertisement_bytes_read_ptr =
|
||||
ble_advertisement_bytes->getData();
|
||||
|
||||
// 1. Version.
|
||||
Version::Value version = parseVersionFromByte(
|
||||
static_cast<std::uint16_t>(*ble_advertisement_bytes_read_ptr));
|
||||
if (!isSupportedVersion(version)) {
|
||||
NEARBY_LOG(INFO,
|
||||
"Cannot deserialize BLEAdvertisement: unsupported Version %u",
|
||||
version);
|
||||
return ConstPtr<BLEAdvertisement>();
|
||||
}
|
||||
|
||||
// 2. Socket Version.
|
||||
SocketVersion::Value socket_version = parseSocketVersionFromByte(
|
||||
static_cast<std::uint16_t>(*ble_advertisement_bytes_read_ptr));
|
||||
if (!isSupportedSocketVersion(socket_version)) {
|
||||
NEARBY_LOG(
|
||||
INFO,
|
||||
"Cannot deserialize BLEAdvertisement: unsupported SocketVersion %u",
|
||||
socket_version);
|
||||
return ConstPtr<BLEAdvertisement>();
|
||||
}
|
||||
ble_advertisement_bytes_read_ptr += kVersionLength;
|
||||
|
||||
// 3. Service ID hash.
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_hash(MakeConstPtr(
|
||||
new ByteArray(ble_advertisement_bytes_read_ptr, kServiceIdHashLength)));
|
||||
ble_advertisement_bytes_read_ptr += kServiceIdHashLength;
|
||||
|
||||
// 4.1. Data size.
|
||||
size_t expected_data_size =
|
||||
deserializeDataSize(ble_advertisement_bytes_read_ptr);
|
||||
if (expected_data_size < 0) {
|
||||
NEARBY_LOG(INFO,
|
||||
"Cannot deserialize BLEAdvertisement: negative data size %zu",
|
||||
expected_data_size);
|
||||
return ConstPtr<BLEAdvertisement>();
|
||||
}
|
||||
ble_advertisement_bytes_read_ptr += kDataSizeLength;
|
||||
|
||||
// Check that the stated data size is the same as what we received.
|
||||
size_t actual_data_size = computeDataSize(ble_advertisement_bytes);
|
||||
if (actual_data_size < expected_data_size) {
|
||||
NEARBY_LOG(INFO,
|
||||
"Cannot deserialize BLEAdvertisement: expected data to be %zu "
|
||||
"bytes, got %zu bytes",
|
||||
expected_data_size, actual_data_size);
|
||||
return ConstPtr<BLEAdvertisement>();
|
||||
}
|
||||
|
||||
// 4.2. Data.
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_data(MakeConstPtr(
|
||||
new ByteArray(ble_advertisement_bytes_read_ptr, expected_data_size)));
|
||||
ble_advertisement_bytes_read_ptr += expected_data_size;
|
||||
|
||||
return MakeRefCountedConstPtr(new BLEAdvertisement(
|
||||
version, socket_version, scoped_service_id_hash.release(),
|
||||
scoped_data.release()));
|
||||
}
|
||||
|
||||
ConstPtr<ByteArray> BLEAdvertisement::toBytes(
|
||||
Version::Value version, SocketVersion::Value socket_version,
|
||||
ConstPtr<ByteArray> service_id_hash, ConstPtr<ByteArray> data) {
|
||||
// Check that the given input is valid.
|
||||
if (!isSupportedVersion(version)) {
|
||||
NEARBY_LOG(INFO,
|
||||
"Cannot serialize BLEAdvertisement: unsupported Version %u",
|
||||
version);
|
||||
return ConstPtr<ByteArray>();
|
||||
}
|
||||
|
||||
if (!isSupportedSocketVersion(socket_version)) {
|
||||
NEARBY_LOG(
|
||||
INFO, "Cannot serialize BLEAdvertisement: unsupported SocketVersion %u",
|
||||
socket_version);
|
||||
return ConstPtr<ByteArray>();
|
||||
}
|
||||
|
||||
if (service_id_hash->size() != kServiceIdHashLength) {
|
||||
NEARBY_LOG(INFO,
|
||||
"Cannot serialize BLEAdvertisement: expected a service_id_hash "
|
||||
"of %u bytes, but got %zu",
|
||||
kServiceIdHashLength, service_id_hash->size());
|
||||
return ConstPtr<ByteArray>();
|
||||
}
|
||||
|
||||
if (data->size() > kMaxDataSize) {
|
||||
NEARBY_LOG(INFO,
|
||||
"Cannot serialize BLEAdvertisement: expected data of at most %u "
|
||||
"bytes, but got %zu",
|
||||
kMaxDataSize, data->size());
|
||||
return ConstPtr<ByteArray>();
|
||||
}
|
||||
|
||||
// Initialize the bytes.
|
||||
size_t advertisement_length = computeAdvertisementLength(data);
|
||||
Ptr<ByteArray> advertisement_bytes{new ByteArray{advertisement_length}};
|
||||
char *advertisement_bytes_write_ptr = advertisement_bytes->getData();
|
||||
|
||||
// 1. Version.
|
||||
serializeVersionByte(advertisement_bytes_write_ptr, version);
|
||||
|
||||
// 2. SocketVersion.
|
||||
serializeSocketVersionByte(advertisement_bytes_write_ptr, socket_version);
|
||||
advertisement_bytes_write_ptr += kVersionLength;
|
||||
|
||||
// 3. Service ID hash.
|
||||
memcpy(advertisement_bytes_write_ptr, service_id_hash->getData(),
|
||||
kServiceIdHashLength);
|
||||
advertisement_bytes_write_ptr += kServiceIdHashLength;
|
||||
|
||||
// 4.1. Data length.
|
||||
serializeDataSize(advertisement_bytes_write_ptr, data->size());
|
||||
advertisement_bytes_write_ptr += kDataSizeLength;
|
||||
|
||||
// 4.2. Data.
|
||||
memcpy(advertisement_bytes_write_ptr, data->getData(), data->size());
|
||||
advertisement_bytes_write_ptr += data->size();
|
||||
|
||||
return ConstifyPtr(advertisement_bytes);
|
||||
}
|
||||
|
||||
bool BLEAdvertisement::isSupportedVersion(Version::Value version) {
|
||||
return version >= Version::V1 && version <= Version::V2;
|
||||
}
|
||||
|
||||
bool BLEAdvertisement::isSupportedSocketVersion(
|
||||
SocketVersion::Value socket_version) {
|
||||
return socket_version >= SocketVersion::V1 &&
|
||||
socket_version <= SocketVersion::V2;
|
||||
}
|
||||
|
||||
BLEAdvertisement::Version::Value BLEAdvertisement::parseVersionFromByte(
|
||||
std::uint16_t byte) {
|
||||
return static_cast<BLEAdvertisement::Version::Value>(
|
||||
(byte & kVersionBitmask) >> 5);
|
||||
}
|
||||
|
||||
BLEAdvertisement::SocketVersion::Value
|
||||
BLEAdvertisement::parseSocketVersionFromByte(std::uint16_t byte) {
|
||||
return static_cast<SocketVersion::Value>((byte & kSocketVersionBitmask) >> 2);
|
||||
}
|
||||
|
||||
size_t BLEAdvertisement::deserializeDataSize(
|
||||
const char *data_size_bytes_read_ptr) {
|
||||
// Allocate a chunk of memory to store our deserialized size.
|
||||
char data_size_bytes[kDataSizeLength];
|
||||
|
||||
// Assign the bits of our size from the given raw bytes, keeping in mind that
|
||||
// we need to convert from Big Endian to Little Endian in the process.
|
||||
for (int i = 0; i < kDataSizeLength; ++i) {
|
||||
data_size_bytes[i] = data_size_bytes_read_ptr[kDataSizeLength - i - 1];
|
||||
}
|
||||
|
||||
// Interpret the char array as a single int.
|
||||
return static_cast<size_t>(
|
||||
*(reinterpret_cast<std::uint32_t *>(&data_size_bytes)));
|
||||
}
|
||||
|
||||
size_t BLEAdvertisement::computeDataSize(
|
||||
ConstPtr<ByteArray> ble_advertisement_bytes) {
|
||||
return ble_advertisement_bytes->size() - kMinAdvertisementLength;
|
||||
}
|
||||
|
||||
size_t BLEAdvertisement::computeAdvertisementLength(ConstPtr<ByteArray> data) {
|
||||
// The advertisement length is the minimum length + the length of the data.
|
||||
return kMinAdvertisementLength + data->size();
|
||||
}
|
||||
|
||||
void BLEAdvertisement::serializeVersionByte(char *version_byte_write_ptr,
|
||||
Version::Value version) {
|
||||
*version_byte_write_ptr |=
|
||||
static_cast<char>((version << 5) & kVersionBitmask);
|
||||
}
|
||||
|
||||
void BLEAdvertisement::serializeSocketVersionByte(
|
||||
char *socket_version_byte_write_ptr, SocketVersion::Value socket_version) {
|
||||
*socket_version_byte_write_ptr |=
|
||||
static_cast<char>((socket_version << 2) & kSocketVersionBitmask);
|
||||
}
|
||||
|
||||
void BLEAdvertisement::serializeDataSize(char *data_size_bytes_write_ptr,
|
||||
size_t data_size) {
|
||||
// Get a raw representation of the data size bytes in memory.
|
||||
char *data_size_bytes = reinterpret_cast<char *>(&data_size);
|
||||
|
||||
// Append these raw bytes to advertisement bytes, keeping in mind that we need
|
||||
// to convert from Little Endian to Big Endian in the process.
|
||||
for (int i = 0; i < kDataSizeLength; ++i) {
|
||||
data_size_bytes_write_ptr[i] = data_size_bytes[kDataSizeLength - i - 1];
|
||||
}
|
||||
}
|
||||
|
||||
BLEAdvertisement::BLEAdvertisement(Version::Value version,
|
||||
SocketVersion::Value socket_version,
|
||||
ConstPtr<ByteArray> service_id_hash,
|
||||
ConstPtr<ByteArray> data)
|
||||
: version_(version),
|
||||
socket_version_(socket_version),
|
||||
service_id_hash_(service_id_hash),
|
||||
data_(data) {}
|
||||
|
||||
BLEAdvertisement::~BLEAdvertisement() {
|
||||
// Nothing to do.
|
||||
}
|
||||
|
||||
BLEAdvertisement::Version::Value BLEAdvertisement::getVersion() const {
|
||||
return version_;
|
||||
}
|
||||
|
||||
BLEAdvertisement::SocketVersion::Value BLEAdvertisement::getSocketVersion()
|
||||
const {
|
||||
return socket_version_;
|
||||
}
|
||||
|
||||
ConstPtr<ByteArray> BLEAdvertisement::getServiceIdHash() const {
|
||||
return service_id_hash_.get();
|
||||
}
|
||||
|
||||
ConstPtr<ByteArray> BLEAdvertisement::getData() const { return data_.get(); }
|
||||
|
||||
bool BLEAdvertisement::operator==(const BLEAdvertisement &rhs) const {
|
||||
return this->getVersion() == rhs.getVersion() &&
|
||||
this->getSocketVersion() == rhs.getSocketVersion() &&
|
||||
*(this->getServiceIdHash()) == *(rhs.getServiceIdHash()) &&
|
||||
*(this->getData()) == *(rhs.getData());
|
||||
}
|
||||
|
||||
bool BLEAdvertisement::operator<(const BLEAdvertisement &rhs) const {
|
||||
if (this->getVersion() != rhs.getVersion()) {
|
||||
return this->getVersion() < rhs.getVersion();
|
||||
}
|
||||
if (this->getSocketVersion() != rhs.getSocketVersion()) {
|
||||
return this->getSocketVersion() < rhs.getSocketVersion();
|
||||
}
|
||||
if (*(this->getServiceIdHash()) != *(rhs.getServiceIdHash())) {
|
||||
return *(this->getServiceIdHash()) < *(rhs.getServiceIdHash());
|
||||
}
|
||||
return *(this->getData()) < *(rhs.getData());
|
||||
}
|
||||
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
@@ -0,0 +1,100 @@
|
||||
#ifndef CORE_INTERNAL_MEDIUMS_BLE_ADVERTISEMENT_H_
|
||||
#define CORE_INTERNAL_MEDIUMS_BLE_ADVERTISEMENT_H_
|
||||
|
||||
#include "platform/byte_array.h"
|
||||
#include "platform/ptr.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
// Represents the format of the Mediums BLE Advertisement used in advertising
|
||||
// and discovery.
|
||||
//
|
||||
// [VERSION][SOCKET_VERSION][2_RESERVED_BITS][SERVICE_ID_HASH][DATA_SIZE][DATA]
|
||||
//
|
||||
// See go/nearby-ble-design for more information.
|
||||
class BLEAdvertisement {
|
||||
public:
|
||||
// Versions of the BLEAdvertisement.
|
||||
struct Version {
|
||||
enum Value {
|
||||
UNKNOWN = 0,
|
||||
V1 = 1,
|
||||
V2 = 2,
|
||||
// Version is only allocated 3 bits in the BLEAdvertisement, so this can
|
||||
// never go beyond V7.
|
||||
};
|
||||
};
|
||||
|
||||
// Versions of the BLESocket.
|
||||
struct SocketVersion {
|
||||
enum Value {
|
||||
UNKNOWN = 0,
|
||||
V1 = 1,
|
||||
V2 = 2,
|
||||
// SocketVersion is only allocated 3 bits in the BLEAdvertisement, so this
|
||||
// can never go beyond V7.
|
||||
};
|
||||
};
|
||||
|
||||
static ConstPtr<BLEAdvertisement> fromBytes(
|
||||
ConstPtr<ByteArray> ble_advertisement_bytes);
|
||||
|
||||
static ConstPtr<ByteArray> toBytes(Version::Value version,
|
||||
SocketVersion::Value socket_version,
|
||||
ConstPtr<ByteArray> service_id_hash,
|
||||
ConstPtr<ByteArray> data);
|
||||
|
||||
static const std::uint32_t kServiceIdHashLength;
|
||||
|
||||
~BLEAdvertisement();
|
||||
|
||||
Version::Value getVersion() const;
|
||||
SocketVersion::Value getSocketVersion() const;
|
||||
ConstPtr<ByteArray> getServiceIdHash() const;
|
||||
ConstPtr<ByteArray> getData() const;
|
||||
|
||||
// Operator overloads when comparing ConstPtr<BLEAdvertisement>.
|
||||
bool operator==(const BLEAdvertisement &rhs) const;
|
||||
bool operator<(const BLEAdvertisement &rhs) const;
|
||||
|
||||
private:
|
||||
static bool isSupportedVersion(Version::Value version);
|
||||
static bool isSupportedSocketVersion(SocketVersion::Value socket_version);
|
||||
static Version::Value parseVersionFromByte(std::uint16_t byte);
|
||||
static SocketVersion::Value parseSocketVersionFromByte(std::uint16_t byte);
|
||||
static size_t deserializeDataSize(const char *data_size_bytes_read_ptr);
|
||||
static size_t computeDataSize(ConstPtr<ByteArray> ble_advertisement_bytes);
|
||||
static size_t computeAdvertisementLength(ConstPtr<ByteArray> data);
|
||||
static void serializeVersionByte(char *version_byte_write_ptr,
|
||||
Version::Value version);
|
||||
static void serializeSocketVersionByte(char *socket_version_byte_write_ptr,
|
||||
SocketVersion::Value socket_version);
|
||||
static void serializeDataSize(char *data_size_bytes_write_ptr,
|
||||
size_t data_size);
|
||||
|
||||
static const std::uint32_t kVersionLength;
|
||||
static const std::uint32_t kDataSizeLength;
|
||||
static const std::uint32_t kMinAdvertisementLength;
|
||||
static const std::uint32_t kMaxDataSize;
|
||||
static const std::uint16_t kVersionBitmask;
|
||||
static const std::uint16_t kSocketVersionBitmask;
|
||||
|
||||
BLEAdvertisement(Version::Value version, SocketVersion::Value socket_version,
|
||||
ConstPtr<ByteArray> service_id_hash,
|
||||
ConstPtr<ByteArray> data);
|
||||
|
||||
const Version::Value version_;
|
||||
const SocketVersion::Value socket_version_;
|
||||
ScopedPtr<ConstPtr<ByteArray> > service_id_hash_;
|
||||
ScopedPtr<ConstPtr<ByteArray> > data_;
|
||||
};
|
||||
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
|
||||
#endif // CORE_INTERNAL_MEDIUMS_BLE_ADVERTISEMENT_H_
|
||||
@@ -0,0 +1,208 @@
|
||||
#include "core/internal/mediums/ble_advertisement_header.h"
|
||||
|
||||
#include "platform/base64_utils.h"
|
||||
#include "platform/byte_array.h"
|
||||
#include "platform/logging.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
// The following IfThisThenThat is for BloomFilter length in
|
||||
// ble_v2.createAdvertisementHeader
|
||||
// LINT.IfChange
|
||||
const std::uint32_t BLEAdvertisementHeader::kServiceIdBloomFilterLength = 10;
|
||||
// LINT.ThenChange(//depot/google3/core/internal/\
|
||||
// mediums/ble_v2.h)
|
||||
const std::uint32_t BLEAdvertisementHeader::kAdvertisementHashLength = 4;
|
||||
|
||||
const std::uint32_t BLEAdvertisementHeader::kVersionAndNumSlotsLength = 1;
|
||||
const std::uint32_t BLEAdvertisementHeader::kMinAdvertisementHeaderLength =
|
||||
kVersionAndNumSlotsLength + kServiceIdBloomFilterLength +
|
||||
kAdvertisementHashLength;
|
||||
const std::uint16_t BLEAdvertisementHeader::kVersionBitmask = 0x0E0;
|
||||
const std::uint16_t BLEAdvertisementHeader::kNumSlotsBitmask = 0x01F;
|
||||
|
||||
ConstPtr<BLEAdvertisementHeader> BLEAdvertisementHeader::fromString(
|
||||
const std::string &ble_advertisement_header_string) {
|
||||
ScopedPtr<Ptr<ByteArray> > scoped_ble_advertisement_header_bytes(
|
||||
Base64Utils::decode(ble_advertisement_header_string));
|
||||
if (scoped_ble_advertisement_header_bytes.isNull()) {
|
||||
NEARBY_LOG(
|
||||
INFO,
|
||||
"Cannot deserialize BLEAdvertisementHeader: failed Base64 decoding");
|
||||
return ConstPtr<BLEAdvertisementHeader>();
|
||||
}
|
||||
|
||||
if (scoped_ble_advertisement_header_bytes->size() <
|
||||
kMinAdvertisementHeaderLength) {
|
||||
NEARBY_LOG(INFO,
|
||||
"Cannot deserialize BLEAdvertisementHeader: expecting min %u "
|
||||
"raw bytes, got %zu instead",
|
||||
kMinAdvertisementHeaderLength,
|
||||
scoped_ble_advertisement_header_bytes->size());
|
||||
return ConstPtr<BLEAdvertisementHeader>();
|
||||
}
|
||||
|
||||
// Now, time to read the bytes!
|
||||
const char *ble_advertisement_header_read_ptr =
|
||||
scoped_ble_advertisement_header_bytes->getData();
|
||||
|
||||
// 1. Version.
|
||||
// The first 3 bits of the first byte represent the version.
|
||||
Version::Value version = parseVersionFromByte(
|
||||
static_cast<std::uint16_t>(*ble_advertisement_header_read_ptr));
|
||||
if (version != Version::V2) {
|
||||
NEARBY_LOG(
|
||||
INFO,
|
||||
"Cannot deserialize BLEAdvertisementHeader, unsupported version %u",
|
||||
version);
|
||||
return ConstPtr<BLEAdvertisementHeader>();
|
||||
}
|
||||
|
||||
// 2. Number of slots.
|
||||
// The last 5 bits of the first byte represent the number of slots.
|
||||
std::uint32_t num_slots = parseNumSlotsFromByte(
|
||||
static_cast<std::uint16_t>(*ble_advertisement_header_read_ptr));
|
||||
ble_advertisement_header_read_ptr += kVersionAndNumSlotsLength;
|
||||
|
||||
// 3. Service ID bloom filter.
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_bloom_filter(
|
||||
MakeConstPtr(new ByteArray(ble_advertisement_header_read_ptr,
|
||||
kServiceIdBloomFilterLength)));
|
||||
ble_advertisement_header_read_ptr += kServiceIdBloomFilterLength;
|
||||
|
||||
// 4. Advertisement hash.
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_advertisement_hash(
|
||||
MakeConstPtr(new ByteArray(ble_advertisement_header_read_ptr,
|
||||
kAdvertisementHashLength)));
|
||||
ble_advertisement_header_read_ptr += kAdvertisementHashLength;
|
||||
|
||||
return MakeRefCountedConstPtr(new BLEAdvertisementHeader(
|
||||
version, num_slots, scoped_service_id_bloom_filter.release(),
|
||||
scoped_advertisement_hash.release()));
|
||||
}
|
||||
|
||||
std::string BLEAdvertisementHeader::asString(
|
||||
Version::Value version, std::uint32_t num_slots,
|
||||
ConstPtr<ByteArray> service_id_bloom_filter,
|
||||
ConstPtr<ByteArray> advertisement_hash) {
|
||||
// Check that the given input is valid.
|
||||
if (version != Version::V2) {
|
||||
NEARBY_LOG(
|
||||
INFO, "Cannot serialize BLEAdvertisementHeader: unsupported Version %u",
|
||||
version);
|
||||
return "";
|
||||
}
|
||||
|
||||
if (service_id_bloom_filter->size() != kServiceIdBloomFilterLength) {
|
||||
NEARBY_LOG(INFO,
|
||||
"Cannot serialize BLEAdvertisementHeader: expected "
|
||||
"service_id_bloom_filter of %u bytes, but got %zu",
|
||||
kServiceIdBloomFilterLength, service_id_bloom_filter->size());
|
||||
return "";
|
||||
}
|
||||
|
||||
if (advertisement_hash->size() != kAdvertisementHashLength) {
|
||||
NEARBY_LOG(INFO,
|
||||
"Cannot serialize BLEAdvertisementHeader: expected "
|
||||
"advertisement_hash of %u bytes, but got %zu",
|
||||
kAdvertisementHashLength, advertisement_hash->size());
|
||||
return "";
|
||||
}
|
||||
|
||||
// Initialize the bytes.
|
||||
ByteArray advertisement_header_bytes{kMinAdvertisementHeaderLength};
|
||||
char *advertisement_header_bytes_write_ptr =
|
||||
advertisement_header_bytes.getData();
|
||||
|
||||
// 1. Version.
|
||||
serializeVersionByte(advertisement_header_bytes_write_ptr, version);
|
||||
|
||||
// 2. Number of slots.
|
||||
serializeNumSlots(advertisement_header_bytes_write_ptr, num_slots);
|
||||
advertisement_header_bytes_write_ptr += kVersionAndNumSlotsLength;
|
||||
|
||||
// 3. Service ID bloom filter.
|
||||
memcpy(advertisement_header_bytes_write_ptr,
|
||||
service_id_bloom_filter->getData(), kServiceIdBloomFilterLength);
|
||||
advertisement_header_bytes_write_ptr += kServiceIdBloomFilterLength;
|
||||
|
||||
// 4. Advertisement hash.
|
||||
memcpy(advertisement_header_bytes_write_ptr, advertisement_hash->getData(),
|
||||
kAdvertisementHashLength);
|
||||
advertisement_header_bytes_write_ptr += kAdvertisementHashLength;
|
||||
|
||||
// Header needs to be binary safe, so apply a Base64 encoding.
|
||||
return Base64Utils::encode(advertisement_header_bytes);
|
||||
}
|
||||
|
||||
BLEAdvertisementHeader::Version::Value
|
||||
BLEAdvertisementHeader::parseVersionFromByte(std::uint16_t byte) {
|
||||
return static_cast<Version::Value>((byte & kVersionBitmask) >> 5);
|
||||
}
|
||||
|
||||
std::uint32_t BLEAdvertisementHeader::parseNumSlotsFromByte(
|
||||
std::uint16_t byte) {
|
||||
return static_cast<std::uint32_t>((byte & kNumSlotsBitmask));
|
||||
}
|
||||
|
||||
void BLEAdvertisementHeader::serializeVersionByte(char *version_byte_write_ptr,
|
||||
Version::Value version) {
|
||||
*version_byte_write_ptr |=
|
||||
static_cast<char>((version << 5) & kVersionBitmask);
|
||||
}
|
||||
|
||||
void BLEAdvertisementHeader::serializeNumSlots(char *num_slots_byte_write_ptr,
|
||||
std::uint32_t num_slots) {
|
||||
*num_slots_byte_write_ptr |= static_cast<char>(num_slots & kNumSlotsBitmask);
|
||||
}
|
||||
|
||||
BLEAdvertisementHeader::BLEAdvertisementHeader(
|
||||
BLEAdvertisementHeader::Version::Value version, std::uint32_t num_slots,
|
||||
ConstPtr<ByteArray> service_id_bloom_filter,
|
||||
ConstPtr<ByteArray> advertisement_hash)
|
||||
: version_(version),
|
||||
num_slots_(num_slots),
|
||||
service_id_bloom_filter_(service_id_bloom_filter),
|
||||
advertisement_hash_(advertisement_hash) {}
|
||||
|
||||
BLEAdvertisementHeader::~BLEAdvertisementHeader() {
|
||||
// Nothing to do.
|
||||
}
|
||||
|
||||
BLEAdvertisementHeader::Version::Value BLEAdvertisementHeader::getVersion()
|
||||
const {
|
||||
return version_;
|
||||
}
|
||||
|
||||
std::uint32_t BLEAdvertisementHeader::getNumSlots() const { return num_slots_; }
|
||||
|
||||
ConstPtr<ByteArray> BLEAdvertisementHeader::getServiceIdBloomFilter() const {
|
||||
return service_id_bloom_filter_.get();
|
||||
}
|
||||
|
||||
ConstPtr<ByteArray> BLEAdvertisementHeader::getAdvertisementHash() const {
|
||||
return advertisement_hash_.get();
|
||||
}
|
||||
|
||||
bool BLEAdvertisementHeader::operator<(
|
||||
const BLEAdvertisementHeader &rhs) const {
|
||||
if (this->getVersion() != rhs.getVersion()) {
|
||||
return this->getVersion() < rhs.getVersion();
|
||||
}
|
||||
if (this->getNumSlots() != rhs.getNumSlots()) {
|
||||
return this->getNumSlots() < rhs.getNumSlots();
|
||||
}
|
||||
if (*(this->getServiceIdBloomFilter()) != *(rhs.getServiceIdBloomFilter())) {
|
||||
return *(this->getServiceIdBloomFilter()) <
|
||||
*(rhs.getServiceIdBloomFilter());
|
||||
}
|
||||
return *(this->getAdvertisementHash()) < *(rhs.getAdvertisementHash());
|
||||
}
|
||||
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
@@ -0,0 +1,91 @@
|
||||
#ifndef CORE_INTERNAL_MEDIUMS_BLE_ADVERTISEMENT_HEADER_H_
|
||||
#define CORE_INTERNAL_MEDIUMS_BLE_ADVERTISEMENT_HEADER_H_
|
||||
|
||||
#include "platform/byte_array.h"
|
||||
#include "platform/ptr.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
// Represents the format of the Mediums BLE Advertisement Header used in
|
||||
// Advertising + Discovery.
|
||||
//
|
||||
// [VERSION][NUM_SLOTS][SERVICE_ID_BLOOM_FILTER][ADVERTISEMENT_HASH]
|
||||
//
|
||||
// See go/nearby-ble-design for more information.
|
||||
class BLEAdvertisementHeader {
|
||||
public:
|
||||
// Versions of the BLEAdvertisementHeader.
|
||||
struct Version {
|
||||
enum Value {
|
||||
V2 = 2,
|
||||
// Version is only allocated 3 bits in the BLEAdvertisementHeader, so this
|
||||
// can never go beyond V7.
|
||||
//
|
||||
// V1 is not present because it's an old format used in Nearby Connections
|
||||
// before this logic was pushed down into Nearby Mediums. V1 put
|
||||
// everything in the service data, while V2 puts the data inside a GATT
|
||||
// characteristic so the two are not compatible.
|
||||
};
|
||||
};
|
||||
|
||||
static ConstPtr<BLEAdvertisementHeader> fromString(
|
||||
const std::string &ble_advertisement_header_string);
|
||||
|
||||
static std::string asString(Version::Value version, std::uint32_t num_slots,
|
||||
ConstPtr<ByteArray> service_id_bloom_filter,
|
||||
ConstPtr<ByteArray> advertisement_hash);
|
||||
|
||||
static const std::uint32_t kServiceIdBloomFilterLength;
|
||||
static const std::uint32_t kAdvertisementHashLength;
|
||||
|
||||
~BLEAdvertisementHeader();
|
||||
|
||||
Version::Value getVersion() const;
|
||||
std::uint32_t getNumSlots() const;
|
||||
ConstPtr<ByteArray> getServiceIdBloomFilter() const;
|
||||
ConstPtr<ByteArray> getAdvertisementHash() const;
|
||||
|
||||
// Operator overloads when comparing ConstPtr<BLEAdvertisementHeader>.
|
||||
bool operator<(const BLEAdvertisementHeader &rhs) const;
|
||||
|
||||
private:
|
||||
// DiscoveredPeripheralTracker needs to be a friend of this class because it
|
||||
// directly calls the constructor (the Java code keeps the constructor package
|
||||
// private).
|
||||
// Calling the constuctor directly allows us to avoid the unnessary extra
|
||||
// calls to parse and decode to get the BLEAdvertisementHeader.
|
||||
template <typename>
|
||||
friend class DiscoveredPeripheralTracker;
|
||||
|
||||
static Version::Value parseVersionFromByte(std::uint16_t byte);
|
||||
static std::uint32_t parseNumSlotsFromByte(std::uint16_t byte);
|
||||
|
||||
static const std::uint32_t kVersionAndNumSlotsLength;
|
||||
static const std::uint32_t kMinAdvertisementHeaderLength;
|
||||
static const std::uint16_t kVersionBitmask;
|
||||
static const std::uint16_t kNumSlotsBitmask;
|
||||
|
||||
BLEAdvertisementHeader(Version::Value version, std::uint32_t num_slots,
|
||||
ConstPtr<ByteArray> service_id_bloom_filter,
|
||||
ConstPtr<ByteArray> advertisement_hash);
|
||||
|
||||
static void serializeVersionByte(char *version_byte_write_ptr,
|
||||
Version::Value version);
|
||||
static void serializeNumSlots(char *num_slots_byte_write_ptr,
|
||||
std::uint32_t num_slots);
|
||||
|
||||
const Version::Value version_;
|
||||
const uint32_t num_slots_;
|
||||
ScopedPtr<ConstPtr<ByteArray> > service_id_bloom_filter_;
|
||||
ScopedPtr<ConstPtr<ByteArray> > advertisement_hash_;
|
||||
};
|
||||
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
|
||||
#endif // CORE_INTERNAL_MEDIUMS_BLE_ADVERTISEMENT_HEADER_H_
|
||||
@@ -0,0 +1,221 @@
|
||||
#include "core/internal/mediums/ble_advertisement_header.h"
|
||||
|
||||
#include "platform/base64_utils.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
const BLEAdvertisementHeader::Version::Value kVersion =
|
||||
BLEAdvertisementHeader::Version::V2;
|
||||
const std::uint32_t kNumSlots = 2;
|
||||
const char kServiceIDBloomFilter[] = {0x01, 0x02, 0x03, 0x04, 0x05,
|
||||
0x06, 0x07, 0x08, 0x09, 0x0A};
|
||||
const char kAdvertisementHash[] = {0x0A, 0x0B, 0x0C, 0x0D};
|
||||
const size_t kAdvertisementHeaderLength = 15;
|
||||
const size_t kLongAdvertisementHeaderLength = kAdvertisementHeaderLength + 1;
|
||||
const size_t kShortAdvertisementHeaderLength = kAdvertisementHeaderLength - 1;
|
||||
|
||||
TEST(BLEAdvertisementHeader, SerializationDeserializationWorks) {
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_bloom_filter(MakeConstPtr(
|
||||
new ByteArray(kServiceIDBloomFilter,
|
||||
sizeof(kServiceIDBloomFilter) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_advertisement_hash(
|
||||
MakeConstPtr(new ByteArray(kAdvertisementHash,
|
||||
sizeof(kAdvertisementHash) / sizeof(char))));
|
||||
|
||||
std::string ble_advertisement_header_string(BLEAdvertisementHeader::asString(
|
||||
kVersion, kNumSlots, scoped_service_id_bloom_filter.get(),
|
||||
scoped_advertisement_hash.get()));
|
||||
ScopedPtr<ConstPtr<BLEAdvertisementHeader> > scoped_ble_advertisement_header(
|
||||
BLEAdvertisementHeader::fromString(ble_advertisement_header_string));
|
||||
|
||||
ASSERT_EQ(kVersion, scoped_ble_advertisement_header->getVersion());
|
||||
ASSERT_EQ(kNumSlots, scoped_ble_advertisement_header->getNumSlots());
|
||||
ASSERT_EQ(
|
||||
0,
|
||||
memcmp(
|
||||
kServiceIDBloomFilter,
|
||||
scoped_ble_advertisement_header->getServiceIdBloomFilter()->getData(),
|
||||
scoped_ble_advertisement_header->getServiceIdBloomFilter()->size()));
|
||||
ASSERT_EQ(
|
||||
0,
|
||||
memcmp(kAdvertisementHash,
|
||||
scoped_ble_advertisement_header->getAdvertisementHash()->getData(),
|
||||
scoped_ble_advertisement_header->getAdvertisementHash()->size()));
|
||||
}
|
||||
|
||||
TEST(BLEAdvertisementHeader, SerializationFailsWithBadVersion) {
|
||||
BLEAdvertisementHeader::Version::Value bad_version =
|
||||
static_cast<BLEAdvertisementHeader::Version::Value>(666);
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_bloom_filter(MakeConstPtr(
|
||||
new ByteArray(kServiceIDBloomFilter,
|
||||
sizeof(kServiceIDBloomFilter) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_advertisement_hash(
|
||||
MakeConstPtr(new ByteArray(kAdvertisementHash,
|
||||
sizeof(kAdvertisementHash) / sizeof(char))));
|
||||
|
||||
std::string ble_advertisement_header_string(BLEAdvertisementHeader::asString(
|
||||
bad_version, kNumSlots, scoped_service_id_bloom_filter.get(),
|
||||
scoped_advertisement_hash.get()));
|
||||
|
||||
ASSERT_EQ("", ble_advertisement_header_string);
|
||||
}
|
||||
|
||||
TEST(BLEAdvertisementHeader, SerializationFailsWithShortServiceIdBloomFilter) {
|
||||
char short_service_id_bloom_filter[] = {0x01, 0x02, 0x03, 0x04, 0x05,
|
||||
0x06, 0x07, 0x08, 0x09};
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_bloom_filter(MakeConstPtr(
|
||||
new ByteArray(short_service_id_bloom_filter,
|
||||
sizeof(short_service_id_bloom_filter) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_advertisement_hash(
|
||||
MakeConstPtr(new ByteArray(kAdvertisementHash,
|
||||
sizeof(kAdvertisementHash) / sizeof(char))));
|
||||
|
||||
std::string ble_advertisement_header_string(BLEAdvertisementHeader::asString(
|
||||
kVersion, kNumSlots, scoped_service_id_bloom_filter.get(),
|
||||
scoped_advertisement_hash.get()));
|
||||
|
||||
ASSERT_EQ("", ble_advertisement_header_string);
|
||||
}
|
||||
|
||||
TEST(BLEAdvertisementHeader, SerializationFailsWithLongServiceIdBloomFilter) {
|
||||
char long_service_id_bloom_filter[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
|
||||
0x07, 0x08, 0x09, 0x0A, 0x0B};
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_bloom_filter(MakeConstPtr(
|
||||
new ByteArray(long_service_id_bloom_filter,
|
||||
sizeof(long_service_id_bloom_filter) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_advertisement_hash(
|
||||
MakeConstPtr(new ByteArray(kAdvertisementHash,
|
||||
sizeof(kAdvertisementHash) / sizeof(char))));
|
||||
|
||||
std::string ble_advertisement_header_string(BLEAdvertisementHeader::asString(
|
||||
kVersion, kNumSlots, scoped_service_id_bloom_filter.get(),
|
||||
scoped_advertisement_hash.get()));
|
||||
|
||||
ASSERT_EQ("", ble_advertisement_header_string);
|
||||
}
|
||||
|
||||
TEST(BLEAdvertisementHeader, SerializationFailsWithShortAdvertisementHash) {
|
||||
char short_advertisement_hash[] = {0x0A, 0x0B, 0x0C};
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_bloom_filter(MakeConstPtr(
|
||||
new ByteArray(kServiceIDBloomFilter,
|
||||
sizeof(kServiceIDBloomFilter) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_advertisement_hash(MakeConstPtr(
|
||||
new ByteArray(short_advertisement_hash,
|
||||
sizeof(short_advertisement_hash) / sizeof(char))));
|
||||
|
||||
std::string ble_advertisement_header_string(BLEAdvertisementHeader::asString(
|
||||
kVersion, kNumSlots, scoped_service_id_bloom_filter.get(),
|
||||
scoped_advertisement_hash.get()));
|
||||
|
||||
ASSERT_EQ("", ble_advertisement_header_string);
|
||||
}
|
||||
|
||||
TEST(BLEAdvertisementHeader, SerializationFailsWithLongAdvertisementHash) {
|
||||
char long_advertisement_hash[] = {0x0A, 0x0B, 0x0C, 0x0D, 0x0E};
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_bloom_filter(MakeConstPtr(
|
||||
new ByteArray(kServiceIDBloomFilter,
|
||||
sizeof(kServiceIDBloomFilter) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_advertisement_hash(MakeConstPtr(
|
||||
new ByteArray(long_advertisement_hash,
|
||||
sizeof(long_advertisement_hash) / sizeof(char))));
|
||||
|
||||
std::string ble_advertisement_header_string(BLEAdvertisementHeader::asString(
|
||||
kVersion, kNumSlots, scoped_service_id_bloom_filter.get(),
|
||||
scoped_advertisement_hash.get()));
|
||||
|
||||
ASSERT_EQ("", ble_advertisement_header_string);
|
||||
}
|
||||
|
||||
TEST(BLEAdvertisementHeader, DeserializationWorksWithExtraBytes) {
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_bloom_filter(MakeConstPtr(
|
||||
new ByteArray(kServiceIDBloomFilter,
|
||||
sizeof(kServiceIDBloomFilter) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_advertisement_hash(
|
||||
MakeConstPtr(new ByteArray(kAdvertisementHash,
|
||||
sizeof(kAdvertisementHash) / sizeof(char))));
|
||||
std::string ble_advertisement_header_string =
|
||||
BLEAdvertisementHeader::asString(kVersion, kNumSlots,
|
||||
scoped_service_id_bloom_filter.get(),
|
||||
scoped_advertisement_hash.get());
|
||||
|
||||
// Base64 decode the string, add a character, and then re-encode it. We must
|
||||
// explicitly define how long our array is because we can't use variable
|
||||
// length arrays.
|
||||
ScopedPtr<Ptr<ByteArray> > scoped_ble_advertisement_header_bytes(
|
||||
Base64Utils::decode(ble_advertisement_header_string));
|
||||
char raw_long_ble_advertisement_header_bytes[kLongAdvertisementHeaderLength];
|
||||
memcpy(raw_long_ble_advertisement_header_bytes,
|
||||
scoped_ble_advertisement_header_bytes->getData(),
|
||||
kLongAdvertisementHeaderLength);
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_long_ble_advertisement_header_bytes(
|
||||
MakeConstPtr(new ByteArray(raw_long_ble_advertisement_header_bytes,
|
||||
kLongAdvertisementHeaderLength)));
|
||||
std::string long_ble_advertisement_header_string =
|
||||
Base64Utils::encode(scoped_long_ble_advertisement_header_bytes.get());
|
||||
|
||||
ScopedPtr<ConstPtr<BLEAdvertisementHeader> > scoped_ble_advertisement_header(
|
||||
BLEAdvertisementHeader::fromString(long_ble_advertisement_header_string));
|
||||
|
||||
ASSERT_EQ(kVersion, scoped_ble_advertisement_header->getVersion());
|
||||
ASSERT_EQ(kNumSlots, scoped_ble_advertisement_header->getNumSlots());
|
||||
ASSERT_EQ(
|
||||
0,
|
||||
memcmp(
|
||||
kServiceIDBloomFilter,
|
||||
scoped_ble_advertisement_header->getServiceIdBloomFilter()->getData(),
|
||||
scoped_ble_advertisement_header->getServiceIdBloomFilter()->size()));
|
||||
ASSERT_EQ(
|
||||
0,
|
||||
memcmp(kAdvertisementHash,
|
||||
scoped_ble_advertisement_header->getAdvertisementHash()->getData(),
|
||||
scoped_ble_advertisement_header->getAdvertisementHash()->size()));
|
||||
}
|
||||
|
||||
TEST(BLEAdvertisementHeader, DeserializationFailsWithShortLength) {
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_bloom_filter(MakeConstPtr(
|
||||
new ByteArray(kServiceIDBloomFilter,
|
||||
sizeof(kServiceIDBloomFilter) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_advertisement_hash(
|
||||
MakeConstPtr(new ByteArray(kAdvertisementHash,
|
||||
sizeof(kAdvertisementHash) / sizeof(char))));
|
||||
std::string ble_advertisement_header_string =
|
||||
BLEAdvertisementHeader::asString(kVersion, kNumSlots,
|
||||
scoped_service_id_bloom_filter.get(),
|
||||
scoped_advertisement_hash.get());
|
||||
|
||||
// Base64 decode the string, remove a character, and then re-encode it. We
|
||||
// must explicitly define how long our array is because we can't use variable
|
||||
// length arrays.
|
||||
ScopedPtr<Ptr<ByteArray> > scoped_ble_advertisement_header_bytes(
|
||||
Base64Utils::decode(ble_advertisement_header_string));
|
||||
char
|
||||
raw_short_ble_advertisement_header_bytes[kShortAdvertisementHeaderLength];
|
||||
memcpy(raw_short_ble_advertisement_header_bytes,
|
||||
scoped_ble_advertisement_header_bytes->getData(),
|
||||
kShortAdvertisementHeaderLength);
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_short_ble_advertisement_header_bytes(
|
||||
MakeConstPtr(new ByteArray(raw_short_ble_advertisement_header_bytes,
|
||||
kShortAdvertisementHeaderLength)));
|
||||
std::string short_ble_advertisement_header_string =
|
||||
Base64Utils::encode(scoped_short_ble_advertisement_header_bytes.get());
|
||||
|
||||
ScopedPtr<ConstPtr<BLEAdvertisementHeader> > scoped_ble_advertisement_header(
|
||||
BLEAdvertisementHeader::fromString(
|
||||
short_ble_advertisement_header_string));
|
||||
|
||||
ASSERT_TRUE(scoped_ble_advertisement_header.isNull());
|
||||
}
|
||||
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
@@ -0,0 +1,319 @@
|
||||
#include "core/internal/mediums/ble_advertisement.h"
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
namespace {
|
||||
|
||||
const BLEAdvertisement::Version::Value kVersion = BLEAdvertisement::Version::V2;
|
||||
const BLEAdvertisement::SocketVersion::Value kSocketVersion =
|
||||
BLEAdvertisement::SocketVersion::V2;
|
||||
const char kServiceIDHashBytes[] = {0x0A, 0x0B, 0x0C};
|
||||
const char kData[] =
|
||||
"How much wood can a woodchuck chuck if a wood chuck would chuck wood?";
|
||||
// This corresponds to the length of a specific BLEAdvertisement packed with the
|
||||
// kData given above. Be sure to update this if kData ever changes.
|
||||
const size_t kAdvertisementLength = 77;
|
||||
const size_t kLongAdvertisementLength = kAdvertisementLength + 1000;
|
||||
|
||||
TEST(BLEAdvertisementTest, SerializationDeserializationWorksV1) {
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_hash(
|
||||
MakeConstPtr(new ByteArray(kServiceIDHashBytes,
|
||||
sizeof(kServiceIDHashBytes) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_data(
|
||||
MakeConstPtr(new ByteArray(kData, sizeof(kData) / sizeof(char))));
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_ble_advertisement_bytes(
|
||||
BLEAdvertisement::toBytes(
|
||||
BLEAdvertisement::Version::V1, BLEAdvertisement::SocketVersion::V1,
|
||||
scoped_service_id_hash.get(), scoped_data.get()));
|
||||
ScopedPtr<ConstPtr<BLEAdvertisement> > scoped_ble_advertisement(
|
||||
BLEAdvertisement::fromBytes(scoped_ble_advertisement_bytes.get()));
|
||||
|
||||
ASSERT_EQ(BLEAdvertisement::Version::V1,
|
||||
scoped_ble_advertisement->getVersion());
|
||||
ASSERT_EQ(BLEAdvertisement::SocketVersion::V1,
|
||||
scoped_ble_advertisement->getSocketVersion());
|
||||
ASSERT_EQ(scoped_service_id_hash->size(),
|
||||
scoped_ble_advertisement->getServiceIdHash()->size());
|
||||
ASSERT_EQ(0, memcmp(kServiceIDHashBytes,
|
||||
scoped_ble_advertisement->getServiceIdHash()->getData(),
|
||||
scoped_ble_advertisement->getServiceIdHash()->size()));
|
||||
ASSERT_EQ(scoped_data->size(), scoped_ble_advertisement->getData()->size());
|
||||
ASSERT_EQ(0, memcmp(kData, scoped_ble_advertisement->getData()->getData(),
|
||||
scoped_ble_advertisement->getData()->size()));
|
||||
}
|
||||
|
||||
TEST(BLEAdvertisementTest, SerializationDeserializationWorks) {
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_hash(
|
||||
MakeConstPtr(new ByteArray(kServiceIDHashBytes,
|
||||
sizeof(kServiceIDHashBytes) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_data(
|
||||
MakeConstPtr(new ByteArray(kData, sizeof(kData) / sizeof(char))));
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_ble_advertisement_bytes(
|
||||
BLEAdvertisement::toBytes(kVersion, kSocketVersion,
|
||||
scoped_service_id_hash.get(),
|
||||
scoped_data.get()));
|
||||
ScopedPtr<ConstPtr<BLEAdvertisement> > scoped_ble_advertisement(
|
||||
BLEAdvertisement::fromBytes(scoped_ble_advertisement_bytes.get()));
|
||||
|
||||
ASSERT_EQ(kVersion, scoped_ble_advertisement->getVersion());
|
||||
ASSERT_EQ(kSocketVersion, scoped_ble_advertisement->getSocketVersion());
|
||||
ASSERT_EQ(scoped_service_id_hash->size(),
|
||||
scoped_ble_advertisement->getServiceIdHash()->size());
|
||||
ASSERT_EQ(0, memcmp(kServiceIDHashBytes,
|
||||
scoped_ble_advertisement->getServiceIdHash()->getData(),
|
||||
scoped_ble_advertisement->getServiceIdHash()->size()));
|
||||
ASSERT_EQ(scoped_data->size(), scoped_ble_advertisement->getData()->size());
|
||||
ASSERT_EQ(0, memcmp(kData, scoped_ble_advertisement->getData()->getData(),
|
||||
scoped_ble_advertisement->getData()->size()));
|
||||
}
|
||||
|
||||
TEST(BLEAdvertisementTest, SerializationDeserializationWorksWithEmptyData) {
|
||||
char empty_data[0];
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_hash(
|
||||
MakeConstPtr(new ByteArray(kServiceIDHashBytes,
|
||||
sizeof(kServiceIDHashBytes) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_data(MakeConstPtr(
|
||||
new ByteArray(empty_data, sizeof(empty_data) / sizeof(char))));
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_ble_advertisement_bytes(
|
||||
BLEAdvertisement::toBytes(kVersion, kSocketVersion,
|
||||
scoped_service_id_hash.get(),
|
||||
scoped_data.get()));
|
||||
ScopedPtr<ConstPtr<BLEAdvertisement> > scoped_ble_advertisement(
|
||||
BLEAdvertisement::fromBytes(scoped_ble_advertisement_bytes.get()));
|
||||
|
||||
ASSERT_EQ(kVersion, scoped_ble_advertisement->getVersion());
|
||||
ASSERT_EQ(kSocketVersion, scoped_ble_advertisement->getSocketVersion());
|
||||
ASSERT_EQ(scoped_service_id_hash->size(),
|
||||
scoped_ble_advertisement->getServiceIdHash()->size());
|
||||
ASSERT_EQ(0, memcmp(kServiceIDHashBytes,
|
||||
scoped_ble_advertisement->getServiceIdHash()->getData(),
|
||||
scoped_ble_advertisement->getServiceIdHash()->size()));
|
||||
ASSERT_EQ(scoped_data->size(), scoped_ble_advertisement->getData()->size());
|
||||
ASSERT_EQ(0, memcmp(kData, scoped_ble_advertisement->getData()->getData(),
|
||||
scoped_ble_advertisement->getData()->size()));
|
||||
}
|
||||
|
||||
TEST(BLEAdvertisementTest, SerializationDeserializationFailsWithLargeData) {
|
||||
// Create data that's larger than the allowed size.
|
||||
char large_data[513];
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_hash(
|
||||
MakeConstPtr(new ByteArray(kServiceIDHashBytes,
|
||||
sizeof(kServiceIDHashBytes) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_data(MakeConstPtr(
|
||||
new ByteArray(large_data, sizeof(large_data) / sizeof(char))));
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_ble_advertisement_bytes(
|
||||
BLEAdvertisement::toBytes(kVersion, kSocketVersion,
|
||||
scoped_service_id_hash.get(),
|
||||
scoped_data.get()));
|
||||
ScopedPtr<ConstPtr<BLEAdvertisement> > scoped_ble_advertisement(
|
||||
BLEAdvertisement::fromBytes(scoped_ble_advertisement_bytes.get()));
|
||||
|
||||
ASSERT_TRUE(scoped_ble_advertisement.isNull());
|
||||
}
|
||||
|
||||
TEST(BLEAdvertisementTest, SerializationFailsWithBadVersion) {
|
||||
BLEAdvertisement::Version::Value bad_version =
|
||||
static_cast<BLEAdvertisement::Version::Value>(666);
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_hash(
|
||||
MakeConstPtr(new ByteArray(kServiceIDHashBytes,
|
||||
sizeof(kServiceIDHashBytes) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_data(
|
||||
MakeConstPtr(new ByteArray(kData, sizeof(kData) / sizeof(char))));
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_ble_advertisement_bytes(
|
||||
BLEAdvertisement::toBytes(bad_version, kSocketVersion,
|
||||
scoped_service_id_hash.get(),
|
||||
scoped_data.get()));
|
||||
|
||||
ASSERT_TRUE(scoped_ble_advertisement_bytes.isNull());
|
||||
}
|
||||
|
||||
TEST(BLEAdvertisementTest, SerializationFailsWithBadSocketVersion) {
|
||||
BLEAdvertisement::SocketVersion::Value bad_socket_version =
|
||||
static_cast<BLEAdvertisement::SocketVersion::Value>(666);
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_hash(
|
||||
MakeConstPtr(new ByteArray(kServiceIDHashBytes,
|
||||
sizeof(kServiceIDHashBytes) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_data(
|
||||
MakeConstPtr(new ByteArray(kData, sizeof(kData) / sizeof(char))));
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_ble_advertisement_bytes(
|
||||
BLEAdvertisement::toBytes(kVersion, bad_socket_version,
|
||||
scoped_service_id_hash.get(),
|
||||
scoped_data.get()));
|
||||
|
||||
ASSERT_TRUE(scoped_ble_advertisement_bytes.isNull());
|
||||
}
|
||||
|
||||
TEST(BLEAdvertisementTest, SerializationFailsWithShortServiceIdHash) {
|
||||
char short_service_id_hash_bytes[] = {0x0A, 0x0B};
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_hash(MakeConstPtr(
|
||||
new ByteArray(short_service_id_hash_bytes,
|
||||
sizeof(short_service_id_hash_bytes) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_data(
|
||||
MakeConstPtr(new ByteArray(kData, sizeof(kData) / sizeof(char))));
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_ble_advertisement_bytes(
|
||||
BLEAdvertisement::toBytes(kVersion, kSocketVersion,
|
||||
scoped_service_id_hash.get(),
|
||||
scoped_data.get()));
|
||||
|
||||
ASSERT_TRUE(scoped_ble_advertisement_bytes.isNull());
|
||||
}
|
||||
|
||||
TEST(BLEAdvertisementTest, SerializationFailsWithLongServiceIdHash) {
|
||||
char long_service_id_hash_bytes[] = {0x0A, 0x0B, 0x0C, 0x0D};
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_hash(MakeConstPtr(
|
||||
new ByteArray(long_service_id_hash_bytes,
|
||||
sizeof(long_service_id_hash_bytes) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_data(
|
||||
MakeConstPtr(new ByteArray(kData, sizeof(kData) / sizeof(char))));
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_ble_advertisement_bytes(
|
||||
BLEAdvertisement::toBytes(kVersion, kSocketVersion,
|
||||
scoped_service_id_hash.get(),
|
||||
scoped_data.get()));
|
||||
|
||||
ASSERT_TRUE(scoped_ble_advertisement_bytes.isNull());
|
||||
}
|
||||
|
||||
TEST(BLEAdvertisementTest, SerializationFailsWithLongData) {
|
||||
// BLEAdvertisement shouldn't be able to support data with the max GATT
|
||||
// attribute length because it needs some room for the preceding fields.
|
||||
char long_data[512];
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_hash(
|
||||
MakeConstPtr(new ByteArray(kServiceIDHashBytes,
|
||||
sizeof(kServiceIDHashBytes) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_data(
|
||||
MakeConstPtr(new ByteArray(long_data, sizeof(long_data) / sizeof(char))));
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_ble_advertisement_bytes(
|
||||
BLEAdvertisement::toBytes(kVersion, kSocketVersion,
|
||||
scoped_service_id_hash.get(),
|
||||
scoped_data.get()));
|
||||
|
||||
ASSERT_TRUE(scoped_ble_advertisement_bytes.isNull());
|
||||
}
|
||||
|
||||
TEST(BLEAdvertisementTest, DeserializationWorksWithExtraBytes) {
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_hash(
|
||||
MakeConstPtr(new ByteArray(kServiceIDHashBytes,
|
||||
sizeof(kServiceIDHashBytes) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_data(
|
||||
MakeConstPtr(new ByteArray(kData, sizeof(kData) / sizeof(char))));
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_ble_advertisement_bytes(
|
||||
BLEAdvertisement::toBytes(kVersion, kSocketVersion,
|
||||
scoped_service_id_hash.get(),
|
||||
scoped_data.get()));
|
||||
|
||||
// Copy the bytes into a new array with extra bytes. We must explicitly
|
||||
// define how long our array is because we can't use variable length arrays.
|
||||
char raw_ble_advertisement_bytes[kLongAdvertisementLength];
|
||||
memcpy(raw_ble_advertisement_bytes, scoped_ble_advertisement_bytes->getData(),
|
||||
kLongAdvertisementLength);
|
||||
|
||||
// Re-parse the BLE advertisement using our extra long advertisement bytes.
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_long_ble_advertisement_bytes(
|
||||
MakeConstPtr(new ByteArray(raw_ble_advertisement_bytes,
|
||||
kLongAdvertisementLength)));
|
||||
ScopedPtr<ConstPtr<BLEAdvertisement> > scoped_long_ble_advertisement(
|
||||
BLEAdvertisement::fromBytes(scoped_long_ble_advertisement_bytes.get()));
|
||||
|
||||
ASSERT_EQ(kVersion, scoped_long_ble_advertisement->getVersion());
|
||||
ASSERT_EQ(kSocketVersion, scoped_long_ble_advertisement->getSocketVersion());
|
||||
ASSERT_EQ(scoped_service_id_hash->size(),
|
||||
scoped_long_ble_advertisement->getServiceIdHash()->size());
|
||||
ASSERT_EQ(0,
|
||||
memcmp(kServiceIDHashBytes,
|
||||
scoped_long_ble_advertisement->getServiceIdHash()->getData(),
|
||||
scoped_long_ble_advertisement->getServiceIdHash()->size()));
|
||||
ASSERT_EQ(scoped_data->size(),
|
||||
scoped_long_ble_advertisement->getData()->size());
|
||||
ASSERT_EQ(0,
|
||||
memcmp(kData, scoped_long_ble_advertisement->getData()->getData(),
|
||||
scoped_long_ble_advertisement->getData()->size()));
|
||||
}
|
||||
|
||||
TEST(BLEAdvertisementTest, DeserializationFailsWithNullBytes) {
|
||||
ScopedPtr<ConstPtr<BLEAdvertisement> > scoped_ble_advertisement(
|
||||
BLEAdvertisement::fromBytes(ConstPtr<ByteArray>()));
|
||||
|
||||
ASSERT_TRUE(scoped_ble_advertisement.isNull());
|
||||
}
|
||||
|
||||
TEST(BLEAdvertisementTest, DeserializationFailsWithShortLength) {
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_hash(
|
||||
MakeConstPtr(new ByteArray(kServiceIDHashBytes,
|
||||
sizeof(kServiceIDHashBytes) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_data(
|
||||
MakeConstPtr(new ByteArray(kData, sizeof(kData) / sizeof(char))));
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_ble_advertisement_bytes(
|
||||
BLEAdvertisement::toBytes(kVersion, kSocketVersion,
|
||||
scoped_service_id_hash.get(),
|
||||
scoped_data.get()));
|
||||
|
||||
// Cut off the advertisement so that it's too short.
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_short_ble_advertisement_bytes(
|
||||
MakeConstPtr(
|
||||
new ByteArray(scoped_ble_advertisement_bytes->getData(), 7)));
|
||||
ScopedPtr<ConstPtr<BLEAdvertisement> > scoped_ble_advertisement(
|
||||
BLEAdvertisement::fromBytes(scoped_short_ble_advertisement_bytes.get()));
|
||||
|
||||
ASSERT_TRUE(scoped_ble_advertisement.isNull());
|
||||
}
|
||||
|
||||
TEST(BLEAdvertisementTest, DeserializationFailsWithInvalidDataLength) {
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_hash(
|
||||
MakeConstPtr(new ByteArray(kServiceIDHashBytes,
|
||||
sizeof(kServiceIDHashBytes) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_data(
|
||||
MakeConstPtr(new ByteArray(kData, sizeof(kData) / sizeof(char))));
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_ble_advertisement_bytes(
|
||||
BLEAdvertisement::toBytes(kVersion, kSocketVersion,
|
||||
scoped_service_id_hash.get(),
|
||||
scoped_data.get()));
|
||||
|
||||
// Corrupt the DATA_SIZE bits. Start by making a raw copy of the BLE
|
||||
// advertisement bytes so we can modify it. We must explicitly define how long
|
||||
// our array is because we can't use variable length arrays.
|
||||
char raw_ble_advertisement_bytes[kAdvertisementLength];
|
||||
memcpy(raw_ble_advertisement_bytes, scoped_ble_advertisement_bytes->getData(),
|
||||
kAdvertisementLength);
|
||||
|
||||
// The data size field lives in indices 4-7. Corrupt it.
|
||||
memset(raw_ble_advertisement_bytes + 4, 0xFF, 4);
|
||||
|
||||
// Try to parse the BLE advertisement using our corrupted advertisement bytes.
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_corrupted_ble_advertisement_bytes(
|
||||
MakeConstPtr(
|
||||
new ByteArray(raw_ble_advertisement_bytes, kAdvertisementLength)));
|
||||
ScopedPtr<ConstPtr<BLEAdvertisement> > scoped_ble_advertisement(
|
||||
BLEAdvertisement::fromBytes(
|
||||
scoped_corrupted_ble_advertisement_bytes.get()));
|
||||
|
||||
ASSERT_TRUE(scoped_ble_advertisement.isNull());
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
@@ -0,0 +1,112 @@
|
||||
#include "core/internal/mediums/ble_packet.h"
|
||||
|
||||
#include <limits>
|
||||
|
||||
#include "platform/logging.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
const std::uint32_t BLEPacket::kServiceIdHashLength = 3;
|
||||
|
||||
const std::uint32_t BLEPacket::kMinPacketLength = kServiceIdHashLength;
|
||||
const std::uint32_t BLEPacket::kMaxDataSize =
|
||||
std::numeric_limits<int32_t>::max() - kMinPacketLength;
|
||||
|
||||
ConstPtr<BLEPacket> BLEPacket::fromBytes(ConstPtr<ByteArray> ble_packet_bytes) {
|
||||
if (ble_packet_bytes.isNull()) {
|
||||
NEARBY_LOG(INFO, "Cannot deserialize BLEPacket: null bytes passed in");
|
||||
return ConstPtr<BLEPacket>();
|
||||
}
|
||||
|
||||
if (ble_packet_bytes->size() < kMinPacketLength) {
|
||||
NEARBY_LOG(
|
||||
INFO,
|
||||
"Cannot deserialize BLEPacket: expecting min %u raw bytes, got %zu",
|
||||
kMinPacketLength, ble_packet_bytes->size());
|
||||
return ConstPtr<BLEPacket>();
|
||||
}
|
||||
|
||||
// Now, time to read the bytes!
|
||||
const char *ble_packet_bytes_read_ptr = ble_packet_bytes->getData();
|
||||
|
||||
// 1. Service ID hash.
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_hash(MakeConstPtr(
|
||||
new ByteArray(ble_packet_bytes_read_ptr, kServiceIdHashLength)));
|
||||
ble_packet_bytes_read_ptr += kServiceIdHashLength;
|
||||
|
||||
// 2. Data.
|
||||
size_t data_size = computeDataSize(ble_packet_bytes);
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_data(
|
||||
MakeConstPtr(new ByteArray(ble_packet_bytes_read_ptr, data_size)));
|
||||
ble_packet_bytes_read_ptr += data_size;
|
||||
|
||||
return MakeConstPtr(
|
||||
new BLEPacket(scoped_service_id_hash.release(), scoped_data.release()));
|
||||
}
|
||||
|
||||
ConstPtr<ByteArray> BLEPacket::toBytes(ConstPtr<ByteArray> service_id_hash,
|
||||
ConstPtr<ByteArray> data) {
|
||||
if (service_id_hash->size() != kServiceIdHashLength) {
|
||||
NEARBY_LOG(
|
||||
INFO,
|
||||
"Cannot serialize BLEPacket: expected a service_id_hash of %u bytes, "
|
||||
"but got %zu",
|
||||
kServiceIdHashLength, service_id_hash->size());
|
||||
return ConstPtr<ByteArray>();
|
||||
}
|
||||
|
||||
if (data->size() > kMaxDataSize) {
|
||||
NEARBY_LOG(INFO,
|
||||
"Cannot serialize BLEPacket: expected data of at most %u bytes, "
|
||||
"but got %zu",
|
||||
kMaxDataSize, data->size());
|
||||
return ConstPtr<ByteArray>();
|
||||
}
|
||||
|
||||
// Initialize the bytes.
|
||||
size_t packet_length = computePacketLength(data);
|
||||
Ptr<ByteArray> packet_bytes{new ByteArray{packet_length}};
|
||||
char *packet_bytes_write_ptr = packet_bytes->getData();
|
||||
|
||||
// 1. Service ID hash.
|
||||
memcpy(packet_bytes_write_ptr, service_id_hash->getData(),
|
||||
kServiceIdHashLength);
|
||||
packet_bytes_write_ptr += kServiceIdHashLength;
|
||||
|
||||
// 2. Data.
|
||||
memcpy(packet_bytes_write_ptr, data->getData(), data->size());
|
||||
packet_bytes_write_ptr += data->size();
|
||||
|
||||
return ConstifyPtr(packet_bytes);
|
||||
}
|
||||
|
||||
size_t BLEPacket::computeDataSize(ConstPtr<ByteArray> ble_packet_bytes) {
|
||||
return ble_packet_bytes->size() - kMinPacketLength;
|
||||
}
|
||||
|
||||
size_t BLEPacket::computePacketLength(ConstPtr<ByteArray> data) {
|
||||
// The packet length is the minimum length + the length of the data.
|
||||
return kMinPacketLength + data->size();
|
||||
}
|
||||
|
||||
BLEPacket::BLEPacket(ConstPtr<ByteArray> service_id_hash,
|
||||
ConstPtr<ByteArray> data)
|
||||
: service_id_hash_(service_id_hash), data_(data) {}
|
||||
|
||||
BLEPacket::~BLEPacket() {
|
||||
// Nothing to do.
|
||||
}
|
||||
|
||||
ConstPtr<ByteArray> BLEPacket::getServiceIdHash() const {
|
||||
return service_id_hash_.get();
|
||||
}
|
||||
|
||||
ConstPtr<ByteArray> BLEPacket::getData() const { return data_.get(); }
|
||||
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
@@ -0,0 +1,49 @@
|
||||
#ifndef CORE_INTERNAL_MEDIUMS_BLE_PACKET_H_
|
||||
#define CORE_INTERNAL_MEDIUMS_BLE_PACKET_H_
|
||||
|
||||
#include "platform/byte_array.h"
|
||||
#include "platform/ptr.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
// Represents the format of data sent over BLE sockets.
|
||||
//
|
||||
// [SERVICE_ID_HASH][DATA]
|
||||
//
|
||||
// See go/nearby-ble-design for more information.
|
||||
class BLEPacket {
|
||||
public:
|
||||
static ConstPtr<BLEPacket> fromBytes(ConstPtr<ByteArray> ble_packet_bytes);
|
||||
|
||||
static ConstPtr<ByteArray> toBytes(ConstPtr<ByteArray> service_id_hash,
|
||||
ConstPtr<ByteArray> data);
|
||||
|
||||
static const std::uint32_t kServiceIdHashLength;
|
||||
|
||||
~BLEPacket();
|
||||
|
||||
ConstPtr<ByteArray> getServiceIdHash() const;
|
||||
ConstPtr<ByteArray> getData() const;
|
||||
|
||||
private:
|
||||
static size_t computeDataSize(ConstPtr<ByteArray> ble_packet_bytes);
|
||||
static size_t computePacketLength(ConstPtr<ByteArray> data);
|
||||
|
||||
static const std::uint32_t kMinPacketLength;
|
||||
static const std::uint32_t kMaxDataSize;
|
||||
|
||||
BLEPacket(ConstPtr<ByteArray> service_id_hash, ConstPtr<ByteArray> data);
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > service_id_hash_;
|
||||
ScopedPtr<ConstPtr<ByteArray> > data_;
|
||||
};
|
||||
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
|
||||
#endif // CORE_INTERNAL_MEDIUMS_BLE_PACKET_H_
|
||||
@@ -0,0 +1,108 @@
|
||||
#include "core/internal/mediums/ble_packet.h"
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
const char kServiceIDHash[] = {0x0A, 0x0B, 0x0C};
|
||||
const char kData[] = {0x00, 0x01, 0x02, 0x03, 0x04};
|
||||
|
||||
TEST(BLEPacket, SerializationDeserializationWorks) {
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_hash(MakeConstPtr(
|
||||
new ByteArray(kServiceIDHash, sizeof(kServiceIDHash) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_data(
|
||||
MakeConstPtr(new ByteArray(kData, sizeof(kData) / sizeof(char))));
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_ble_packet_bytes(
|
||||
BLEPacket::toBytes(scoped_service_id_hash.get(), scoped_data.get()));
|
||||
ScopedPtr<ConstPtr<BLEPacket> > scoped_ble_packet(
|
||||
BLEPacket::fromBytes(scoped_ble_packet_bytes.get()));
|
||||
|
||||
ASSERT_EQ(0, memcmp(kServiceIDHash,
|
||||
scoped_ble_packet->getServiceIdHash()->getData(),
|
||||
scoped_ble_packet->getServiceIdHash()->size()));
|
||||
ASSERT_EQ(0, memcmp(kData, scoped_ble_packet->getData()->getData(),
|
||||
scoped_ble_packet->getData()->size()));
|
||||
}
|
||||
|
||||
TEST(BLEPacket, SerializationDeserializationWorksWithEmptyData) {
|
||||
char empty_data[] = {};
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_hash(MakeConstPtr(
|
||||
new ByteArray(kServiceIDHash, sizeof(kServiceIDHash) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_data(MakeConstPtr(
|
||||
new ByteArray(empty_data, sizeof(empty_data) / sizeof(char))));
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_ble_packet_bytes(
|
||||
BLEPacket::toBytes(scoped_service_id_hash.get(), scoped_data.get()));
|
||||
ScopedPtr<ConstPtr<BLEPacket> > scoped_ble_packet(
|
||||
BLEPacket::fromBytes(scoped_ble_packet_bytes.get()));
|
||||
|
||||
ASSERT_EQ(0, memcmp(kServiceIDHash,
|
||||
scoped_ble_packet->getServiceIdHash()->getData(),
|
||||
scoped_ble_packet->getServiceIdHash()->size()));
|
||||
ASSERT_EQ(0, memcmp(empty_data, scoped_ble_packet->getData()->getData(),
|
||||
scoped_ble_packet->getData()->size()));
|
||||
}
|
||||
|
||||
TEST(BLEPacket, SerializationFailsWithShortServiceIdHash) {
|
||||
char short_service_id_hash[] = {0x0A, 0x0B};
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_hash(MakeConstPtr(
|
||||
new ByteArray(short_service_id_hash,
|
||||
sizeof(short_service_id_hash) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_data(
|
||||
MakeConstPtr(new ByteArray(kData, sizeof(kData) / sizeof(char))));
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_ble_packet_bytes(
|
||||
BLEPacket::toBytes(scoped_service_id_hash.get(), scoped_data.get()));
|
||||
|
||||
ASSERT_TRUE(scoped_ble_packet_bytes.isNull());
|
||||
}
|
||||
|
||||
TEST(BLEPacket, SerializationFailsWithLongServiceIdHash) {
|
||||
char long_service_id_hash[]{0x0A, 0x0B, 0x0C, 0x0D};
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_hash(
|
||||
MakeConstPtr(new ByteArray(long_service_id_hash,
|
||||
sizeof(long_service_id_hash) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_data(
|
||||
MakeConstPtr(new ByteArray(kData, sizeof(kData) / sizeof(char))));
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_ble_packet_bytes(
|
||||
BLEPacket::toBytes(scoped_service_id_hash.get(), scoped_data.get()));
|
||||
|
||||
ASSERT_TRUE(scoped_ble_packet_bytes.isNull());
|
||||
}
|
||||
|
||||
TEST(BLEPacket, DeserializationFailsWithNullBytes) {
|
||||
ScopedPtr<ConstPtr<BLEPacket> > scoped_ble_packet(
|
||||
BLEPacket::fromBytes(ConstPtr<ByteArray>()));
|
||||
|
||||
ASSERT_TRUE(scoped_ble_packet.isNull());
|
||||
}
|
||||
|
||||
TEST(BLEPacket, DeserializationFailsWithShortLength) {
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_service_id_hash(MakeConstPtr(
|
||||
new ByteArray(kServiceIDHash, sizeof(kServiceIDHash) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_data(
|
||||
MakeConstPtr(new ByteArray(kData, sizeof(kData) / sizeof(char))));
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_ble_packet_bytes(
|
||||
BLEPacket::toBytes(scoped_service_id_hash.get(), scoped_data.get()));
|
||||
|
||||
// Cut off the packet so that it's too short
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_short_ble_packet_bytes(
|
||||
MakeConstPtr(new ByteArray(scoped_ble_packet_bytes->getData(), 2)));
|
||||
ScopedPtr<ConstPtr<BLEPacket> > scoped_ble_packet(
|
||||
BLEPacket::fromBytes(scoped_short_ble_packet_bytes.get()));
|
||||
|
||||
ASSERT_TRUE(scoped_ble_packet.isNull());
|
||||
}
|
||||
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
@@ -0,0 +1,19 @@
|
||||
#include "core/internal/mediums/ble_peripheral.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
BLEPeripheral::BLEPeripheral(ConstPtr<ByteArray> id) : id_(id) {}
|
||||
|
||||
BLEPeripheral::~BLEPeripheral() {
|
||||
// Nothing to do.
|
||||
}
|
||||
|
||||
ConstPtr<ByteArray> BLEPeripheral::getId() const { return id_.get(); }
|
||||
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
@@ -0,0 +1,30 @@
|
||||
#ifndef CORE_INTERNAL_MEDIUMS_BLE_PERIPHERAL_H_
|
||||
#define CORE_INTERNAL_MEDIUMS_BLE_PERIPHERAL_H_
|
||||
|
||||
#include "platform/byte_array.h"
|
||||
#include "platform/ptr.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
class BLEPeripheral {
|
||||
public:
|
||||
explicit BLEPeripheral(ConstPtr<ByteArray> id);
|
||||
~BLEPeripheral();
|
||||
|
||||
ConstPtr<ByteArray> getId() const;
|
||||
|
||||
private:
|
||||
// A unique identifier for this peripheral. It can be the BLE advertisement it
|
||||
// was found on, or even simply the BLE MAC address.
|
||||
ScopedPtr<ConstPtr<ByteArray>> id_;
|
||||
};
|
||||
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
|
||||
#endif // CORE_INTERNAL_MEDIUMS_BLE_PERIPHERAL_H_
|
||||
@@ -0,0 +1,831 @@
|
||||
#include "core/internal/mediums/ble.h"
|
||||
#include "core/internal/mediums/ble_advertisement_header.h"
|
||||
#include "core/internal/mediums/bloom_filter.h"
|
||||
#include "core/internal/mediums/utils.h"
|
||||
#include "core/internal/mediums/uuid.h"
|
||||
#include "platform/synchronized.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
namespace ble_v2 {
|
||||
|
||||
template <typename Platform>
|
||||
class ProcessOnLostRunnable : public Runnable {
|
||||
public:
|
||||
explicit ProcessOnLostRunnable(Ptr<BLEV2<Platform>> ble_v2)
|
||||
: ble_v2_(ble_v2) {}
|
||||
|
||||
void run() override { ble_v2_->processOnLostTimeout(); }
|
||||
|
||||
private:
|
||||
Ptr<BLEV2<Platform>> ble_v2_;
|
||||
};
|
||||
|
||||
template <typename Platform>
|
||||
class OnAdvertisementFoundRunnable : public Runnable {
|
||||
public:
|
||||
OnAdvertisementFoundRunnable(
|
||||
Ptr<BLEV2<Platform>> ble_v2, Ptr<BLEPeripheralV2> peripheral,
|
||||
ConstPtr<BLEAdvertisementData> advertisement_data)
|
||||
: ble_v2_(ble_v2),
|
||||
peripheral_(peripheral),
|
||||
advertisement_data_(advertisement_data) {}
|
||||
|
||||
// This method is synchronized because it affects class state, but is called
|
||||
// from a separate thread that fires whenever a BLE advertisement is seen.
|
||||
void run() override {
|
||||
Synchronized s(ble_v2_->lock_.get());
|
||||
|
||||
ble_v2_->discovered_peripheral_tracker_->processFoundBleAdvertisement(
|
||||
peripheral_, advertisement_data_.release(),
|
||||
MakePtr(new typename BLEV2<Platform>::GATTAdvertisementFetcherFacade(
|
||||
ble_v2_)));
|
||||
}
|
||||
|
||||
private:
|
||||
Ptr<BLEV2<Platform>> ble_v2_;
|
||||
Ptr<BLEPeripheralV2> peripheral_;
|
||||
ScopedPtr<ConstPtr<BLEAdvertisementData>> advertisement_data_;
|
||||
};
|
||||
|
||||
} // namespace ble_v2
|
||||
|
||||
template <typename Platform>
|
||||
const std::int32_t BLEV2<Platform>::kNumAdvertisementSlots = 2;
|
||||
|
||||
template <typename Platform>
|
||||
const std::int32_t BLEV2<Platform>::kMaxAdvertisementLength = 512;
|
||||
|
||||
template <typename Platform>
|
||||
const std::int32_t BLEV2<Platform>::kDummyServiceIdLength = 512;
|
||||
|
||||
template <typename Platform>
|
||||
const char* BLEV2<Platform>::kCopresenceServiceUuid =
|
||||
"0000FEF3-0000-1000-8000-00805F9B34FB";
|
||||
|
||||
template <typename Platform>
|
||||
const std::int64_t BLEV2<Platform>::kOnLostTimeoutMillis = 15000;
|
||||
|
||||
template <typename Platform>
|
||||
const std::int64_t BLEV2<Platform>::kGattAdvertisementOperationTimeoutMillis =
|
||||
5000;
|
||||
|
||||
template <typename Platform>
|
||||
const std::int64_t
|
||||
BLEV2<Platform>::kMinConnectionAttemptRecoveryDurationMillis = 1000;
|
||||
|
||||
template <typename Platform>
|
||||
const std::int32_t
|
||||
BLEV2<Platform>::kMaxConnectionAttemptRecoveryFuzzDurationMillis = 10000;
|
||||
|
||||
template <typename Platform>
|
||||
const std::uint32_t BLEV2<Platform>::kDefaultMtu = 512;
|
||||
|
||||
// These two values make up the base UUID we use when advertising a slot. The
|
||||
// base is an all zero Version-3 name-based UUID. To turn this into an
|
||||
// advertisement slot UUID, we simply OR the least significant bits with the
|
||||
// slot number.
|
||||
//
|
||||
// More info about the format can be found here:
|
||||
// https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based)
|
||||
template <typename Platform>
|
||||
const std::int64_t BLEV2<Platform>::kAdvertisementUuidMsb = 0x0000000000003000;
|
||||
|
||||
template <typename Platform>
|
||||
const std::int64_t BLEV2<Platform>::kAdvertisementUuidLsb = 0x8000000000000000;
|
||||
|
||||
template <typename Platform>
|
||||
BLEV2<Platform>::BLEV2(Ptr<BluetoothRadio<Platform>> bluetooth_radio)
|
||||
: lock_(Platform::createLock()),
|
||||
platform_thread_offloader_(Platform::createSingleThreadExecutor()),
|
||||
prng_(MakePtr(new Prng())),
|
||||
hash_utils_(Platform::createHashUtils()),
|
||||
bluetooth_radio_(bluetooth_radio),
|
||||
bluetooth_adapter_(Platform::createBluetoothAdapter()),
|
||||
ble_medium_(Platform::createBLEMediumV2()),
|
||||
scanning_info_(),
|
||||
discovered_peripheral_tracker_(
|
||||
new DiscoveredPeripheralTracker<Platform>()),
|
||||
on_lost_executor_(Platform::createScheduledExecutor()),
|
||||
advertising_info_(),
|
||||
gatt_server_info_(),
|
||||
accepting_connections_info_() {}
|
||||
|
||||
template <typename Platform>
|
||||
BLEV2<Platform>::~BLEV2() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
on_lost_executor_->shutdown();
|
||||
platform_thread_offloader_->shutdown();
|
||||
stopAdvertising();
|
||||
stopAdvertisementGattServer();
|
||||
stopAcceptingConnections();
|
||||
stopScanning();
|
||||
// discovered_peripheral_tracker is a ScopedPtr member and will take care of
|
||||
// itself.
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BLEV2<Platform>::isAvailable() {
|
||||
// This is purposefully left un-synchronized like its java counterpart.
|
||||
// Callers should be able to query this without waiting for other operations
|
||||
// to complete first and this should be safe to call after shutdown. We would
|
||||
// have made it static, but it relies on variables from the constructor (like
|
||||
// ble_medium_ and bluetooth_adapter_).
|
||||
return !ble_medium_.isNull() && !bluetooth_adapter_.isNull();
|
||||
}
|
||||
|
||||
// Returns true if currently scanning for BLE advertisements.
|
||||
template <typename Platform>
|
||||
bool BLEV2<Platform>::isAdvertising() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
return !advertising_info_.isNull();
|
||||
}
|
||||
|
||||
// Starts BLE advertising, delivering additional information through a GATT
|
||||
// server.
|
||||
template <typename Platform>
|
||||
bool BLEV2<Platform>::startAdvertising(
|
||||
const string& service_id, ConstPtr<ByteArray> advertisement_bytes,
|
||||
BLEMediumV2::PowerMode::Value power_mode,
|
||||
const string& fast_advertisement_service_uuid) {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
// Avoid leaks.
|
||||
ScopedPtr<ConstPtr<ByteArray>> scoped_advertisement_bytes(
|
||||
advertisement_bytes);
|
||||
|
||||
if (service_id.empty() || scoped_advertisement_bytes.isNull()) {
|
||||
// logger.atSevere().log("Refusing to start BLE advertising because a null
|
||||
// parameter was passed in.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (scoped_advertisement_bytes->size() > kMaxAdvertisementLength) {
|
||||
// logger.atSevere().log("Refusing to start BLE advertising because the
|
||||
// advertisement was too long. Expected at most %d bytes but received %d.",
|
||||
// kMaxAdvertisementLength, scoped_advertisement_bytes->size());
|
||||
return false;
|
||||
}
|
||||
|
||||
// Note: We don't include logic checking/using the fast_pair_model_id because
|
||||
// that is a java-only concept for now.
|
||||
|
||||
if (isAdvertising()) {
|
||||
// logger.atSevere().log("Failed to BLE advertise because we're already
|
||||
// advertising.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!bluetooth_radio_->isEnabled()) {
|
||||
// logger.atSevere().log("Can't start BLE advertising because Bluetooth
|
||||
// isn't enabled.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isAvailable()) {
|
||||
// logger.atSevere().log("Can't start BLE advertising because BLE is not
|
||||
// available.");
|
||||
return false;
|
||||
}
|
||||
|
||||
// TODO(ahlee): Remove this check here and in the java code (redundant)
|
||||
// Stop any existing advertisement GATT servers. We don't stop it in
|
||||
// stopAdvertising() to avoid GATT issues with BLE sockets.
|
||||
if (isAdvertisementGattServerRunning()) {
|
||||
stopAdvertisementGattServer();
|
||||
}
|
||||
|
||||
// Start a GATT server to deliver the full advertisement data. If we fail to
|
||||
// advertise the header, we must shut this down before the method returns.
|
||||
bool is_fast_advertisement = !fast_advertisement_service_uuid.empty();
|
||||
if (!is_fast_advertisement) {
|
||||
if (!startAdvertisementGattServer(service_id,
|
||||
scoped_advertisement_bytes.get())) {
|
||||
// logger.atSevere().log("Failed to to BLE advertise because the
|
||||
// advertisement GATT server failed to start");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray>> advertisement_header_bytes(
|
||||
createAdvertisementHeader(service_id, scoped_advertisement_bytes.get(),
|
||||
is_fast_advertisement));
|
||||
if (advertisement_header_bytes.isNull()) {
|
||||
// logger.atSevere().log("Failed to to BLE advertise because we could not
|
||||
// create an advertisement header");
|
||||
// We failed to start BLE advertising, so stop the advertisement GATT
|
||||
// server.
|
||||
stopAdvertisementGattServer();
|
||||
return false;
|
||||
}
|
||||
|
||||
ScopedPtr<Ptr<BLEAdvertisementData>> advertisement(
|
||||
new BLEAdvertisementData());
|
||||
advertisement->is_connectable = true;
|
||||
advertisement->tx_power_level =
|
||||
BLEAdvertisementData::UNSPECIFIED_TX_POWER_LEVEL;
|
||||
|
||||
ScopedPtr<Ptr<BLEAdvertisementData>> scan_response(
|
||||
new BLEAdvertisementData());
|
||||
scan_response->is_connectable = true;
|
||||
scan_response->tx_power_level =
|
||||
BLEAdvertisementData::UNSPECIFIED_TX_POWER_LEVEL;
|
||||
scan_response->service_uuids.insert(kCopresenceServiceUuid);
|
||||
scan_response->service_data.insert(std::make_pair(
|
||||
kCopresenceServiceUuid, advertisement_header_bytes.release()));
|
||||
|
||||
// Note: We don't use fast pair data because that is java-only for now.
|
||||
|
||||
// TODO(ahlee): Fix this if check in the java code.
|
||||
if (is_fast_advertisement) {
|
||||
ScopedPtr<ConstPtr<ByteArray>> service_id_hash(
|
||||
generateServiceIdHash(BLEAdvertisement::Version::V2, service_id));
|
||||
ScopedPtr<ConstPtr<ByteArray>> fast_advertisement_bytes(
|
||||
BLEAdvertisement::toBytes(
|
||||
BLEAdvertisement::Version::V2, BLEAdvertisement::SocketVersion::V2,
|
||||
service_id_hash.get(), scoped_advertisement_bytes.get()));
|
||||
if (fast_advertisement_bytes.isNull()) {
|
||||
// logger.atSevere().log("Failed to BLE advertise because we could not
|
||||
// create a fast advertisement for service UUID %s.",
|
||||
// fast_advertisement_service_uuid);
|
||||
|
||||
// We shouldn't have started an advertisement GATT server in the first
|
||||
// place if we are using fast advertisements. However, to avoid careless
|
||||
// leaks, try shutting down the server anyway.
|
||||
stopAdvertisementGattServer();
|
||||
return false;
|
||||
}
|
||||
advertisement->service_data.insert(std::make_pair(
|
||||
fast_advertisement_service_uuid, fast_advertisement_bytes.release()));
|
||||
scan_response->service_uuids.insert(fast_advertisement_service_uuid);
|
||||
}
|
||||
|
||||
if (!ble_medium_->startAdvertising(ConstifyPtr(advertisement.release()),
|
||||
ConstifyPtr(scan_response.release()),
|
||||
power_mode)) {
|
||||
// If BLE advertising was not successful, stop the advertisement GATT
|
||||
// server.
|
||||
stopAdvertisementGattServer();
|
||||
return false;
|
||||
}
|
||||
|
||||
// logger.atVerbose().flog("Started BLE advertising with advertisement %s for
|
||||
// serviceID %s.", advertisement_header, service_id);
|
||||
advertising_info_ = MakePtr(new AdvertisingInfo(service_id));
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
ConstPtr<ByteArray> BLEV2<Platform>::createAdvertisementHeader(
|
||||
const string& service_id, ConstPtr<ByteArray> advertisement_bytes,
|
||||
bool is_fast_advertisement) {
|
||||
// Create a randomized dummy service ID to anonymize our header with.
|
||||
string dummy_service_id;
|
||||
dummy_service_id.reserve(kDummyServiceIdLength);
|
||||
for (int i = 0; i < kDummyServiceIdLength; i++) {
|
||||
dummy_service_id[i] = static_cast<char>(prng_->nextInt32() & 0x000000FF);
|
||||
}
|
||||
|
||||
// Put the service ID along with the dummy service ID into our bloom filter
|
||||
// Note: BloomFilter length should always match
|
||||
// BLEAdvertisementHeader::kServiceIdBloomFilterLength
|
||||
ScopedPtr<Ptr<BloomFilter<10>>> bloom_filter(new BloomFilter<10>());
|
||||
bloom_filter->add(dummy_service_id);
|
||||
|
||||
// Only add the service ID to our bloom filter if it's not a fast
|
||||
// advertisement. Fast advertisements want discoverers to avoid reading our
|
||||
// GATT advertisement.
|
||||
if (!is_fast_advertisement) {
|
||||
bloom_filter->add(service_id);
|
||||
}
|
||||
|
||||
// Create a hash seeded from dummy_service_id + advertisementBytes
|
||||
//
|
||||
// First, populate advertisement_bodies with the dummy_service_id and
|
||||
// advertisement_bytes.
|
||||
string advertisement_bodies;
|
||||
advertisement_bodies.reserve(dummy_service_id.size() +
|
||||
advertisement_bytes->size());
|
||||
advertisement_bodies.append(dummy_service_id.data(), dummy_service_id.size());
|
||||
advertisement_bodies.append(advertisement_bytes->getData(),
|
||||
advertisement_bytes->size());
|
||||
|
||||
// Then, generate the advertisement hash from the populated
|
||||
// advertisement_bodies string.
|
||||
ScopedPtr<ConstPtr<ByteArray>> advertisement_bodies_byte_array(MakeConstPtr(
|
||||
new ByteArray(advertisement_bodies.data(), advertisement_bodies.size())));
|
||||
ScopedPtr<ConstPtr<ByteArray>> advertisement_hash(
|
||||
generateAdvertisementHash(advertisement_bodies_byte_array.get()));
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray>> bloom_filter_bytes(bloom_filter->asBytes());
|
||||
string ble_advertisement_header_string = BLEAdvertisementHeader::asString(
|
||||
BLEAdvertisementHeader::Version::V2, kNumAdvertisementSlots,
|
||||
bloom_filter_bytes.get(), advertisement_hash.get());
|
||||
|
||||
return MakeConstPtr(new ByteArray(ble_advertisement_header_string.data(),
|
||||
ble_advertisement_header_string.size()));
|
||||
}
|
||||
|
||||
// Stops BLE advertising.
|
||||
template <typename Platform>
|
||||
void BLEV2<Platform>::stopAdvertising() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
if (!isAdvertising()) {
|
||||
// logger.atDebug().log("Can't turn off BLE advertising because it never
|
||||
// started.");
|
||||
return;
|
||||
}
|
||||
|
||||
ble_medium_->stopAdvertising();
|
||||
// Reset advertising_info_to mark that we're no longer advertising.
|
||||
advertising_info_.destroy();
|
||||
|
||||
// Do NOT stop the advertisement GATT server here. Doing so will cause any
|
||||
// other existing GATT connections to stop receiving callbacks. This affects
|
||||
// our BLE sockets. Therefore, we only stop it in shutdown() and
|
||||
// startAdvertising(), where it is safe to do so. At those two points, we
|
||||
// shouldn't expect any BLE sockets to be connected.
|
||||
|
||||
// logger.atVerbose().log("Turned BLE advertising off");
|
||||
}
|
||||
|
||||
// Returns true if currently scanning for BLE advertisements.
|
||||
template <typename Platform>
|
||||
bool BLEV2<Platform>::isScanning() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
return !scanning_info_.isNull();
|
||||
}
|
||||
|
||||
// Starts scanning for BLE advertisements (if it is possible for the device).
|
||||
template <typename Platform>
|
||||
bool BLEV2<Platform>::startScanning(
|
||||
const string& service_id,
|
||||
Ptr<DiscoveredPeripheralCallback> discovered_peripheral_callback,
|
||||
BLEMediumV2::PowerMode::Value power_mode,
|
||||
const string& fast_advertisement_service_uuid) {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
// Avoid leaks.
|
||||
ScopedPtr<Ptr<DiscoveredPeripheralCallback>>
|
||||
scoped_discovered_peripheral_callback(discovered_peripheral_callback);
|
||||
|
||||
if (service_id.empty() || scoped_discovered_peripheral_callback.isNull()) {
|
||||
// logger.atSevere().log("Refusing to start BLE scanning because at least
|
||||
// one of workSource, serviceId, or discoveredPeripheralCallback is null.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isScanning()) {
|
||||
// logger.atSevere().log("Refusing to start BLE scanning because we are
|
||||
// already scanning.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!bluetooth_radio_->isEnabled()) {
|
||||
// logger.atSevere().log("Can't start BLE scanning because Bluetooth was
|
||||
// never turned on");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isAvailable()) {
|
||||
// logger.atSevere().log("Can't start BLE scanning because BLE is not
|
||||
// available.");
|
||||
return false;
|
||||
}
|
||||
|
||||
discovered_peripheral_tracker_->startTracking(
|
||||
service_id, scoped_discovered_peripheral_callback.release(),
|
||||
fast_advertisement_service_uuid);
|
||||
// Avoid leaks.
|
||||
ScopedPtr<Ptr<ScanCallbackFacade>> scan_callback_facade(
|
||||
new ScanCallbackFacade(MakePtr(this)));
|
||||
std::set<string> service_uuids;
|
||||
service_uuids.insert(kCopresenceServiceUuid);
|
||||
if (!ble_medium_->startScanning(service_uuids, power_mode,
|
||||
scan_callback_facade.get())) {
|
||||
discovered_peripheral_tracker_->stopTracking(service_id);
|
||||
return false;
|
||||
}
|
||||
|
||||
// logger.atVerbose().log("Started BLE scanning for serviceID %s.",
|
||||
// service_id);
|
||||
scanning_info_ = MakePtr(new ScanningInfo(
|
||||
service_id, scan_callback_facade.release(), createOnLostAlarm()));
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
void BLEV2<Platform>::onAdvertisementFoundImpl(
|
||||
Ptr<BLEPeripheralV2> ble_peripheral,
|
||||
ConstPtr<BLEAdvertisementData> advertisement_data) {
|
||||
offloadFromPlatformThread(
|
||||
MakePtr(new ble_v2::OnAdvertisementFoundRunnable<Platform>(
|
||||
MakePtr(this), ble_peripheral, advertisement_data)));
|
||||
}
|
||||
|
||||
// This method is synchronized because it affects class state, but is called
|
||||
// from a separate thread that has a recurring alarm running on it.
|
||||
template <typename Platform>
|
||||
void BLEV2<Platform>::processOnLostTimeout() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
discovered_peripheral_tracker_->processLostGattAdvertisements();
|
||||
}
|
||||
|
||||
// Stops scanning for BLE advertisements.
|
||||
template <typename Platform>
|
||||
void BLEV2<Platform>::stopScanning() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
if (!isScanning()) {
|
||||
// logger.atDebug().log("Can't turn off BLE scanning because we never
|
||||
// started scanning.");
|
||||
return;
|
||||
}
|
||||
|
||||
scanning_info_->on_lost_alarm->cancel();
|
||||
|
||||
ble_medium_->stopScanning();
|
||||
discovered_peripheral_tracker_->stopTracking(scanning_info_->service_id);
|
||||
// Reset our bundle of scanning state to mark that we're no longer scanning.
|
||||
scanning_info_.destroy();
|
||||
}
|
||||
|
||||
// TODO(b/112199086) Change to RecurringCancelableAlarm
|
||||
template <typename Platform>
|
||||
Ptr<CancelableAlarm<Platform>> BLEV2<Platform>::createOnLostAlarm() {
|
||||
// return MakePtr(new CancelableAlarm<Platform>(
|
||||
// "BluetoothLowEnergy.startScanning() onLost",
|
||||
// MakePtr(new
|
||||
// ble_v2::ProcessOnLostRunnable<Platform>(MakePtr(this))),
|
||||
// kOnLostTimeoutMillis, on_lost_executor_.get()));
|
||||
return Ptr<CancelableAlarm<Platform>>();
|
||||
}
|
||||
|
||||
// Returns true if the device is currently accepting incoming BLE socket
|
||||
// connections.
|
||||
template <typename Platform>
|
||||
bool BLEV2<Platform>::isAcceptingConnections() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
return !accepting_connections_info_.isNull();
|
||||
}
|
||||
|
||||
// Starts accepting incoming BLE socket connections.
|
||||
template <typename Platform>
|
||||
bool BLEV2<Platform>::startAcceptingConnections(
|
||||
const string& service_id,
|
||||
Ptr<AcceptedConnectionCallback> accepted_connection_callback) {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
// Avoid leaks.
|
||||
ScopedPtr<Ptr<AcceptedConnectionCallback>>
|
||||
scoped_accepted_connection_callback(accepted_connection_callback);
|
||||
if (service_id.empty() || scoped_accepted_connection_callback.isNull()) {
|
||||
// logger.atSevere().log("Refusing to start accepting BLE connections
|
||||
// because at least one of serviceId or acceptedConnectionCallback is
|
||||
// null.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isAcceptingConnections()) {
|
||||
// logger.atSevere().log("Refusing to start accepting BLE connections for %s
|
||||
// because another BLE server socket is already in-progress.", service_id);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!bluetooth_radio_->isEnabled()) {
|
||||
// logger.atSevere().log("Can't start accepting BLE connections for %s
|
||||
// because Bluetooth isn't enabled.", service_id);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isAvailable()) {
|
||||
// logger.atSevere().log("Can't start accepting BLE connections for %s
|
||||
// because BLE is not available.", service_id);
|
||||
return false;
|
||||
}
|
||||
|
||||
// TODO(ahlee): Implement w/ the rest of the connecting logic.
|
||||
// Default to returning true and creating accepting_connections_info_ so we
|
||||
// can test the advertising and discovery flow fully.
|
||||
accepting_connections_info_ =
|
||||
MakePtr(new AcceptingConnectionsInfo(service_id));
|
||||
return true;
|
||||
}
|
||||
|
||||
// Stops accepting incoming BLE socket connections.
|
||||
template <typename Platform>
|
||||
void BLEV2<Platform>::stopAcceptingConnections() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
if (!isAcceptingConnections()) {
|
||||
// logger.atDebug().log("Can't stop accepting BLE connections because it was
|
||||
// never started.");
|
||||
return;
|
||||
}
|
||||
|
||||
ble_medium_->stopListeningForIncomingBLESockets();
|
||||
|
||||
// Reset our bundle of accepting connections state to mark that we're no
|
||||
// longer accepting connections.
|
||||
accepting_connections_info_.destroy();
|
||||
}
|
||||
|
||||
// Note: getGattConnectionBackoffPeriodMillis is only used in the java version
|
||||
// of reliablyConnect() for now.
|
||||
|
||||
// Returns true if the advertisement GATT server is currently running.
|
||||
template <typename Platform>
|
||||
bool BLEV2<Platform>::isAdvertisementGattServerRunning() {
|
||||
return !gatt_server_info_.isNull();
|
||||
}
|
||||
|
||||
// Starts a GATT server to deliver additional advertisement data. Returns true
|
||||
// if the server was started successfully.
|
||||
template <typename Platform>
|
||||
bool BLEV2<Platform>::startAdvertisementGattServer(
|
||||
const string& service_id, ConstPtr<ByteArray> advertisement) {
|
||||
// advertisement is not being wrapped in a ScopedPtr because ownership is not
|
||||
// passed on from startAdvertising().
|
||||
|
||||
if (isAdvertisementGattServerRunning()) {
|
||||
// logger.atSevere().log("Refusing to start an advertisement GATT server
|
||||
// because one is already running.");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Create a BleAdvertisement to wrap over the passed in advertisement.
|
||||
ScopedPtr<ConstPtr<ByteArray>> legacy_service_id_hash(
|
||||
generateServiceIdHash(BLEAdvertisement::Version::V1, service_id));
|
||||
ScopedPtr<ConstPtr<ByteArray>> legacy_ble_advertisement_bytes(
|
||||
BLEAdvertisement::toBytes(BLEAdvertisement::Version::V1,
|
||||
BLEAdvertisement::SocketVersion::V1,
|
||||
legacy_service_id_hash.get(), advertisement));
|
||||
if (legacy_ble_advertisement_bytes.isNull()) {
|
||||
// logger.atSevere().log("Refusing to start an advertisement GATT server
|
||||
// because creating a legacy BleAdvertisement with service ID %s failed.",
|
||||
// service_id);
|
||||
return false;
|
||||
}
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray>> service_id_hash(
|
||||
generateServiceIdHash(BLEAdvertisement::Version::V2, service_id));
|
||||
ScopedPtr<ConstPtr<ByteArray>> ble_advertisement_bytes(
|
||||
BLEAdvertisement::toBytes(BLEAdvertisement::Version::V2,
|
||||
BLEAdvertisement::SocketVersion::V2,
|
||||
service_id_hash.get(), advertisement));
|
||||
if (ble_advertisement_bytes.isNull()) {
|
||||
// logger.atSevere().log("Refusing to start an advertisement GATT server
|
||||
// because creating a BleAdvertisement with service ID %s failed.",
|
||||
// service_id);
|
||||
return false;
|
||||
}
|
||||
|
||||
return internalStartAdvertisementGattServer(
|
||||
legacy_ble_advertisement_bytes.release(),
|
||||
ble_advertisement_bytes.release());
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BLEV2<Platform>::internalStartAdvertisementGattServer(
|
||||
ConstPtr<ByteArray> legacy_ble_advertisement_bytes,
|
||||
ConstPtr<ByteArray> ble_advertisement_bytes) {
|
||||
// Avoid leaks.
|
||||
ScopedPtr<ConstPtr<ByteArray>> scoped_legacy_ble_advertisement_bytes(
|
||||
legacy_ble_advertisement_bytes);
|
||||
ScopedPtr<ConstPtr<ByteArray>> scoped_ble_advertisement_bytes(
|
||||
ble_advertisement_bytes);
|
||||
|
||||
ScopedPtr<Ptr<ServerGATTConnectionLifecycleCallbackFacade>>
|
||||
connection_lifecycle_callback(
|
||||
new ServerGATTConnectionLifecycleCallbackFacade(MakePtr(this)));
|
||||
ScopedPtr<Ptr<GATTServer>> gatt_server(
|
||||
ble_medium_->startGATTServer(connection_lifecycle_callback.get()));
|
||||
if (gatt_server.isNull()) {
|
||||
// logger.atSevere().withCause(e).log("Unable to start an advertisement GATT
|
||||
// server.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!generateAdvertisementCharacteristic(
|
||||
/* slot= */ 0, scoped_legacy_ble_advertisement_bytes.release(),
|
||||
gatt_server.get())) {
|
||||
gatt_server->stop();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!generateAdvertisementCharacteristic(
|
||||
/* slot= */ 1, scoped_ble_advertisement_bytes.release(),
|
||||
gatt_server.get())) {
|
||||
gatt_server->stop();
|
||||
return false;
|
||||
}
|
||||
|
||||
// GattCharacteristic is not included in GATTServerInfo because we don't need
|
||||
// it after it's been updated.
|
||||
gatt_server_info_ = MakePtr(new GATTServerInfo(
|
||||
gatt_server.release(), connection_lifecycle_callback.release()));
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BLEV2<Platform>::generateAdvertisementCharacteristic(
|
||||
std::int32_t slot, ConstPtr<ByteArray> advertisement,
|
||||
Ptr<GATTServer> gatt_server) {
|
||||
// Avoid leaks.
|
||||
ScopedPtr<ConstPtr<ByteArray>> scoped_advertisement(advertisement);
|
||||
|
||||
std::set<GATTCharacteristic::Permission::Value> permissions;
|
||||
permissions.insert(GATTCharacteristic::Permission::READ);
|
||||
std::set<GATTCharacteristic::Property::Value> properties;
|
||||
properties.insert(GATTCharacteristic::Property::READ);
|
||||
Ptr<GATTCharacteristic> gatt_characteristic(gatt_server->createCharacteristic(
|
||||
kCopresenceServiceUuid, generateAdvertisementUuid(slot), permissions,
|
||||
properties));
|
||||
|
||||
if (gatt_characteristic.isNull()) {
|
||||
// logger.atSevere().withCause(e).log("Unable to create and add a
|
||||
// characterstic to the gatt server for the advertisement.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!gatt_server->updateCharacteristic(gatt_characteristic,
|
||||
scoped_advertisement.release())) {
|
||||
// logger.atSevere().withCause(e).log("Unable to write a value to the GATT
|
||||
// characteristic.");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Note: In the java counterpart this in a utils class.
|
||||
// Generates a characteristic UUID for an advertisement at the given slot.
|
||||
template <typename Platform>
|
||||
string BLEV2<Platform>::generateAdvertisementUuid(std::int32_t slot) {
|
||||
return UUID<Platform>(kAdvertisementUuidMsb, kAdvertisementUuidLsb | slot)
|
||||
.str();
|
||||
}
|
||||
|
||||
// Stops a GATT server used for additional advertisement data.
|
||||
template <typename Platform>
|
||||
void BLEV2<Platform>::stopAdvertisementGattServer() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
if (!isAdvertisementGattServerRunning()) {
|
||||
// logger.atSevere().log("Unable to stop the advertisement GATT server
|
||||
// because it's not running.");
|
||||
return;
|
||||
}
|
||||
|
||||
gatt_server_info_->gatt_server->stop();
|
||||
gatt_server_info_.destroy();
|
||||
}
|
||||
|
||||
// Connects to a GATT server, reads advertisement data, and then disconnects
|
||||
// from the GATT server. This method blocks until all advertisements are read,
|
||||
// or a connection error occurs.
|
||||
template <typename Platform>
|
||||
Ptr<AdvertisementReadResult<Platform>>
|
||||
BLEV2<Platform>::processFetchGattAdvertisementsRequest(
|
||||
Ptr<BLEPeripheralV2> peripheral, std::int32_t num_slots,
|
||||
Ptr<AdvertisementReadResult<Platform>> advertisement_read_result) {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
if (advertisement_read_result.isNull()) {
|
||||
advertisement_read_result =
|
||||
MakeRefCountedPtr(new AdvertisementReadResult<Platform>());
|
||||
}
|
||||
|
||||
if (peripheral.isNull()) {
|
||||
// logger.atSevere().log("Can't read from an advertisement GATT server
|
||||
// because ble peripheral is null.");
|
||||
return advertisement_read_result;
|
||||
}
|
||||
|
||||
if (!bluetooth_radio_->isEnabled()) {
|
||||
// logger.atSevere().log("Can't read from an advertisement GATT server
|
||||
// because Bluetooth was never turned on.");
|
||||
return advertisement_read_result;
|
||||
}
|
||||
|
||||
if (!isAvailable()) {
|
||||
// logger.atSevere().log("Can't read from an advertisement GATT server
|
||||
// because BLE is not available.");
|
||||
return advertisement_read_result;
|
||||
}
|
||||
|
||||
return internalReadFromAdvertisementGattServer(peripheral, num_slots,
|
||||
advertisement_read_result);
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
Ptr<AdvertisementReadResult<Platform>>
|
||||
BLEV2<Platform>::internalReadFromAdvertisementGattServer(
|
||||
Ptr<BLEPeripheralV2> peripheral, std::int32_t num_slots,
|
||||
Ptr<AdvertisementReadResult<Platform>> advertisement_read_result) {
|
||||
// Attempt to connect and read some GATT characteristics.
|
||||
bool read_success = true;
|
||||
|
||||
ScopedPtr<Ptr<ClientGATTConnectionLifecycleCallbackFacade>>
|
||||
connection_lifecycle_callback(
|
||||
new ClientGATTConnectionLifecycleCallbackFacade(MakePtr(this)));
|
||||
ScopedPtr<Ptr<ClientGATTConnection>> gatt_connection(
|
||||
ble_medium_->connectToGATTServer(peripheral, kDefaultMtu,
|
||||
BLEMediumV2::PowerMode::HIGH,
|
||||
connection_lifecycle_callback.get()));
|
||||
if (!gatt_connection.isNull() && gatt_connection->discoverServices()) {
|
||||
// Read all advertisements from all slots that we haven't read from yet.
|
||||
for (std::int32_t slot = 0; slot < num_slots; ++slot) {
|
||||
// Make sure we haven't already read this advertisement before.
|
||||
if (advertisement_read_result->hasAdvertisement(slot)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Make sure the characteristic even exists for this slot number. If the
|
||||
// characteristic doesn't exist, we shouldn't count the fetch as a
|
||||
// failure because there's nothing we could've done about a non-existent
|
||||
// characteristic.
|
||||
Ptr<GATTCharacteristic> gatt_characteristic(
|
||||
gatt_connection->getCharacteristic(kCopresenceServiceUuid,
|
||||
generateAdvertisementUuid(slot)));
|
||||
if (/* !advertisementSlotExists()= */ gatt_characteristic.isNull()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Read advertisement data from the characteristic associated with this
|
||||
// slot.
|
||||
ScopedPtr<ConstPtr<ByteArray>> characteristic_value(
|
||||
gatt_connection->readCharacteristic(gatt_characteristic));
|
||||
if (!characteristic_value.isNull()) {
|
||||
advertisement_read_result->addAdvertisement(
|
||||
slot, characteristic_value.release());
|
||||
// logger.atVerbose().log("Successfully read advertisement at slot %d
|
||||
// on peripheral %s.", slot, peripheral);
|
||||
} else {
|
||||
// logger.atWarning().withCause(characteristicReadException).log("Can't
|
||||
// read advertisement for slot %d on peripheral %s.", slot,
|
||||
// peripheral);
|
||||
read_success = false;
|
||||
}
|
||||
// Whether or not we succeeded with this slot, we should try reading the
|
||||
// other slots to get as many advertisements as possible before
|
||||
// returning a success or failure.
|
||||
}
|
||||
|
||||
gatt_connection->disconnect();
|
||||
} else {
|
||||
// logger.atWarning().withCause(connectException).log("Can't connect to an
|
||||
// advertisement GATT server for peripheral %s.", peripheral);
|
||||
read_success = false;
|
||||
}
|
||||
|
||||
advertisement_read_result->recordLastReadStatus(read_success);
|
||||
return advertisement_read_result;
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
void BLEV2<Platform>::offloadFromPlatformThread(Ptr<Runnable> runnable) {
|
||||
platform_thread_offloader_->execute(runnable);
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
ConstPtr<ByteArray> BLEV2<Platform>::generateAdvertisementHash(
|
||||
ConstPtr<ByteArray> advertisement_bytes) {
|
||||
return Utils::sha256Hash(hash_utils_.get(), advertisement_bytes,
|
||||
BLEAdvertisementHeader::kAdvertisementHashLength);
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
ConstPtr<ByteArray> BLEV2<Platform>::generateServiceIdHash(
|
||||
BLEAdvertisement::Version::Value version, const string& service_id) {
|
||||
ScopedPtr<ConstPtr<ByteArray>> service_id_bytes(
|
||||
MakeConstPtr(new ByteArray(service_id.data(), service_id.size())));
|
||||
switch (version) {
|
||||
case BLEAdvertisement::Version::V1:
|
||||
return Utils::legacySha256HashOnlyForPrinting(
|
||||
hash_utils_.get(), service_id_bytes.get(),
|
||||
BLEAdvertisement::kServiceIdHashLength);
|
||||
case BLEAdvertisement::Version::V2:
|
||||
// Fall through.
|
||||
case BLEAdvertisement::Version::UNKNOWN:
|
||||
// Fall through.
|
||||
default:
|
||||
// Use the latest known hashing scheme.
|
||||
return Utils::sha256Hash(hash_utils_.get(), service_id_bytes.get(),
|
||||
BLEAdvertisement::kServiceIdHashLength);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
@@ -0,0 +1,312 @@
|
||||
#ifndef CORE_INTERNAL_MEDIUMS_BLE_V2_H_
|
||||
#define CORE_INTERNAL_MEDIUMS_BLE_V2_H_
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "core/internal/mediums/advertisement_read_result.h"
|
||||
#include "core/internal/mediums/ble_advertisement.h"
|
||||
#include "core/internal/mediums/bluetooth_radio.h"
|
||||
#include "core/internal/mediums/discovered_peripheral_callback.h"
|
||||
#include "core/internal/mediums/discovered_peripheral_tracker.h"
|
||||
#include "platform/api/ble_v2.h"
|
||||
#include "platform/api/bluetooth_adapter.h"
|
||||
#include "platform/api/hash_utils.h"
|
||||
#include "platform/api/lock.h"
|
||||
#include "platform/byte_array.h"
|
||||
#include "platform/cancelable_alarm.h"
|
||||
#include "platform/port/string.h"
|
||||
#include "platform/prng.h"
|
||||
#include "platform/ptr.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
namespace ble_v2 {
|
||||
|
||||
template <typename>
|
||||
class ProcessOnLostRunnable;
|
||||
|
||||
template <typename>
|
||||
class OnAdvertisementFoundRunnable;
|
||||
|
||||
} // namespace ble_v2
|
||||
|
||||
template <typename Platform>
|
||||
class BLEV2 {
|
||||
public:
|
||||
explicit BLEV2(Ptr<BluetoothRadio<Platform>> bluetooth_radio);
|
||||
~BLEV2();
|
||||
|
||||
bool isAvailable();
|
||||
// While the start* functions for each action (advertising, scanning,
|
||||
// accepting connections) take in a service_id, the stop* and is* functions do
|
||||
// not. This is because the service_id isn't used. In the java code, shutdown
|
||||
// calls all the stop* functions w/ a null service_id. The service_id is just
|
||||
// passed through to the corresponding is* function, which ignores it.
|
||||
// service_id should be added back in when C++ supports multi-client.
|
||||
bool startAdvertising(const string& service_id,
|
||||
ConstPtr<ByteArray> advertisement,
|
||||
BLEMediumV2::PowerMode::Value power_mode,
|
||||
const string& fast_advertisement_service_uuid);
|
||||
void stopAdvertising();
|
||||
|
||||
bool startScanning(
|
||||
const string& service_id,
|
||||
Ptr<DiscoveredPeripheralCallback> discovered_peripheral_callback,
|
||||
BLEMediumV2::PowerMode::Value power_mode,
|
||||
const string& fast_advertisement_service_uuid);
|
||||
void stopScanning();
|
||||
|
||||
class AcceptedConnectionCallback {
|
||||
public:
|
||||
virtual ~AcceptedConnectionCallback() {}
|
||||
|
||||
// TODO(ahlee): Add in connecting logic.
|
||||
};
|
||||
|
||||
bool isAcceptingConnections();
|
||||
bool startAcceptingConnections(
|
||||
const string& service_id,
|
||||
Ptr<AcceptedConnectionCallback> accepted_connection_callback);
|
||||
void stopAcceptingConnections();
|
||||
|
||||
private:
|
||||
template <typename>
|
||||
friend class ble_v2::ProcessOnLostRunnable;
|
||||
template <typename>
|
||||
friend class ble_v2::OnAdvertisementFoundRunnable;
|
||||
|
||||
class GATTAdvertisementFetcherFacade
|
||||
: public DiscoveredPeripheralTracker<Platform>::GattAdvertisementFetcher {
|
||||
public:
|
||||
explicit GATTAdvertisementFetcherFacade(Ptr<BLEV2<Platform>> impl)
|
||||
: impl_(impl) {}
|
||||
~GATTAdvertisementFetcherFacade() override {}
|
||||
|
||||
Ptr<AdvertisementReadResult<Platform>> fetchGattAdvertisements(
|
||||
Ptr<BLEPeripheralV2> ble_peripheral, std::int32_t num_slots,
|
||||
Ptr<AdvertisementReadResult<Platform>> advertisement_read_result)
|
||||
override {
|
||||
return impl_->processFetchGattAdvertisementsRequest(
|
||||
ble_peripheral, num_slots, advertisement_read_result);
|
||||
}
|
||||
|
||||
private:
|
||||
Ptr<BLEV2<Platform>> impl_;
|
||||
};
|
||||
|
||||
class ScanCallbackFacade : public BLEMediumV2::ScanCallback {
|
||||
public:
|
||||
explicit ScanCallbackFacade(Ptr<BLEV2<Platform>> impl) : impl_(impl) {}
|
||||
~ScanCallbackFacade() override {}
|
||||
|
||||
void onAdvertisementFound(
|
||||
Ptr<BLEPeripheralV2> peripheral,
|
||||
ConstPtr<BLEAdvertisementData> advertisement_data) override {
|
||||
impl_->onAdvertisementFoundImpl(peripheral, advertisement_data);
|
||||
}
|
||||
|
||||
private:
|
||||
Ptr<BLEV2<Platform>> impl_;
|
||||
};
|
||||
|
||||
class ClientGATTConnectionLifecycleCallbackFacade
|
||||
: public ClientGATTConnectionLifecycleCallback {
|
||||
public:
|
||||
explicit ClientGATTConnectionLifecycleCallbackFacade(
|
||||
Ptr<BLEV2<Platform>> impl)
|
||||
: impl_(impl) {}
|
||||
~ClientGATTConnectionLifecycleCallbackFacade() override {}
|
||||
|
||||
void onDisconnected(Ptr<ClientGATTConnection> connection) override {
|
||||
// Avoid leaks.
|
||||
ScopedPtr<Ptr<ClientGATTConnection>> scoped_connection(connection);
|
||||
|
||||
// Nothing else to do for now.
|
||||
}
|
||||
|
||||
private:
|
||||
Ptr<BLEV2<Platform>> impl_;
|
||||
};
|
||||
|
||||
class ServerGATTConnectionLifecycleCallbackFacade
|
||||
: public ServerGATTConnectionLifecycleCallback {
|
||||
public:
|
||||
explicit ServerGATTConnectionLifecycleCallbackFacade(
|
||||
Ptr<BLEV2<Platform>> impl)
|
||||
: impl_(impl) {}
|
||||
~ServerGATTConnectionLifecycleCallbackFacade() override {}
|
||||
|
||||
void onCharacteristicSubscription(
|
||||
Ptr<ServerGATTConnection> connection,
|
||||
Ptr<GATTCharacteristic> characteristic) override {
|
||||
// Avoid leaks. Do not scope the characteristic because it is ref counted
|
||||
// by the per-platform ble_v2 implementation.
|
||||
ScopedPtr<Ptr<ServerGATTConnection>> scoped_connection(connection);
|
||||
|
||||
// Nothing else to do for now.
|
||||
}
|
||||
|
||||
void onCharacteristicUnsubscription(
|
||||
Ptr<ServerGATTConnection> connection,
|
||||
Ptr<GATTCharacteristic> characteristic) override {
|
||||
// Avoid leaks. Do not scope the characteristic because it is ref counted
|
||||
// by the per-platform ble_v2 implementation.
|
||||
ScopedPtr<Ptr<ServerGATTConnection>> scoped_connection(connection);
|
||||
|
||||
// Nothing else to do for now.
|
||||
}
|
||||
|
||||
private:
|
||||
Ptr<BLEV2<Platform>> impl_;
|
||||
};
|
||||
|
||||
struct ScanningInfo {
|
||||
ScanningInfo(const string& service_id,
|
||||
Ptr<ScanCallbackFacade> scan_callback_facade,
|
||||
Ptr<CancelableAlarm<Platform>> on_lost_alarm)
|
||||
: service_id(service_id),
|
||||
scan_callback_facade(scan_callback_facade),
|
||||
on_lost_alarm(on_lost_alarm) {}
|
||||
~ScanningInfo() {
|
||||
// Nothing to do (the ScopedPtr members take care of themselves).
|
||||
}
|
||||
|
||||
const string service_id;
|
||||
ScopedPtr<Ptr<ScanCallbackFacade>> scan_callback_facade;
|
||||
// TODO(ahlee): Change to recurring cancelable alarm
|
||||
ScopedPtr<Ptr<CancelableAlarm<Platform>>> on_lost_alarm;
|
||||
};
|
||||
|
||||
struct AdvertisingInfo {
|
||||
explicit AdvertisingInfo(const string& service_id)
|
||||
: service_id(service_id) {}
|
||||
~AdvertisingInfo() {}
|
||||
|
||||
const string service_id;
|
||||
};
|
||||
|
||||
struct GATTServerInfo {
|
||||
GATTServerInfo(Ptr<GATTServer> gatt_server,
|
||||
Ptr<ServerGATTConnectionLifecycleCallbackFacade>
|
||||
connection_lifecycle_callback)
|
||||
: gatt_server(gatt_server),
|
||||
connection_lifecycle_callback(connection_lifecycle_callback) {}
|
||||
~GATTServerInfo() {
|
||||
// Nothing to do (the ScopedPtr members take care of themselves).
|
||||
}
|
||||
|
||||
ScopedPtr<Ptr<GATTServer>> gatt_server;
|
||||
ScopedPtr<Ptr<ServerGATTConnectionLifecycleCallbackFacade>>
|
||||
connection_lifecycle_callback;
|
||||
};
|
||||
|
||||
struct AcceptingConnectionsInfo {
|
||||
explicit AcceptingConnectionsInfo(const string& service_id)
|
||||
: service_id(service_id) {}
|
||||
~AcceptingConnectionsInfo() {
|
||||
// Nothing to do (the ScopedPtr members take care of themselves).
|
||||
}
|
||||
|
||||
const string service_id;
|
||||
// TODO(ahlee): Fill in.
|
||||
};
|
||||
|
||||
static const std::int32_t kNumAdvertisementSlots;
|
||||
static const std::int32_t kMaxAdvertisementLength;
|
||||
static const std::int32_t kDummyServiceIdLength;
|
||||
static const char* kCopresenceServiceUuid;
|
||||
static const std::int64_t kOnLostTimeoutMillis;
|
||||
static const std::int64_t kGattAdvertisementOperationTimeoutMillis;
|
||||
static const std::int64_t kMinConnectionAttemptRecoveryDurationMillis;
|
||||
static const std::int32_t kMaxConnectionAttemptRecoveryFuzzDurationMillis;
|
||||
static const std::uint32_t kDefaultMtu;
|
||||
static const std::int64_t kAdvertisementUuidMsb;
|
||||
static const std::int64_t kAdvertisementUuidLsb;
|
||||
|
||||
bool isAdvertising();
|
||||
ConstPtr<ByteArray> createAdvertisementHeader(
|
||||
const string& service_id, ConstPtr<ByteArray> advertisement_bytes,
|
||||
bool is_fast_advertisement);
|
||||
|
||||
bool isScanning();
|
||||
void onAdvertisementFoundImpl(
|
||||
Ptr<BLEPeripheralV2> ble_peripheral,
|
||||
ConstPtr<BLEAdvertisementData> advertisement_data);
|
||||
void processOnLostTimeout();
|
||||
Ptr<CancelableAlarm<Platform>> createOnLostAlarm();
|
||||
|
||||
bool isAdvertisementGattServerRunning();
|
||||
bool startAdvertisementGattServer(const string& service_id,
|
||||
ConstPtr<ByteArray> advertisement);
|
||||
bool internalStartAdvertisementGattServer(
|
||||
ConstPtr<ByteArray> legacy_ble_advertisement_bytes,
|
||||
ConstPtr<ByteArray> ble_advertisement_bytes);
|
||||
bool generateAdvertisementCharacteristic(
|
||||
std::int32_t slot, ConstPtr<ByteArray> advertisement,
|
||||
Ptr<GATTServer> gatt_server);
|
||||
void stopAdvertisementGattServer();
|
||||
|
||||
Ptr<AdvertisementReadResult<Platform>> processFetchGattAdvertisementsRequest(
|
||||
Ptr<BLEPeripheralV2> peripheral, std::int32_t num_slots,
|
||||
Ptr<AdvertisementReadResult<Platform>> advertisement_read_result);
|
||||
Ptr<AdvertisementReadResult<Platform>>
|
||||
internalReadFromAdvertisementGattServer(
|
||||
Ptr<BLEPeripheralV2> ble_peripheral, std::int32_t num_slots,
|
||||
Ptr<AdvertisementReadResult<Platform>> advertisement_read_result);
|
||||
|
||||
void offloadFromPlatformThread(Ptr<Runnable> runnable);
|
||||
// TODO(ahlee): Move these out to utils (also used by
|
||||
// DiscoveredPeripheralTracker).
|
||||
ConstPtr<ByteArray> generateAdvertisementHash(
|
||||
ConstPtr<ByteArray> advertisement_bytes);
|
||||
ConstPtr<ByteArray> generateServiceIdHash(
|
||||
BLEAdvertisement::Version::Value version, const string& service_id);
|
||||
|
||||
// This maps to a helper function found in bluetoothlowenergy/Utils.java. In
|
||||
// the C++ code we moved it because it's only used here.
|
||||
string generateAdvertisementUuid(std::int32_t slot);
|
||||
|
||||
// ------------ GENERAL ------------
|
||||
|
||||
ScopedPtr<Ptr<Lock>> lock_;
|
||||
// Where we throw potentially blocking work off of the platform thread.
|
||||
ScopedPtr<Ptr<typename Platform::SingleThreadExecutorType>>
|
||||
platform_thread_offloader_;
|
||||
ScopedPtr<Ptr<Prng>> prng_;
|
||||
ScopedPtr<Ptr<HashUtils>> hash_utils_;
|
||||
|
||||
// ------------ CORE BLE ------------
|
||||
|
||||
Ptr<BluetoothRadio<Platform>> bluetooth_radio_;
|
||||
ScopedPtr<Ptr<BluetoothAdapter>> bluetooth_adapter_;
|
||||
// The underlying, per-platform implementation.
|
||||
ScopedPtr<Ptr<BLEMediumV2>> ble_medium_;
|
||||
|
||||
// ------------ DISCOVERY ------------
|
||||
|
||||
// scanning_info_ is not scoped because it's nullable.
|
||||
Ptr<ScanningInfo> scanning_info_;
|
||||
ScopedPtr<Ptr<DiscoveredPeripheralTracker<Platform>>>
|
||||
discovered_peripheral_tracker_;
|
||||
ScopedPtr<Ptr<typename Platform::ScheduledExecutorType>> on_lost_executor_;
|
||||
|
||||
// ------------ ADVERTISING ------------
|
||||
|
||||
// advertising_info_, gatt_server_info_, and accepting_connections_info_ are
|
||||
// not scoped because they are nullable.
|
||||
Ptr<AdvertisingInfo> advertising_info_;
|
||||
Ptr<GATTServerInfo> gatt_server_info_;
|
||||
Ptr<AcceptingConnectionsInfo> accepting_connections_info_;
|
||||
};
|
||||
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
|
||||
#include "core/internal/mediums/ble_v2.cc"
|
||||
|
||||
#endif // CORE_INTERNAL_MEDIUMS_BLE_V2_H_
|
||||
@@ -0,0 +1,109 @@
|
||||
#include "core/internal/mediums/bloom_filter.h"
|
||||
|
||||
#include "absl/numeric/int128.h"
|
||||
#include "absl/strings/numbers.h"
|
||||
#include "smhasher/MurmurHash3.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
template <size_t CapacityInBytes>
|
||||
const std::int32_t BloomFilter<CapacityInBytes>::kHasherNumberOfRepetitions = 5;
|
||||
|
||||
template <size_t CapacityInBytes>
|
||||
BloomFilter<CapacityInBytes>::BloomFilter() : bits_() {}
|
||||
|
||||
template <size_t CapacityInBytes>
|
||||
BloomFilter<CapacityInBytes>::BloomFilter(ConstPtr<ByteArray> bytes) : bits_() {
|
||||
const char* bytes_read_ptr = bytes->getData();
|
||||
for (size_t byte_index = 0; byte_index < bytes->size(); byte_index++) {
|
||||
for (size_t bit_index = 0; bit_index < 8; bit_index++) {
|
||||
bits_.set((byte_index * 8) + bit_index,
|
||||
(*bytes_read_ptr >> bit_index) & 0x01);
|
||||
}
|
||||
bytes_read_ptr++;
|
||||
}
|
||||
}
|
||||
|
||||
template <size_t CapacityInBytes>
|
||||
BloomFilter<CapacityInBytes>::~BloomFilter() {
|
||||
// Nothing to do.
|
||||
}
|
||||
|
||||
template <size_t CapacityInBytes>
|
||||
ConstPtr<ByteArray> BloomFilter<CapacityInBytes>::asBytes() {
|
||||
// Gets a binary string representation of the bitset where the leftmost
|
||||
// character corresponds to bitset position (total size) - 1.
|
||||
//
|
||||
// If the bitset's internal representation is:
|
||||
// [position 0] 0 0 1 1 0 0 0 1 0 1 0 1 [position 11]
|
||||
// The string representation will be outputted like this:
|
||||
// "1 0 1 0 1 0 0 0 1 1 0 0"
|
||||
std::string bitset_binary_string = bits_.to_string();
|
||||
|
||||
Ptr<ByteArray> result_bytes{new ByteArray{CapacityInBytes}};
|
||||
char* result_bytes_write_ptr = result_bytes->getData();
|
||||
// We go through the string backwards because the rightmost character
|
||||
// corresponds to position 0 in the bitset.
|
||||
for (size_t i = bits_.size(); i > 0; i -= 8) {
|
||||
std::string byte_binary_string = bitset_binary_string.substr(i - 8, 8);
|
||||
std::uint32_t byte_value;
|
||||
absl::numbers_internal::safe_strtou32_base(byte_binary_string, &byte_value,
|
||||
/* base= */ 2);
|
||||
*result_bytes_write_ptr = static_cast<char>(byte_value & 0x000000FF);
|
||||
result_bytes_write_ptr++;
|
||||
}
|
||||
return ConstifyPtr(result_bytes);
|
||||
}
|
||||
|
||||
template <size_t CapacityInBytes>
|
||||
void BloomFilter<CapacityInBytes>::add(const std::string& s) {
|
||||
std::vector<std::int32_t> hashes = getHashes(s);
|
||||
for (std::vector<std::int32_t>::iterator it = hashes.begin();
|
||||
it != hashes.end(); ++it) {
|
||||
size_t position = static_cast<size_t>(*it) % bits_.size();
|
||||
bits_.set(position);
|
||||
}
|
||||
}
|
||||
|
||||
template <size_t CapacityInBytes>
|
||||
bool BloomFilter<CapacityInBytes>::possiblyContains(const std::string& s) {
|
||||
std::vector<std::int32_t> hashes = getHashes(s);
|
||||
for (std::vector<std::int32_t>::iterator i = hashes.begin();
|
||||
i != hashes.end(); ++i) {
|
||||
size_t position = static_cast<size_t>(*i) % bits_.size();
|
||||
if (!bits_.test(position)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
template <size_t CapacityInBytes>
|
||||
std::vector<std::int32_t> BloomFilter<CapacityInBytes>::getHashes(
|
||||
const std::string& s) {
|
||||
std::vector<std::int32_t> hashes(kHasherNumberOfRepetitions, 0);
|
||||
|
||||
absl::uint128 hash128;
|
||||
MurmurHash3_x64_128(s.data(), s.size(), 0, &hash128);
|
||||
std::uint64_t hash64 =
|
||||
absl::Uint128Low64(hash128); // the lower 64 bits of the 128-bit hash
|
||||
std::int32_t hash1 = static_cast<std::int32_t>(
|
||||
hash64 & 0x00000000FFFFFFFF); // the lower 32 bits of the 64-bit hash
|
||||
std::int32_t hash2 = static_cast<std::int32_t>(
|
||||
(hash64 >> 32) & 0x0FFFFFFFF); // the upper 32 bits of the 64-bit hash
|
||||
for (size_t i = 1; i <= kHasherNumberOfRepetitions; i++) {
|
||||
std::int32_t combinedHash = static_cast<std::int32_t>(hash1 + (i * hash2));
|
||||
// Flip all the bits if it's negative (guaranteed positive number)
|
||||
if (combinedHash < 0) combinedHash = ~combinedHash;
|
||||
hashes[i - 1] = combinedHash;
|
||||
}
|
||||
return hashes;
|
||||
}
|
||||
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
@@ -0,0 +1,54 @@
|
||||
#ifndef CORE_INTERNAL_MEDIUMS_BLOOM_FILTER_H_
|
||||
#define CORE_INTERNAL_MEDIUMS_BLOOM_FILTER_H_
|
||||
|
||||
#include <bitset>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#include "platform/byte_array.h"
|
||||
#include "platform/port/string.h"
|
||||
#include "platform/ptr.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
/**
|
||||
* A bloom filter that gives access to the underlying BitSet. The implementation
|
||||
* is copied from our Java version of Bloom filter, which in turn copies from
|
||||
* Guava's BloomFilter.
|
||||
*
|
||||
* BloomFilter is templatized on the size of the byte array and not the size of
|
||||
* the bit set to ensure the bit set's length is a multiple of 8 (and can
|
||||
* neatly be returned as a ByteArray).
|
||||
*/
|
||||
template <size_t CapacityInBytes>
|
||||
class BloomFilter {
|
||||
public:
|
||||
BloomFilter();
|
||||
explicit BloomFilter(ConstPtr<ByteArray> bytes);
|
||||
~BloomFilter();
|
||||
|
||||
ConstPtr<ByteArray> asBytes();
|
||||
|
||||
void add(const std::string& s);
|
||||
|
||||
bool possiblyContains(const std::string& s);
|
||||
|
||||
private:
|
||||
static const std::int32_t kHasherNumberOfRepetitions;
|
||||
|
||||
std::vector<std::int32_t> getHashes(const std::string& s);
|
||||
|
||||
std::bitset<CapacityInBytes * 8> bits_;
|
||||
};
|
||||
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
|
||||
#include "core/internal/mediums/bloom_filter.cc"
|
||||
|
||||
#endif // CORE_INTERNAL_MEDIUMS_BLOOM_FILTER_H_
|
||||
@@ -0,0 +1,162 @@
|
||||
#include "core/internal/mediums/bloom_filter.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
namespace {
|
||||
|
||||
const size_t kByteArrayLength = 100;
|
||||
|
||||
TEST(BloomFilterTest, EmptyFilterReturnsEmptyArray) {
|
||||
ScopedPtr<Ptr<BloomFilter<kByteArrayLength>>> scoped_bloom_filter(
|
||||
new BloomFilter<kByteArrayLength>());
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray>> scoped_bloom_filter_bytes(
|
||||
scoped_bloom_filter->asBytes());
|
||||
std::string empty_string(kByteArrayLength, '\0');
|
||||
ASSERT_EQ(0, memcmp(scoped_bloom_filter_bytes->getData(), empty_string.data(),
|
||||
empty_string.size()));
|
||||
}
|
||||
|
||||
TEST(BloomFilterTest, EmptyFilterNeverContains) {
|
||||
ScopedPtr<Ptr<BloomFilter<kByteArrayLength>>> scoped_bloom_filter(
|
||||
new BloomFilter<kByteArrayLength>());
|
||||
|
||||
ASSERT_FALSE(scoped_bloom_filter->possiblyContains("ELEMENT_1"));
|
||||
ASSERT_FALSE(scoped_bloom_filter->possiblyContains("ELEMENT_2"));
|
||||
ASSERT_FALSE(scoped_bloom_filter->possiblyContains("ELEMENT_3"));
|
||||
}
|
||||
|
||||
TEST(BloomFilterTest, AddSuccess) {
|
||||
ScopedPtr<Ptr<BloomFilter<kByteArrayLength>>> scoped_bloom_filter(
|
||||
new BloomFilter<kByteArrayLength>());
|
||||
ASSERT_FALSE(scoped_bloom_filter->possiblyContains("ELEMENT_1"));
|
||||
|
||||
scoped_bloom_filter->add("ELEMENT_1");
|
||||
ASSERT_TRUE(scoped_bloom_filter->possiblyContains("ELEMENT_1"));
|
||||
}
|
||||
|
||||
TEST(BloomFilterTest, AddOnlyGivenArg) {
|
||||
ScopedPtr<Ptr<BloomFilter<kByteArrayLength>>> scoped_bloom_filter(
|
||||
new BloomFilter<kByteArrayLength>());
|
||||
scoped_bloom_filter->add("ELEMENT_1");
|
||||
|
||||
ASSERT_TRUE(scoped_bloom_filter->possiblyContains("ELEMENT_1"));
|
||||
ASSERT_FALSE(scoped_bloom_filter->possiblyContains("ELEMENT_2"));
|
||||
ASSERT_FALSE(scoped_bloom_filter->possiblyContains("ELEMENT_3"));
|
||||
}
|
||||
|
||||
TEST(BloomFilterTest, AddMultipleArgs) {
|
||||
ScopedPtr<Ptr<BloomFilter<kByteArrayLength>>> scoped_bloom_filter(
|
||||
new BloomFilter<kByteArrayLength>());
|
||||
scoped_bloom_filter->add("ELEMENT_1");
|
||||
scoped_bloom_filter->add("ELEMENT_2");
|
||||
|
||||
ASSERT_TRUE(scoped_bloom_filter->possiblyContains("ELEMENT_1"));
|
||||
ASSERT_TRUE(scoped_bloom_filter->possiblyContains("ELEMENT_2"));
|
||||
ASSERT_FALSE(scoped_bloom_filter->possiblyContains("ELEMENT_3"));
|
||||
}
|
||||
|
||||
TEST(BloomFilterTest, AddMultipleArgsReturnsNonemptyArray) {
|
||||
ScopedPtr<Ptr<BloomFilter<10>>> scoped_bloom_filter(new BloomFilter<10>());
|
||||
scoped_bloom_filter->add("ELEMENT_1");
|
||||
scoped_bloom_filter->add("ELEMENT_2");
|
||||
scoped_bloom_filter->add("ELEMENT_3");
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray>> scoped_bloom_filter_bytes(
|
||||
scoped_bloom_filter->asBytes());
|
||||
std::string empty_string(kByteArrayLength, '\0');
|
||||
ASSERT_NE(0, memcmp(scoped_bloom_filter_bytes->getData(), empty_string.data(),
|
||||
empty_string.size()));
|
||||
}
|
||||
|
||||
/**
|
||||
* This test was added because of a bug where the BloomFilter doesn't utilize
|
||||
* all bits given. Functionally, the filter still works, but we just have a much
|
||||
* higher false positive rate. The bug was caused by confusing bit length and
|
||||
* byte length, which made our BloomFilter only set bits on the first byteLength
|
||||
* (bitLength / 8) bits rather than the whole bitLength bits.
|
||||
*
|
||||
* <p>Here, we're verifying that the bits set are somewhat scattered. So instead
|
||||
* of something like [ 0, 1, 1, 0, 0, 0, 0, ..., 0 ], we should be getting
|
||||
* something like [ 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, ..., 1, 0].
|
||||
*/
|
||||
TEST(BloomFilterTest, RandomnessNoEndBias) {
|
||||
ScopedPtr<Ptr<BloomFilter<kByteArrayLength>>> scoped_bloom_filter(
|
||||
new BloomFilter<kByteArrayLength>());
|
||||
// Add one element to our BloomFilter.
|
||||
scoped_bloom_filter->add("ELEMENT_1");
|
||||
|
||||
std::int32_t non_zero_count = 0;
|
||||
std::int32_t longest_zero_streak = 0;
|
||||
std::int32_t current_zero_streak = 0;
|
||||
|
||||
// Record the amount of non-zero bytes and the longest streak of zero bytes in
|
||||
// the resulting BloomFilter. This is an approximation of reasonable
|
||||
// distribution since we're recording by bytes instead of bits.
|
||||
ScopedPtr<ConstPtr<ByteArray>> scoped_bloom_filter_bytes(
|
||||
scoped_bloom_filter->asBytes());
|
||||
const char* bloom_filter_bytes_read_ptr =
|
||||
scoped_bloom_filter_bytes->getData();
|
||||
for (int i = 0; i < scoped_bloom_filter_bytes->size(); i++) {
|
||||
if (*bloom_filter_bytes_read_ptr == '\0') {
|
||||
current_zero_streak++;
|
||||
} else {
|
||||
// Increment the number of non-zero bytes we've seen, update the longest
|
||||
// zero streak, and then reset the current zero streak.
|
||||
non_zero_count++;
|
||||
longest_zero_streak = std::max(longest_zero_streak, current_zero_streak);
|
||||
current_zero_streak = 0;
|
||||
}
|
||||
bloom_filter_bytes_read_ptr++;
|
||||
}
|
||||
// Update the longest zero streak again for the tail case.
|
||||
longest_zero_streak = std::min(longest_zero_streak, current_zero_streak);
|
||||
|
||||
// Since randomness is hard to measure within one unit test, we instead do a
|
||||
// sanity check. All non-zero bytes should not be packed into one end of the
|
||||
// array.
|
||||
//
|
||||
// In this case, the size of one end is approximated to be:
|
||||
// kByteArrayLength / nonZeroCount.
|
||||
// Therefore, the longest zero streak should be less than:
|
||||
// kByteArrayLength - one end of the array.
|
||||
std::int32_t longest_acceptable_zero_streak =
|
||||
kByteArrayLength - (kByteArrayLength / non_zero_count);
|
||||
ASSERT_TRUE(longest_zero_streak <= longest_acceptable_zero_streak);
|
||||
}
|
||||
|
||||
TEST(BloomFilterTest, RandomnessFalsePositiveRate) {
|
||||
ScopedPtr<Ptr<BloomFilter<10>>> scoped_bloom_filter(new BloomFilter<10>());
|
||||
// Add 5 distinct elements to the BloomFilter.
|
||||
scoped_bloom_filter->add("ELEMENT_1");
|
||||
scoped_bloom_filter->add("ELEMENT_2");
|
||||
scoped_bloom_filter->add("ELEMENT_3");
|
||||
scoped_bloom_filter->add("ELEMENT_4");
|
||||
scoped_bloom_filter->add("ELEMENT_5");
|
||||
|
||||
std::int32_t false_positives = 0;
|
||||
// Now test 100 other elements and record the number of false positives.
|
||||
for (int i = 5; i < 105; i++) {
|
||||
false_positives +=
|
||||
scoped_bloom_filter->possiblyContains("ELEMENT_" + std::to_string(i))
|
||||
? 1
|
||||
: 0;
|
||||
}
|
||||
|
||||
// We expect the false positive rate to be 3% with 5 elements in a 10 byte
|
||||
// filter. Thus, we give a little leeway and verify that the false positive
|
||||
// rate is no more than 5%.
|
||||
ASSERT_LE(false_positives, 5);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
@@ -0,0 +1,468 @@
|
||||
#include "core/internal/mediums/bluetooth_classic.h"
|
||||
|
||||
#include <utility>
|
||||
|
||||
#include "core/internal/mediums/uuid.h"
|
||||
#include "platform/synchronized.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
|
||||
template <typename Platform>
|
||||
const std::int32_t BluetoothClassic<Platform>::kMaxConcurrentAcceptLoops = 5;
|
||||
|
||||
template <typename Platform>
|
||||
BluetoothClassic<Platform>::BluetoothClassic(
|
||||
Ptr<BluetoothRadio<Platform>> bluetooth_radio)
|
||||
: lock_(Platform::createLock()),
|
||||
bluetooth_radio_(bluetooth_radio),
|
||||
bluetooth_adapter_(Platform::createBluetoothAdapter()),
|
||||
bluetooth_classic_medium_(Platform::createBluetoothClassicMedium()),
|
||||
scan_info_(),
|
||||
original_scan_mode_(BluetoothAdapter::ScanMode::UNKNOWN),
|
||||
original_device_name_(),
|
||||
accept_loops_thread_pool_(
|
||||
Platform::createMultiThreadExecutor(kMaxConcurrentAcceptLoops)),
|
||||
bluetooth_server_sockets_() {}
|
||||
|
||||
template <typename Platform>
|
||||
BluetoothClassic<Platform>::~BluetoothClassic() {
|
||||
stopDiscovery();
|
||||
for (BluetoothServerSocketMap::iterator it =
|
||||
bluetooth_server_sockets_.begin();
|
||||
it != bluetooth_server_sockets_.end(); ++it) {
|
||||
stopAcceptingConnections(it->first);
|
||||
}
|
||||
turnOffDiscoverability();
|
||||
|
||||
// All the AcceptLoopRunnable objects in here should already have gotten an
|
||||
// opportunity to shut themselves down cleanly in the calls to
|
||||
// stopAcceptingConnections() above.
|
||||
accept_loops_thread_pool_->shutdown();
|
||||
|
||||
original_device_name_.destroy();
|
||||
scan_info_.destroy();
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BluetoothClassic<Platform>::isAvailable() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
return !bluetooth_classic_medium_.isNull() && !bluetooth_adapter_.isNull();
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BluetoothClassic<Platform>::turnOnDiscoverability(
|
||||
const string& device_name) {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
if (device_name.empty()) {
|
||||
// TODO(ahlee): logger.atSevere().log("Refusing to turn on Bluetooth
|
||||
// discoverability because a null deviceName was passed in.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!bluetooth_radio_->isEnabled()) {
|
||||
// TODO(reznor): log.atSevere().log("Can't turn on Bluetooth discoverability
|
||||
// because Bluetooth isn't enabled.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isAvailable()) {
|
||||
// TODO(reznor): log.atSevere().log("Can't turn on Bluetooth discoverability
|
||||
// because Bluetooth isn't available.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isDiscoverable()) {
|
||||
// TODO(reznor): log.atSevere().log("Refusing to turn on Bluetooth
|
||||
// discoverability with device name %s because we're already discoverable
|
||||
// with device name %s.", deviceName, bluetoothAdapter.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!modifyDeviceName(device_name)) {
|
||||
// TODO(reznor): log.atSevere().log("Failed to turn on Bluetooth
|
||||
// discoverability because we couldn't set the device name to %s",
|
||||
// deviceName);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!modifyScanMode(BluetoothAdapter::ScanMode::CONNECTABLE_DISCOVERABLE)) {
|
||||
// TODO(reznor): log.atSevere().log("Failed to turn on Bluetooth
|
||||
// discoverability because we couldn't set the scan mode to %d",
|
||||
// BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE);
|
||||
|
||||
// Don't forget to perform this rollback of the partial state changes we've
|
||||
// made til now.
|
||||
restoreDeviceName();
|
||||
return false;
|
||||
}
|
||||
|
||||
// TODO(reznor): log.atVerbose().log("Turned on Bluetooth discoverability with
|
||||
// deviceName %s", deviceName);
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
void BluetoothClassic<Platform>::turnOffDiscoverability() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
if (!isDiscoverable()) {
|
||||
// TODO(reznor): log.atDebug().log("Can't turn off Bluetooth discoverability
|
||||
// because it was never turned on.");
|
||||
return;
|
||||
}
|
||||
|
||||
restoreScanMode();
|
||||
restoreDeviceName();
|
||||
|
||||
// TODO(reznor): log.atVerbose().log("Turned Bluetooth discoverability off");
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BluetoothClassic<Platform>::isDiscoverable() const {
|
||||
return ((!original_device_name_.isNull()) &&
|
||||
(BluetoothAdapter::ScanMode::CONNECTABLE_DISCOVERABLE ==
|
||||
bluetooth_adapter_->getScanMode()));
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BluetoothClassic<Platform>::modifyDeviceName(const string& device_name) {
|
||||
original_device_name_ = bluetooth_adapter_->getName();
|
||||
|
||||
if (!bluetooth_adapter_->setName(device_name)) {
|
||||
original_device_name_.destroy();
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BluetoothClassic<Platform>::modifyScanMode(
|
||||
BluetoothAdapter::ScanMode::Value scan_mode) {
|
||||
original_scan_mode_ = bluetooth_adapter_->getScanMode();
|
||||
|
||||
if (!bluetooth_adapter_->setScanMode(scan_mode)) {
|
||||
original_scan_mode_ = BluetoothAdapter::ScanMode::UNKNOWN;
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
void BluetoothClassic<Platform>::restoreScanMode() {
|
||||
if (!bluetooth_adapter_->setScanMode(original_scan_mode_)) {
|
||||
// TODO(reznor): log.atWarning().log("Failed to restore original Bluetooth
|
||||
// scan mode to %d", originalScanMode);
|
||||
}
|
||||
|
||||
// Regardless of whether or not we could actually restore the Bluetooth scan
|
||||
// mode, reset our relevant state.
|
||||
original_scan_mode_ = BluetoothAdapter::ScanMode::UNKNOWN;
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
void BluetoothClassic<Platform>::restoreDeviceName() {
|
||||
if (!bluetooth_adapter_->setName(*original_device_name_)) {
|
||||
// TODO(reznor): log.atWarning().log("Failed to restore original Bluetooth
|
||||
// device name to %s", originalDeviceName);
|
||||
}
|
||||
|
||||
// Regardless of whether or not we could actually restore the Bluetooth device
|
||||
// name, reset the marker that opens us up for business for the next time
|
||||
// 'round.
|
||||
original_device_name_.destroy();
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BluetoothClassic<Platform>::startDiscovery(
|
||||
Ptr<DiscoveredDeviceCallback> discovered_device_callback) {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
if (discovered_device_callback.isNull()) {
|
||||
// TODO(reznor): log.atSevere().log("Refusing to start discovery of
|
||||
// Bluetooth devices because a null discoveredDeviceCallback was passed
|
||||
// in.");
|
||||
return false;
|
||||
}
|
||||
// Avoid leaks.
|
||||
ScopedPtr<Ptr<DiscoveredDeviceCallback>> scoped_discovered_device_callback(
|
||||
discovered_device_callback);
|
||||
|
||||
if (!bluetooth_radio_->isEnabled()) {
|
||||
// TODO(reznor): log.atSevere().log("Can't discover Bluetooth devices
|
||||
// because Bluetooth isn't enabled.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isAvailable()) {
|
||||
// TODO(reznor): log.atSevere().log("Can't discover Bluetooth devices
|
||||
// because Bluetooth isn't available.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isDiscovering()) {
|
||||
// TODO(reznor): log.atSevere().log("Refusing to start discovery of
|
||||
// Bluetooth devices because another discovery is already in-progress.");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Avoid leaks.
|
||||
ScopedPtr<Ptr<BluetoothDiscoveryCallback>>
|
||||
scoped_bluetooth_discovery_callback(new BluetoothDiscoveryCallback(
|
||||
scoped_discovered_device_callback.get()));
|
||||
|
||||
if (!bluetooth_classic_medium_->startDiscovery(
|
||||
scoped_bluetooth_discovery_callback.get())) {
|
||||
// TODO(reznor): log.atSevere().log("Failed to start discovery of Bluetooth
|
||||
// devices.");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Mark the fact that we're currently performing a Bluetooth scan.
|
||||
scan_info_ =
|
||||
MakePtr(new ScanInfo(scoped_discovered_device_callback.release(),
|
||||
scoped_bluetooth_discovery_callback.release()));
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
void BluetoothClassic<Platform>::stopDiscovery() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
if (!isDiscovering()) {
|
||||
// TODO(reznor): log.atDebug().log("Can't stop discovery of Bluetooth
|
||||
// devices because it never started.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!bluetooth_classic_medium_->stopDiscovery()) {
|
||||
// TODO(reznor): log.atWarning().log("Failed to stop discovery of Bluetooth
|
||||
// devices.");
|
||||
}
|
||||
// Regardless of whether or not stopDiscovery() succeeded, destroy scan_info_
|
||||
// to:
|
||||
//
|
||||
// a) Avoid a leak.
|
||||
// b) Mark the fact that we're no longer performing a Bluetooth discovery.
|
||||
scan_info_.destroy();
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BluetoothClassic<Platform>::isDiscovering() const {
|
||||
return !scan_info_.isNull();
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
class AcceptLoopRunnable : public Runnable {
|
||||
public:
|
||||
AcceptLoopRunnable(
|
||||
Ptr<typename BluetoothClassic<Platform>::AcceptedConnectionCallback>
|
||||
accepted_connection_callback,
|
||||
Ptr<BluetoothServerSocket> listening_socket, const string& service_name)
|
||||
: accepted_connection_callback_(accepted_connection_callback),
|
||||
listening_socket_(listening_socket),
|
||||
service_name_(service_name) {}
|
||||
|
||||
void run() override {
|
||||
while (true) {
|
||||
ExceptionOr<Ptr<BluetoothSocket>> bluetooth_socket =
|
||||
listening_socket_->accept();
|
||||
if (!bluetooth_socket.ok()) {
|
||||
if (Exception::IO == bluetooth_socket.exception()) {
|
||||
Utils::closeSocket(listening_socket_, "Bluetooth", service_name_);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
accepted_connection_callback_->onConnectionAccepted(
|
||||
bluetooth_socket.result());
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
ScopedPtr<
|
||||
Ptr<typename BluetoothClassic<Platform>::AcceptedConnectionCallback>>
|
||||
accepted_connection_callback_;
|
||||
Ptr<BluetoothServerSocket> listening_socket_;
|
||||
const string service_name_;
|
||||
};
|
||||
|
||||
template <typename Platform>
|
||||
bool BluetoothClassic<Platform>::startAcceptingConnections(
|
||||
const string& service_name,
|
||||
Ptr<AcceptedConnectionCallback> accepted_connection_callback) {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
// Avoid leaks.
|
||||
ScopedPtr<Ptr<AcceptedConnectionCallback>>
|
||||
scoped_accepted_connection_callback(accepted_connection_callback);
|
||||
if (scoped_accepted_connection_callback.isNull() || service_name.empty()) {
|
||||
// TODO(reznor): log.atSevere().log("Refusing to start accepting Bluetooth
|
||||
// connections because at least one of serviceName or
|
||||
// acceptedConnectionCallback is null.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!bluetooth_radio_->isEnabled()) {
|
||||
// TODO(reznor): log.atSevere().log("Can't create Bluetooth server socket
|
||||
// for %s because Bluetooth isn't enabled.", serviceName);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isAvailable()) {
|
||||
// TODO(reznor): log.atSevere().log("Can't start accepting BLuetooth
|
||||
// connections for %s because Bluetooth isn't available.", serviceName);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isAcceptingConnections(service_name)) {
|
||||
// TODO(reznor): log.atSevere().log("Refusing to start accepting Bluetooth
|
||||
// connections for %s because a Bluetooth server is already in-progress for
|
||||
// that service name.", serviceName);
|
||||
return false;
|
||||
}
|
||||
|
||||
ExceptionOr<Ptr<BluetoothServerSocket>> listening_socket =
|
||||
bluetooth_classic_medium_->listenForService(
|
||||
service_name, generateUUIDFromString(service_name));
|
||||
if (!listening_socket.ok()) {
|
||||
if (Exception::IO == listening_socket.exception()) {
|
||||
// TODO(reznor): log.atSevere().withCause(e).log("Failed to start
|
||||
// accepting Bluetooth connections for %s.", serviceName);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Start the accept loop on a dedicated thread - this stays alive and
|
||||
// listening for new incoming connections until stopAcceptingConnections() is
|
||||
// invoked.
|
||||
accept_loops_thread_pool_->execute(MakePtr(new AcceptLoopRunnable<Platform>(
|
||||
scoped_accepted_connection_callback.release(), listening_socket.result(),
|
||||
service_name)));
|
||||
|
||||
// Mark the fact that there's an in-progress Bluetooth server accepting
|
||||
// connections.
|
||||
bluetooth_server_sockets_.insert(
|
||||
std::make_pair(service_name, listening_socket.result()));
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BluetoothClassic<Platform>::isAcceptingConnections(
|
||||
const string& service_name) {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
return bluetooth_server_sockets_.find(service_name) !=
|
||||
bluetooth_server_sockets_.end();
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
void BluetoothClassic<Platform>::stopAcceptingConnections(
|
||||
const string& service_name) {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
if (service_name.empty()) {
|
||||
// TODO(ahlee): logger.atSevere().log("Unable to stop accepting Bluetooth
|
||||
// connections because the serviceName is empty.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isAcceptingConnections(service_name)) {
|
||||
// TODO(reznor): log.atDebug().log("Can't stop accepting Bluetooth
|
||||
// connections for %s because it was never started.", serviceName);
|
||||
return;
|
||||
}
|
||||
|
||||
// Closing the BluetoothServerSocket will kick off the suicide of the thread
|
||||
// in accept_loops_thread_pool_ that blocks on BluetoothServerSocket.accept().
|
||||
// That may take some time to complete, but there's no particular reason to
|
||||
// wait around for it.
|
||||
BluetoothServerSocketMap::iterator listening_socket_iter =
|
||||
bluetooth_server_sockets_.find(service_name);
|
||||
|
||||
// Store a handle to the BluetoothServerSocket, so we can use it after
|
||||
// removing the entry from bluetooth_server_sockets_; making it scoped
|
||||
// is a bonus that takes care of deallocation before we leave this method.
|
||||
ScopedPtr<Ptr<BluetoothServerSocket>> scoped_listening_socket(
|
||||
listening_socket_iter->second);
|
||||
|
||||
// Regardless of whether or not we fail to close the existing
|
||||
// BluetoothServerSocket, remove it from bluetooth_server_sockets_ so that it
|
||||
// frees up this service for another round.
|
||||
bluetooth_server_sockets_.erase(listening_socket_iter);
|
||||
|
||||
// Finally, close the BluetoothServerSocket.
|
||||
Exception::Value e = scoped_listening_socket->close();
|
||||
if (Exception::NONE != e) {
|
||||
if (Exception::IO == e) {
|
||||
// TODO(reznor): log.atSevere().withCause(e).log("Failed to close
|
||||
// Bluetooth server socket for %s.", serviceName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
Ptr<BluetoothSocket> BluetoothClassic<Platform>::connect(
|
||||
Ptr<BluetoothDevice> bluetooth_device, const string& service_name) {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
if (bluetooth_device.isNull() || service_name.empty()) {
|
||||
// TODO(reznor): log.atSevere().log("Refusing to create client Bluetooth
|
||||
// socket because at least one of bluetoothDevice or serviceName is null.");
|
||||
return Ptr<BluetoothSocket>();
|
||||
}
|
||||
|
||||
if (!bluetooth_radio_->isEnabled()) {
|
||||
// TODO(reznor): log.atSevere().log("Can't create client Bluetooth socket to
|
||||
// %s because Bluetooth isn't enabled.", bluetoothSocketName);
|
||||
return Ptr<BluetoothSocket>();
|
||||
}
|
||||
|
||||
if (!isAvailable()) {
|
||||
// TODO(reznor): log.atSevere().log("Can't create client Bluetooth socket to
|
||||
// %s because Bluetooth isn't available.", bluetoothSocketName);
|
||||
return Ptr<BluetoothSocket>();
|
||||
}
|
||||
|
||||
// WARNING WARNING WARNING
|
||||
//
|
||||
// This block deviates from the corresponding Java code.
|
||||
//
|
||||
// In Java, we pause an in-progress discovery before attempting this
|
||||
// connection, and then resume it after, but the memory management of the
|
||||
// DiscoveredDeviceCallback is complicated in C++, and would need a severe
|
||||
// deviation from the Java code, so we're choosing the lesser of 2 evils, and
|
||||
// introducing this (simplifying) deviation instead -- also, this deviation is
|
||||
// fairly inconsequential since we don't yet have a use-case that needs a
|
||||
// device that:
|
||||
//
|
||||
// a) uses the C++ code,
|
||||
// b) has Bluetooth Classic support, and
|
||||
// c) plays the role of Discoverer.
|
||||
ExceptionOr<Ptr<BluetoothSocket>> bluetooth_socket =
|
||||
bluetooth_classic_medium_->connectToService(
|
||||
bluetooth_device, generateUUIDFromString(service_name));
|
||||
if (!bluetooth_socket.ok()) {
|
||||
if (Exception::IO == bluetooth_socket.exception()) {
|
||||
// TODO(reznor): log.atSevere().log("Failed to connect via Bluetooth
|
||||
// socket to %s.", bluetoothSocketName);
|
||||
}
|
||||
return Ptr<BluetoothSocket>();
|
||||
}
|
||||
|
||||
return bluetooth_socket.result();
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
string BluetoothClassic<Platform>::generateUUIDFromString(const string& data) {
|
||||
return UUID<Platform>(data).str();
|
||||
}
|
||||
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
@@ -0,0 +1,169 @@
|
||||
#ifndef CORE_INTERNAL_MEDIUMS_BLUETOOTH_CLASSIC_H_
|
||||
#define CORE_INTERNAL_MEDIUMS_BLUETOOTH_CLASSIC_H_
|
||||
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
|
||||
#include "core/internal/mediums/bluetooth_radio.h"
|
||||
#include "core/internal/mediums/utils.h"
|
||||
#include "platform/api/bluetooth_adapter.h"
|
||||
#include "platform/api/bluetooth_classic.h"
|
||||
#include "platform/api/lock.h"
|
||||
#include "platform/api/multi_thread_executor.h"
|
||||
#include "platform/byte_array.h"
|
||||
#include "platform/port/string.h"
|
||||
#include "platform/ptr.h"
|
||||
#include "platform/runnable.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
|
||||
template <typename Platform>
|
||||
class BluetoothClassic {
|
||||
public:
|
||||
explicit BluetoothClassic(Ptr<BluetoothRadio<Platform>> bluetooth_radio);
|
||||
~BluetoothClassic();
|
||||
|
||||
bool isAvailable();
|
||||
|
||||
bool turnOnDiscoverability(const string& device_name);
|
||||
void turnOffDiscoverability();
|
||||
|
||||
// Callback that is invoked when a nearby Bluetooth device is discovered.
|
||||
class DiscoveredDeviceCallback {
|
||||
public:
|
||||
virtual ~DiscoveredDeviceCallback() {}
|
||||
|
||||
virtual void onDeviceDiscovered(Ptr<BluetoothDevice> device) = 0;
|
||||
virtual void onDeviceNameChanged(Ptr<BluetoothDevice> device) = 0;
|
||||
virtual void onDeviceLost(Ptr<BluetoothDevice> device) = 0;
|
||||
};
|
||||
|
||||
bool startDiscovery(Ptr<DiscoveredDeviceCallback> discovered_device_callback);
|
||||
void stopDiscovery();
|
||||
|
||||
// Callback that is invoked when a new connection is accepted.
|
||||
class AcceptedConnectionCallback {
|
||||
public:
|
||||
virtual ~AcceptedConnectionCallback() {}
|
||||
|
||||
virtual void onConnectionAccepted(Ptr<BluetoothSocket> socket) = 0;
|
||||
};
|
||||
|
||||
bool startAcceptingConnections(
|
||||
const string& service_name,
|
||||
Ptr<AcceptedConnectionCallback> accepted_connection_callback);
|
||||
bool isAcceptingConnections(const string& service_name);
|
||||
void stopAcceptingConnections(const string& service_name);
|
||||
|
||||
Ptr<BluetoothSocket> connect(Ptr<BluetoothDevice> bluetooth_device,
|
||||
const string& service_name);
|
||||
|
||||
private:
|
||||
class BluetoothDiscoveryCallback
|
||||
: public BluetoothClassicMedium::DiscoveryCallback {
|
||||
public:
|
||||
explicit BluetoothDiscoveryCallback(
|
||||
Ptr<DiscoveredDeviceCallback> discovered_device_callback)
|
||||
: discovered_device_callback_(discovered_device_callback) {}
|
||||
~BluetoothDiscoveryCallback() override {
|
||||
// Nothing to do.
|
||||
}
|
||||
|
||||
void onDeviceDiscovered(Ptr<BluetoothDevice> bluetooth_device) override {
|
||||
discovered_device_callback_->onDeviceDiscovered(bluetooth_device);
|
||||
}
|
||||
void onDeviceNameChanged(Ptr<BluetoothDevice> bluetooth_device) override {
|
||||
discovered_device_callback_->onDeviceNameChanged(bluetooth_device);
|
||||
}
|
||||
void onDeviceLost(Ptr<BluetoothDevice> bluetooth_device) override {
|
||||
discovered_device_callback_->onDeviceLost(bluetooth_device);
|
||||
}
|
||||
|
||||
private:
|
||||
// This could well have been a ScopedPtr, with BluetoothDiscoveryCallback in
|
||||
// turn being owned by ScanInfo (and it would have been cleaner overall,
|
||||
// since the chain of wrapped callbacks starting from
|
||||
// BluetoothDiscoveryCallback would then destruct like a stack of dominoes
|
||||
// falling, triggered by the destruction of ScanInfo), but we instead give
|
||||
// ownership of this DiscoveredDeviceCallback *and*
|
||||
// BluetoothDiscoveryCallback to ScanInfo, to maintain compatibility with
|
||||
// the Java code.
|
||||
Ptr<DiscoveredDeviceCallback> discovered_device_callback_;
|
||||
};
|
||||
|
||||
struct ScanInfo {
|
||||
ScanInfo(Ptr<DiscoveredDeviceCallback> discovered_device_callback,
|
||||
Ptr<BluetoothDiscoveryCallback> bluetooth_discovery_callback)
|
||||
: discovered_device_callback(discovered_device_callback),
|
||||
bluetooth_discovery_callback(bluetooth_discovery_callback) {}
|
||||
~ScanInfo() {
|
||||
// Nothing to do (the ScopedPtr members take care of themselves).
|
||||
}
|
||||
|
||||
// Stores the DiscoveredDeviceCallback passed in to startDiscovery() by
|
||||
// clients so that we can internally stop and start Bluetooth scans
|
||||
// transparently as needed (for example, when a call to connect() is
|
||||
// invoked).
|
||||
ScopedPtr<Ptr<DiscoveredDeviceCallback>> discovered_device_callback;
|
||||
// The ordering of bluetooth_discovery_callback_ coming after
|
||||
// discovered_device_callback_ is very deliberate --
|
||||
// bluetooth_discovery_callback_ contains a reference to
|
||||
// discovered_device_callback_, so it should be destroyed first.
|
||||
ScopedPtr<Ptr<BluetoothDiscoveryCallback>> bluetooth_discovery_callback;
|
||||
};
|
||||
|
||||
static string generateUUIDFromString(const string& data);
|
||||
|
||||
static const std::int32_t kMaxConcurrentAcceptLoops;
|
||||
|
||||
bool isDiscoverable() const;
|
||||
bool modifyDeviceName(const string& device_name);
|
||||
bool modifyScanMode(BluetoothAdapter::ScanMode::Value scan_mode);
|
||||
void restoreScanMode();
|
||||
void restoreDeviceName();
|
||||
bool isDiscovering() const;
|
||||
|
||||
// ------------ GENERAL ------------
|
||||
|
||||
ScopedPtr<Ptr<Lock>> lock_;
|
||||
|
||||
// ------------ CORE BLUETOOTH ------------
|
||||
|
||||
Ptr<BluetoothRadio<Platform>> bluetooth_radio_;
|
||||
ScopedPtr<Ptr<BluetoothAdapter>> bluetooth_adapter_;
|
||||
// The underlying, per-platform implementation.
|
||||
ScopedPtr<Ptr<BluetoothClassicMedium>> bluetooth_classic_medium_;
|
||||
|
||||
// ------------ DISCOVERY ------------
|
||||
|
||||
// A bundle of state required to do a Bluetooth Classic scan. When non-null,
|
||||
// we are currently performing a Bluetooth scan.
|
||||
Ptr<ScanInfo> scan_info_;
|
||||
|
||||
// ------------ ADVERTISING ------------
|
||||
|
||||
// The original scan mode (that controls visibility to scanners) of the device
|
||||
// before we modified it. Restored when we stop advertising.
|
||||
BluetoothAdapter::ScanMode::Value original_scan_mode_;
|
||||
// The original Bluetooth device name, before we modified it. If non-null, we
|
||||
// are currently Bluetooth discoverable. Restored when we stop advertising.
|
||||
Ptr<string> original_device_name_;
|
||||
// A thread pool dedicated to running all the accept loops from
|
||||
// startAcceptingConnections().
|
||||
ScopedPtr<Ptr<typename Platform::MultiThreadExecutorType>>
|
||||
accept_loops_thread_pool_;
|
||||
// A map of service name -> ServerSocket. While this map is non-empty, we
|
||||
// are currently listening for incoming connections.
|
||||
typedef std::map<string, Ptr<BluetoothServerSocket>> BluetoothServerSocketMap;
|
||||
BluetoothServerSocketMap bluetooth_server_sockets_;
|
||||
};
|
||||
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
|
||||
#include "core/internal/mediums/bluetooth_classic.cc"
|
||||
|
||||
#endif // CORE_INTERNAL_MEDIUMS_BLUETOOTH_CLASSIC_H_
|
||||
@@ -0,0 +1,122 @@
|
||||
#include "core/internal/mediums/bluetooth_radio.h"
|
||||
|
||||
#include "platform/exception.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
|
||||
template <typename Platform>
|
||||
std::int64_t BluetoothRadio<Platform>::kPauseBetweenToggleDurationMillis = 3000;
|
||||
|
||||
template <typename Platform>
|
||||
BluetoothRadio<Platform>::BluetoothRadio()
|
||||
: bluetooth_adapter_(Platform::createBluetoothAdapter()),
|
||||
thread_utils_(Platform::createThreadUtils()),
|
||||
originally_enabled_() {
|
||||
if (bluetooth_adapter_.isNull()) {
|
||||
// TODO(reznor): log.atSevere().log("Failed to retrieve default
|
||||
// BluetoothAdapter, Bluetooth is unsupported.");
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
BluetoothRadio<Platform>::~BluetoothRadio() {
|
||||
// We never enabled Bluetooth, nothing to do.
|
||||
if (originally_enabled_.isNull()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Make sure we cleanup the one non-ScopedPtr member before we leave the
|
||||
// destructor.
|
||||
ScopedPtr<Ptr<AtomicBoolean> > scoped_originally_enabled(originally_enabled_);
|
||||
|
||||
// Toggle Bluetooth regardless of our original state. Some devices/chips can
|
||||
// start to freak out after some time (e.g. b/37775337), and this helps to
|
||||
// ensure BT resets properly.
|
||||
toggle();
|
||||
|
||||
if (!setBluetoothState(originally_enabled_->get())) {
|
||||
// TODO(reznor): log.atWarning().log("Failed to turn Bluetooth back to its
|
||||
// original state.");
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BluetoothRadio<Platform>::enable() {
|
||||
if (!saveOriginalState()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return setBluetoothState(true);
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BluetoothRadio<Platform>::disable() {
|
||||
if (!saveOriginalState()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return setBluetoothState(false);
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BluetoothRadio<Platform>::isEnabled() {
|
||||
return !bluetooth_adapter_.isNull() && isInDesiredState(true);
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
void BluetoothRadio<Platform>::toggle() {
|
||||
if (!saveOriginalState()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!setBluetoothState(false)) {
|
||||
// TODO(reznor): log.atWarning().log("Failed to turn Bluetooth off while
|
||||
// toggling state.");
|
||||
}
|
||||
|
||||
if (Exception::INTERRUPTED ==
|
||||
thread_utils_->sleep(kPauseBetweenToggleDurationMillis)) {
|
||||
// TODO(reznor): log.atSevere().withCause(e).log("Interrupted while waiting
|
||||
// in between a Bluetooth toggle.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!setBluetoothState(true)) {
|
||||
// TODO(reznor): log.atWarning().log("Failed to turn Bluetooth on while
|
||||
// toggling state.");
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BluetoothRadio<Platform>::setBluetoothState(bool enable) {
|
||||
return bluetooth_adapter_->setStatus(
|
||||
enable ? BluetoothAdapter::Status::ENABLED
|
||||
: BluetoothAdapter::Status::DISABLED);
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BluetoothRadio<Platform>::isInDesiredState(bool should_be_enabled) const {
|
||||
return ((should_be_enabled && bluetooth_adapter_->isEnabled()) ||
|
||||
(!should_be_enabled && !bluetooth_adapter_->isEnabled()));
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool BluetoothRadio<Platform>::saveOriginalState() {
|
||||
if (bluetooth_adapter_.isNull()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If we haven't saved the original state of the radio, save it.
|
||||
if (originally_enabled_.isNull()) {
|
||||
originally_enabled_ =
|
||||
Platform::createAtomicBoolean(bluetooth_adapter_->isEnabled());
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
@@ -0,0 +1,69 @@
|
||||
#ifndef CORE_INTERNAL_MEDIUMS_BLUETOOTH_RADIO_H_
|
||||
#define CORE_INTERNAL_MEDIUMS_BLUETOOTH_RADIO_H_
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "platform/api/atomic_boolean.h"
|
||||
#include "platform/api/bluetooth_adapter.h"
|
||||
#include "platform/api/thread_utils.h"
|
||||
#include "platform/ptr.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
|
||||
// Provides the operations that can be performed on the Bluetooth radio.
|
||||
template <typename Platform>
|
||||
class BluetoothRadio {
|
||||
public:
|
||||
BluetoothRadio();
|
||||
// Reverts the Bluetooth radio to its original state.
|
||||
~BluetoothRadio();
|
||||
|
||||
// Enables Bluetooth.
|
||||
//
|
||||
// This must be called before attempting to invoke any other methods of
|
||||
// this class.
|
||||
//
|
||||
// Returns true if enabled successfully.
|
||||
bool enable();
|
||||
// Disables Bluetooth.
|
||||
//
|
||||
// Returns true if disabled successfully.
|
||||
bool disable();
|
||||
// Returns true if the Bluetooth radio is currently enabled.
|
||||
bool isEnabled();
|
||||
|
||||
void toggle();
|
||||
|
||||
private:
|
||||
static std::int64_t kPauseBetweenToggleDurationMillis;
|
||||
|
||||
bool setBluetoothState(bool enable);
|
||||
bool isInDesiredState(bool should_be_enabled) const;
|
||||
// To be called in enable(), disable(), and toggle(). This will remember the
|
||||
// original state of the radio before any radio state has been modified.
|
||||
// Returns false if Bluetooth doesn't exist on the device and the state cannot
|
||||
// be obtained.
|
||||
bool saveOriginalState();
|
||||
|
||||
// Null if the device does not support Bluetooth.
|
||||
ScopedPtr<Ptr<BluetoothAdapter>> bluetooth_adapter_;
|
||||
ScopedPtr<Ptr<ThreadUtils>> thread_utils_;
|
||||
// The Bluetooth radio's original state, before we modified it. True if
|
||||
// originally enabled, false if originally disabled, null if we never modified
|
||||
// the radio state. We restore the radio to its original state in the
|
||||
// destructor.
|
||||
//
|
||||
// This is a Ptr instead of a ScopedPtr because it's lazily initialized
|
||||
// (and ScopedPtr doesn't support re-assignment).
|
||||
Ptr<AtomicBoolean> originally_enabled_;
|
||||
};
|
||||
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
|
||||
#include "core/internal/mediums/bluetooth_radio.cc"
|
||||
|
||||
#endif // CORE_INTERNAL_MEDIUMS_BLUETOOTH_RADIO_H_
|
||||
@@ -0,0 +1,32 @@
|
||||
#ifndef CORE_INTERNAL_MEDIUMS_DISCOVERED_PERIPHERAL_CALLBACK_H_
|
||||
#define CORE_INTERNAL_MEDIUMS_DISCOVERED_PERIPHERAL_CALLBACK_H_
|
||||
|
||||
#include "core/internal/mediums/ble_peripheral.h"
|
||||
#include "platform/byte_array.h"
|
||||
#include "platform/port/string.h"
|
||||
#include "platform/ptr.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
/** Callback that is invoked when a {@link BLEPeripheral} is discovered. */
|
||||
class DiscoveredPeripheralCallback {
|
||||
public:
|
||||
virtual ~DiscoveredPeripheralCallback() {}
|
||||
|
||||
virtual void onPeripheralDiscovered(Ptr<BLEPeripheral> ble_peripheral,
|
||||
const string& service_id,
|
||||
ConstPtr<ByteArray> advertisement,
|
||||
bool is_fast_advertisement) = 0;
|
||||
virtual void onPeripheralLost(Ptr<BLEPeripheral> ble_peripheral,
|
||||
const string& service_id);
|
||||
};
|
||||
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
|
||||
#endif // CORE_INTERNAL_MEDIUMS_DISCOVERED_PERIPHERAL_CALLBACK_H_
|
||||
@@ -0,0 +1,744 @@
|
||||
#include "core/internal/mediums/discovered_peripheral_tracker.h"
|
||||
|
||||
#include "core/internal/mediums/ble_packet.h"
|
||||
#include "core/internal/mediums/bloom_filter.h"
|
||||
#include "core/internal/mediums/utils.h"
|
||||
#include "platform/synchronized.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
namespace dpt {
|
||||
|
||||
template <typename K, typename V>
|
||||
void eraseOwnedPtrFromMap(std::map<K, V>& m, const K& k) {
|
||||
typename std::map<K, V>::iterator it = m.find(k);
|
||||
if (it != m.end()) {
|
||||
it->second.destroy();
|
||||
m.erase(it);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename K, typename V>
|
||||
void eraseAllOwnedPtrsFromMap(std::map<K, Ptr<V>>& m) {
|
||||
for (typename std::map<K, Ptr<V>>::iterator it = m.begin(); it != m.end();
|
||||
++it) {
|
||||
it->second.destroy();
|
||||
}
|
||||
m.clear();
|
||||
}
|
||||
|
||||
template <typename K, typename V>
|
||||
V removeOwnedPtrFromMap(std::map<K, V>& m, const K& k) {
|
||||
V removed_ptr;
|
||||
typename std::map<K, V>::iterator it = m.find(k);
|
||||
if (it != m.end()) {
|
||||
removed_ptr = it->second;
|
||||
m.erase(it);
|
||||
}
|
||||
return removed_ptr;
|
||||
}
|
||||
|
||||
} // namespace dpt
|
||||
|
||||
// The maximum number of advertisement slots to assume if we don't know the
|
||||
// exact number.
|
||||
template <typename Platform>
|
||||
const std::int32_t DiscoveredPeripheralTracker<Platform>::kMaxSlots = 10;
|
||||
|
||||
// Amount of time to wait before attempting a connection. This is needed to
|
||||
// prevent the GATT server from operation overload if we just came from a GATT
|
||||
// discovery.
|
||||
template <typename Platform>
|
||||
const std::int64_t
|
||||
DiscoveredPeripheralTracker<Platform>::kMinConnectionDelayMillis =
|
||||
5 * 1000; // 5 seconds
|
||||
|
||||
template <typename Platform>
|
||||
const char* DiscoveredPeripheralTracker<Platform>::kCopresenceServiceUuid =
|
||||
"0000FEF3-0000-1000-8000-00805F9B34FB";
|
||||
|
||||
template <typename Platform>
|
||||
DiscoveredPeripheralTracker<Platform>::DiscoveredPeripheralTracker()
|
||||
: lock_(Platform::createLock()),
|
||||
thread_utils_(Platform::createThreadUtils()),
|
||||
system_clock_(Platform::createSystemClock()),
|
||||
hash_utils_(Platform::createHashUtils()),
|
||||
discovered_peripheral_callbacks_(),
|
||||
lost_entity_trackers_(),
|
||||
fast_advertisement_service_uuids_(),
|
||||
advertisement_read_results_(),
|
||||
gatt_advertisements_(),
|
||||
advertisement_service_ids_(),
|
||||
advertisement_headers_(),
|
||||
mac_addresses_() {}
|
||||
|
||||
template <typename Platform>
|
||||
DiscoveredPeripheralTracker<Platform>::~DiscoveredPeripheralTracker() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
mac_addresses_.clear();
|
||||
advertisement_headers_.clear();
|
||||
advertisement_service_ids_.clear();
|
||||
// gatt_advertisements_ maps a string to a Ptr to a set of ConstPtrs. We do
|
||||
// not go and iterate through every set because those values are RefCounted.
|
||||
dpt::eraseAllOwnedPtrsFromMap(gatt_advertisements_);
|
||||
dpt::eraseAllOwnedPtrsFromMap(advertisement_read_results_);
|
||||
fast_advertisement_service_uuids_.clear();
|
||||
dpt::eraseAllOwnedPtrsFromMap(lost_entity_trackers_);
|
||||
dpt::eraseAllOwnedPtrsFromMap(discovered_peripheral_callbacks_);
|
||||
}
|
||||
|
||||
// Starts tracking discoveries for a particular service ID.
|
||||
template <typename Platform>
|
||||
void DiscoveredPeripheralTracker<Platform>::startTracking(
|
||||
const string& service_id,
|
||||
Ptr<DiscoveredPeripheralCallback> discovered_peripheral_callback,
|
||||
const string& fast_advertisement_service_uuid) {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
dpt::eraseOwnedPtrFromMap(discovered_peripheral_callbacks_, service_id);
|
||||
discovered_peripheral_callbacks_.insert(
|
||||
std::make_pair(service_id, discovered_peripheral_callback));
|
||||
|
||||
// We create a new LostEntityTracker because any pre-existing ones only
|
||||
// contain stale advertisements. LostEntityTracker also doesn't provide a
|
||||
// reset method, so creating a new one is the right way to go.
|
||||
dpt::eraseOwnedPtrFromMap(lost_entity_trackers_, service_id);
|
||||
lost_entity_trackers_.insert(std::make_pair(
|
||||
service_id,
|
||||
MakePtr(new LostEntityTracker<Platform, BLEAdvertisement>())));
|
||||
|
||||
if (!fast_advertisement_service_uuid.empty()) {
|
||||
fast_advertisement_service_uuids_.erase(service_id);
|
||||
fast_advertisement_service_uuids_.insert(
|
||||
std::make_pair(service_id, fast_advertisement_service_uuid));
|
||||
}
|
||||
|
||||
// Clear all of the GATT read results. With this cleared, we will now attempt
|
||||
// to reconnect to every peripheral we see, giving us a chance to search for
|
||||
// the new service we're now tracking.
|
||||
// See the documentation of advertisementReadResults for more information.
|
||||
dpt::eraseAllOwnedPtrsFromMap(advertisement_read_results_);
|
||||
|
||||
// Remove stale data from any previous sessions.
|
||||
clearDataForServiceId(service_id);
|
||||
}
|
||||
|
||||
// Stops tracking discoveries for a particular service ID.
|
||||
template <typename Platform>
|
||||
void DiscoveredPeripheralTracker<Platform>::stopTracking(
|
||||
const string& service_id) {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
fast_advertisement_service_uuids_.erase(service_id);
|
||||
dpt::eraseOwnedPtrFromMap(lost_entity_trackers_, service_id);
|
||||
dpt::eraseOwnedPtrFromMap(discovered_peripheral_callbacks_, service_id);
|
||||
}
|
||||
|
||||
// Processes a found BLE advertisement.
|
||||
template <typename Platform>
|
||||
void DiscoveredPeripheralTracker<Platform>::processFoundBleAdvertisement(
|
||||
Ptr<BLEPeripheralV2> ble_peripheral,
|
||||
ConstPtr<BLEAdvertisementData> advertisement_data,
|
||||
Ptr<GattAdvertisementFetcher> gatt_advertisement_fetcher) {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
// Avoid leaks.
|
||||
ScopedPtr<ConstPtr<BLEAdvertisementData>> scoped_advertisement_data(
|
||||
advertisement_data);
|
||||
ScopedPtr<Ptr<GattAdvertisementFetcher>> scoped_gatt_advertisement_fetcher(
|
||||
gatt_advertisement_fetcher);
|
||||
|
||||
if (getTrackedServiceIds().empty()) {
|
||||
// TODO(ahlee) logger.atVerbose().log("Ignoring BLE advertisement header
|
||||
// because we are not tracking any service IDs.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (ble_peripheral.isNull() || scoped_advertisement_data.isNull()) {
|
||||
// TODO(ahlee) logger.atVerbose().log("Ignoring BLE advertisement header
|
||||
// because the given BleSighting is null or incomplete.");
|
||||
return;
|
||||
}
|
||||
|
||||
handleFastAdvertisement(ble_peripheral, scoped_advertisement_data.get());
|
||||
handleAdvertisementHeader(ble_peripheral, scoped_advertisement_data.get(),
|
||||
scoped_gatt_advertisement_fetcher.get());
|
||||
}
|
||||
|
||||
// Processes the set of lost GATT advertisements and notifies the client of any
|
||||
// lost peripherals.
|
||||
template <typename Platform>
|
||||
void DiscoveredPeripheralTracker<Platform>::processLostGattAdvertisements() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
std::set<string> tracked_service_ids = getTrackedServiceIds();
|
||||
for (typename std::set<string>::iterator tsi_it = tracked_service_ids.begin();
|
||||
tsi_it != tracked_service_ids.end(); ++tsi_it) {
|
||||
BLEAdvertisementSet lost_gatt_advertisements =
|
||||
lost_entity_trackers_.find(*tsi_it)->second->computeLostEntities();
|
||||
|
||||
// Clear the map state for each lost GATT advertisement and report it to the
|
||||
// client.
|
||||
for (BLEAdvertisementSet::iterator lga_it =
|
||||
lost_gatt_advertisements.begin();
|
||||
lga_it != lost_gatt_advertisements.end(); ++lga_it) {
|
||||
clearGattAdvertisement(*lga_it);
|
||||
discovered_peripheral_callbacks_.find(*tsi_it)->second->onPeripheralLost(
|
||||
generateBlePeripheral(*lga_it), *tsi_it);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
Ptr<BLEPeripheral> DiscoveredPeripheralTracker<Platform>::generateBlePeripheral(
|
||||
ConstPtr<BLEAdvertisement> gatt_advertisement) {
|
||||
// TODO(ahlee): Reminder to port over deviceToken change.
|
||||
return MakePtr(new BLEPeripheral(BLEAdvertisement::toBytes(
|
||||
gatt_advertisement->getVersion(), gatt_advertisement->getSocketVersion(),
|
||||
gatt_advertisement->getServiceIdHash(), gatt_advertisement->getData())));
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
std::set<string> DiscoveredPeripheralTracker<Platform>::getTrackedServiceIds() {
|
||||
std::set<string> tracked_service_ids;
|
||||
for (DiscoveredPeripheralCallbackMap::iterator dpc_it =
|
||||
discovered_peripheral_callbacks_.begin();
|
||||
dpc_it != discovered_peripheral_callbacks_.end(); ++dpc_it) {
|
||||
tracked_service_ids.insert(dpc_it->first);
|
||||
}
|
||||
return tracked_service_ids;
|
||||
}
|
||||
|
||||
// Note: There is no C++ equivalent for getTrackedGattAdvertisements() because
|
||||
// we make a copy of the subset of the keys in directly in
|
||||
// clearDataForServiceId().
|
||||
|
||||
template <typename Platform>
|
||||
void DiscoveredPeripheralTracker<Platform>::clearDataForServiceId(
|
||||
const string& service_id) {
|
||||
BLEAdvertisementSet gatt_advertisements_to_clear;
|
||||
for (AdvertisementServiceIdMap::iterator it =
|
||||
advertisement_service_ids_.begin();
|
||||
it != advertisement_service_ids_.end(); ++it) {
|
||||
if (it->second != service_id) {
|
||||
continue;
|
||||
}
|
||||
gatt_advertisements_to_clear.insert(it->first);
|
||||
}
|
||||
|
||||
for (BLEAdvertisementSet::iterator it = gatt_advertisements_to_clear.begin();
|
||||
it != gatt_advertisements_to_clear.end(); ++it) {
|
||||
clearGattAdvertisement(*it);
|
||||
}
|
||||
}
|
||||
|
||||
// Clears out all data related to the provided GATT advertisement. This
|
||||
// includes:
|
||||
// 1. Removing the GATT advertisement from GATT advertisement keyed maps. This
|
||||
// includes advertisementServiceIds, AdvertisementHeaders, and
|
||||
// macAddresses.
|
||||
// 2. Removing the corresponding advertisement header from
|
||||
// advertisementReadResults.
|
||||
// 3. Removing the corresponding advertisement header from gattAdvertisements,
|
||||
// only if there are no remaining GATT advertisements related to that
|
||||
// header.
|
||||
template <typename Platform>
|
||||
void DiscoveredPeripheralTracker<Platform>::clearGattAdvertisement(
|
||||
ConstPtr<BLEAdvertisement> gatt_advertisement) {
|
||||
// BLEAdvertisement is RefCounted, so it does not need to be scoped.
|
||||
advertisement_service_ids_.erase(gatt_advertisement);
|
||||
mac_addresses_.erase(gatt_advertisement);
|
||||
|
||||
ConstPtr<BLEAdvertisementHeader> advertisement_header =
|
||||
dpt::removeOwnedPtrFromMap(advertisement_headers_, gatt_advertisement);
|
||||
typename GattAdvertisementMap::iterator ga_it =
|
||||
gatt_advertisements_.find(advertisement_header);
|
||||
if (ga_it != gatt_advertisements_.end()) {
|
||||
// Remove the GATT advertisement from the advertisement header it's
|
||||
// associated with.
|
||||
Ptr<BLEAdvertisementSet> header_gatt_advertisements = ga_it->second;
|
||||
header_gatt_advertisements->erase(gatt_advertisement);
|
||||
|
||||
// Unconditionally remove the header from advertisementReadResults so we
|
||||
// can attempt to reread the GATT advertisement if they return.
|
||||
dpt::eraseOwnedPtrFromMap(advertisement_read_results_,
|
||||
advertisement_header);
|
||||
|
||||
// If there are no more tracked GATT advertisements under this header, go
|
||||
// ahead and remove it from gattAdvertisements.
|
||||
if (header_gatt_advertisements->empty()) {
|
||||
dpt::eraseOwnedPtrFromMap(gatt_advertisements_, advertisement_header);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
void DiscoveredPeripheralTracker<Platform>::handleFastAdvertisement(
|
||||
Ptr<BLEPeripheralV2> ble_peripheral,
|
||||
ConstPtr<BLEAdvertisementData> advertisement_data) {
|
||||
// Extract the fast advertisement bytes, if any.
|
||||
ScopedPtr<ConstPtr<ByteArray>> fast_advertisement_bytes(
|
||||
extractFastAdvertisementBytes(advertisement_data));
|
||||
if (fast_advertisement_bytes.isNull()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Create a header tied to this fast advertisement. This helps us track the
|
||||
// advertisement when reporting it as lost or connecting.
|
||||
/* RefCounted */ ConstPtr<BLEAdvertisementHeader> fast_advertisement_header =
|
||||
createFastAdvertisementHeader(fast_advertisement_bytes.get());
|
||||
|
||||
// Process the fast advertisement like we would a GATT advertisement and
|
||||
// insert a placeholder AdvertisementReadResult.
|
||||
dpt::eraseOwnedPtrFromMap(advertisement_read_results_,
|
||||
fast_advertisement_header);
|
||||
advertisement_read_results_.insert(
|
||||
std::make_pair(fast_advertisement_header,
|
||||
MakePtr(new AdvertisementReadResult<Platform>())));
|
||||
|
||||
std::set<ConstPtr<ByteArray>> fast_advertisement_bytes_set;
|
||||
fast_advertisement_bytes_set.insert(fast_advertisement_bytes.get());
|
||||
handleRawGattAdvertisements(fast_advertisement_header,
|
||||
fast_advertisement_bytes_set,
|
||||
/* are_fast_advertisements= */ true);
|
||||
updateCommonStateForFoundBleAdvertisement(fast_advertisement_header,
|
||||
ble_peripheral->getId());
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
void DiscoveredPeripheralTracker<Platform>::handleAdvertisementHeader(
|
||||
Ptr<BLEPeripheralV2> ble_peripheral,
|
||||
ConstPtr<BLEAdvertisementData> advertisement_data,
|
||||
Ptr<GattAdvertisementFetcher> gatt_advertisement_fetcher) {
|
||||
// Attempt to parse the advertisement header.
|
||||
/* RefCounted */ ConstPtr<BLEAdvertisementHeader> advertisement_header =
|
||||
BLEAdvertisementHeader::fromString(
|
||||
extractAdvertisementHeaderBytes(ble_peripheral, advertisement_data));
|
||||
if (advertisement_header.isNull()) {
|
||||
// TODO(ahlee) logger.atVerbose().log("Failed to deserialize BLE
|
||||
// advertisement header %s. Ignoring.",
|
||||
// bytesToString(advertisementHeaderBytes));
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if the advertisement header contains a service ID we're tracking.
|
||||
if (!isInterestingAdvertisementHeader(advertisement_header)) {
|
||||
// TODO(ahlee) logger.atVerbose().log("Ignoring BLE advertisement header %s
|
||||
// because it does not contain any service IDs we're interested in.",
|
||||
// advertisementHeader);
|
||||
return;
|
||||
}
|
||||
|
||||
// Determine whether or not we need to read a fresh GATT advertisement.
|
||||
if (shouldReadFromAdvertisementGattServer(advertisement_header)) {
|
||||
// Determine whether or not we need to read a fresh GATT advertisement.
|
||||
std::set<ConstPtr<ByteArray>> raw_gatt_advertisements =
|
||||
fetchRawGattAdvertisements(ble_peripheral, advertisement_header,
|
||||
gatt_advertisement_fetcher);
|
||||
if (!raw_gatt_advertisements.empty()) {
|
||||
handleRawGattAdvertisements(advertisement_header, raw_gatt_advertisements,
|
||||
/* are_fast_advertisements= */ false);
|
||||
}
|
||||
}
|
||||
|
||||
// Regardless of whether or not we read a new GATT advertisement, the maps
|
||||
// should now be up-to-date. With this information, do some general
|
||||
// housekeeping.
|
||||
updateCommonStateForFoundBleAdvertisement(
|
||||
advertisement_header, /* mac_address= */ ble_peripheral->getId());
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
string DiscoveredPeripheralTracker<Platform>::extractAdvertisementHeaderBytes(
|
||||
Ptr<BLEPeripheralV2> ble_peripheral,
|
||||
ConstPtr<BLEAdvertisementData> advertisement_data) {
|
||||
ConstPtr<ByteArray> service_data;
|
||||
std::map<string, ConstPtr<ByteArray>>::const_iterator sd_it =
|
||||
advertisement_data->service_data.find(kCopresenceServiceUuid);
|
||||
if (sd_it != advertisement_data->service_data.end()) {
|
||||
service_data = sd_it->second;
|
||||
}
|
||||
const string& local_name = advertisement_data->local_name; // alias
|
||||
|
||||
// A valid advertisement header lives in either the local name (iOS) or the
|
||||
// service data (Android).
|
||||
if (!service_data.isNull()) {
|
||||
// TODO(ahlee) logger.atVerbose().log("Service data found on possible
|
||||
// Android BLE peripheral at address %s",
|
||||
// bleSighting.getDevice().getAddress());
|
||||
return string(service_data->getData(), service_data->size());
|
||||
} else if (!local_name.empty()) {
|
||||
// TODO(ahlee) logger.atVerbose().log("Local name found on possible iOS BLE
|
||||
// peripheral at address %s", bleSighting.getDevice().getAddress());
|
||||
return local_name;
|
||||
} else {
|
||||
// iOS peripherals have a bug where the local name sometimes doesn't appear.
|
||||
// In that case, we should still take a look at the advertisement in case
|
||||
// there's something valuable on the peripheral's GATT server.
|
||||
|
||||
// TODO(ahlee) logger.atVerbose().log("BLE advertisement found with no
|
||||
// service data or local name from BLE peripheral at address %s (could be a
|
||||
// buggy iOS peripheral with a missing local name).",
|
||||
// bleSighting.getDevice().getAddress());
|
||||
|
||||
// Create a phony BloomFilter that always contains the service ID we're
|
||||
// looking for.
|
||||
return createDummyAdvertisementHeaderBytes(ble_peripheral);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
ConstPtr<ByteArray>
|
||||
DiscoveredPeripheralTracker<Platform>::extractFastAdvertisementBytes(
|
||||
ConstPtr<BLEAdvertisementData> advertisement_data) {
|
||||
ConstPtr<ByteArray> fast_advertisement_bytes;
|
||||
// Iterate through all tracked service IDs to see if any of their fast
|
||||
// advertisements are contained within this BLE advertisement.
|
||||
std::set<string> tracked_service_ids = getTrackedServiceIds();
|
||||
for (typename std::set<string>::iterator tsi_it = tracked_service_ids.begin();
|
||||
tsi_it != tracked_service_ids.end(); ++tsi_it) {
|
||||
// First, check if a service UUID is tied to this service ID.
|
||||
typename FastAdvertisementServiceUUIDMap::iterator fasu_it =
|
||||
fast_advertisement_service_uuids_.find(*tsi_it);
|
||||
if (fasu_it != fast_advertisement_service_uuids_.end()) {
|
||||
const string& fast_advertisement_service_uuid = fasu_it->second; // alias
|
||||
|
||||
// Then, check if there's service data for this fast advertisement
|
||||
// service UUID. If so, we can short-circuit since all BLE
|
||||
// advertisements can contain at most ONE fast advertisement.
|
||||
typename std::map<string, ConstPtr<ByteArray>>::const_iterator sd_it =
|
||||
advertisement_data->service_data.find(
|
||||
fast_advertisement_service_uuid);
|
||||
if (sd_it != advertisement_data->service_data.end()) {
|
||||
// TODO(b/117432693): Remove this copy once Ptr is fully RefCounted.
|
||||
fast_advertisement_bytes = MakeConstPtr(
|
||||
new ByteArray(sd_it->second->getData(), sd_it->second->size()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return fast_advertisement_bytes;
|
||||
}
|
||||
|
||||
// Creates an advertisement header that's purely a hash of the fast
|
||||
// advertisement, since they come with no header.
|
||||
template <typename Platform>
|
||||
/* RefCounted */ ConstPtr<BLEAdvertisementHeader>
|
||||
DiscoveredPeripheralTracker<Platform>::createFastAdvertisementHeader(
|
||||
ConstPtr<ByteArray> fast_advertisement_bytes) {
|
||||
// Our end goal is to have a fully zeroed-out byte array of the correct length
|
||||
// representing an empty bloom filter.
|
||||
// TODO(b/149938110): remove ScopedPtr.
|
||||
ScopedPtr<ConstPtr<ByteArray>> bloom_filter_bytes{ConstPtr<ByteArray>{
|
||||
new ByteArray{BLEAdvertisementHeader::kServiceIdBloomFilterLength}}};
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray>> advertisement_hash(
|
||||
generateAdvertisementHash(fast_advertisement_bytes));
|
||||
return MakeRefCountedConstPtr(new BLEAdvertisementHeader(
|
||||
BLEAdvertisementHeader::Version::V2, /* num_slots= */ 1,
|
||||
bloom_filter_bytes.get(), advertisement_hash.get()));
|
||||
}
|
||||
|
||||
// Creates a dummy advertisement header that possibly contains all tracked
|
||||
// service IDs.
|
||||
template <typename Platform>
|
||||
string
|
||||
DiscoveredPeripheralTracker<Platform>::createDummyAdvertisementHeaderBytes(
|
||||
Ptr<BLEPeripheralV2> ble_peripheral) {
|
||||
// Put the service ID along with the dummy service ID into our bloom filter
|
||||
// Note: BloomFilter length should always match
|
||||
// BLEAdvertisementHeader::kServiceIdBloomFilterLength
|
||||
ScopedPtr<Ptr<BloomFilter<10>>> bloom_filter(new BloomFilter<10>());
|
||||
|
||||
std::set<string> tracked_service_ids = getTrackedServiceIds();
|
||||
for (typename std::set<string>::iterator tsi_it = tracked_service_ids.begin();
|
||||
tsi_it != tracked_service_ids.end(); ++tsi_it) {
|
||||
bloom_filter->add(*tsi_it);
|
||||
}
|
||||
|
||||
const string& ble_peripheral_id = ble_peripheral->getId(); // alias
|
||||
ScopedPtr<ConstPtr<ByteArray>> ble_peripheral_id_bytes(MakeConstPtr(
|
||||
new ByteArray(ble_peripheral_id.data(), ble_peripheral_id.size())));
|
||||
ScopedPtr<ConstPtr<ByteArray>> advertisement_hash(
|
||||
generateAdvertisementHash(ble_peripheral_id_bytes.get()));
|
||||
return BLEAdvertisementHeader::asString(BLEAdvertisementHeader::Version::V2,
|
||||
kMaxSlots, bloom_filter->asBytes(),
|
||||
advertisement_hash.get());
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool DiscoveredPeripheralTracker<Platform>::isInterestingAdvertisementHeader(
|
||||
/* RefCounted */ ConstPtr<BLEAdvertisementHeader> advertisement_header) {
|
||||
ScopedPtr<Ptr<BloomFilter<10>>> bloom_filter(
|
||||
new BloomFilter<10>(advertisement_header->getServiceIdBloomFilter()));
|
||||
std::set<string> tracked_service_ids = getTrackedServiceIds();
|
||||
for (typename std::set<string>::iterator tsi_it = tracked_service_ids.begin();
|
||||
tsi_it != tracked_service_ids.end(); ++tsi_it) {
|
||||
if (bloom_filter->possiblyContains(*tsi_it)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
bool DiscoveredPeripheralTracker<Platform>::
|
||||
shouldReadFromAdvertisementGattServer(
|
||||
/* RefCounted */ ConstPtr<BLEAdvertisementHeader>
|
||||
advertisement_header) {
|
||||
// Check if we have never seen this header. New headers should always be read.
|
||||
typename AdvertisementReadResultMap::iterator arr_it =
|
||||
advertisement_read_results_.find(advertisement_header);
|
||||
if (arr_it == advertisement_read_results_.end()) {
|
||||
// TODO(ahlee) logger.atDebug().log("Received advertisement header %s, but
|
||||
// we have never seen it before. Will try reading its GATT advertisement.",
|
||||
// advertisementHeader);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Extract the last read result for this particular header.
|
||||
Ptr<AdvertisementReadResult<Platform>> advertisement_read_result =
|
||||
arr_it->second; // alias
|
||||
|
||||
// Now evaluate if we should retry reading.
|
||||
switch (advertisement_read_result->evaluateRetryStatus()) {
|
||||
case AdvertisementReadResult<Platform>::RetryStatus::RETRY:
|
||||
// TODO(ahlee) logger.atDebug().log("Received advertisement header %s.
|
||||
// Will retry reading its GATT advertisement.", advertisementHeader);
|
||||
return true;
|
||||
case AdvertisementReadResult<Platform>::RetryStatus::PREVIOUSLY_SUCCEEDED:
|
||||
// TODO(ahlee) logger.atVerbose().log("Received advertisement header %s,
|
||||
// but we have already read its GATT advertisement.",
|
||||
// advertisementHeader);
|
||||
return false;
|
||||
case AdvertisementReadResult<Platform>::RetryStatus::TOO_SOON:
|
||||
// TODO(ahlee) logger.atDebug().log("Received advertisement header %s, but
|
||||
// we have recently failed to read its GATT advertisement.",
|
||||
// advertisementHeader);
|
||||
return false;
|
||||
case AdvertisementReadResult<Platform>::RetryStatus::UNKNOWN:
|
||||
// Fall through.
|
||||
break;
|
||||
}
|
||||
|
||||
// TODO(ahlee) logger.atDebug().log("Received advertisement header %s, but we
|
||||
// do not know whether or not to retry reading its GATT advertisement. Will
|
||||
// retry to be safe.", advertisementHeader);
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
std::set<ConstPtr<ByteArray>>
|
||||
DiscoveredPeripheralTracker<Platform>::fetchRawGattAdvertisements(
|
||||
Ptr<BLEPeripheralV2> ble_peripheral,
|
||||
/* RefCounted */ ConstPtr<BLEAdvertisementHeader> advertisement_header,
|
||||
Ptr<GattAdvertisementFetcher> gatt_advertisement_fetcher) {
|
||||
Ptr<AdvertisementReadResult<Platform>> old_advertisement_read_result;
|
||||
typename AdvertisementReadResultMap::iterator arr_it =
|
||||
advertisement_read_results_.find(advertisement_header);
|
||||
if (arr_it != advertisement_read_results_.end()) {
|
||||
old_advertisement_read_result = arr_it->second; // alias
|
||||
}
|
||||
|
||||
/* RefCounted */ Ptr<AdvertisementReadResult<Platform>>
|
||||
advertisement_read_result =
|
||||
gatt_advertisement_fetcher->fetchGattAdvertisements(
|
||||
ble_peripheral, advertisement_header->getNumSlots(),
|
||||
old_advertisement_read_result);
|
||||
|
||||
dpt::eraseOwnedPtrFromMap(advertisement_read_results_, advertisement_header);
|
||||
arr_it = advertisement_read_results_
|
||||
.insert(std::make_pair(advertisement_header,
|
||||
advertisement_read_result))
|
||||
.first;
|
||||
|
||||
return arr_it->second->getAdvertisements();
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
void DiscoveredPeripheralTracker<Platform>::handleRawGattAdvertisements(
|
||||
/* RefCounted */ ConstPtr<BLEAdvertisementHeader> advertisement_header,
|
||||
const std::set<ConstPtr<ByteArray>>& raw_gatt_advertisements,
|
||||
bool are_fast_advertisements) {
|
||||
typedef std::map<string, ConstPtr<BLEAdvertisement>> BLEAdvertisementMap;
|
||||
// Parse the raw GATT advertisements. The output of this method is a mapping
|
||||
// of service ID -> GATT advertisement.
|
||||
BLEAdvertisementMap parsed_gatt_advertisements =
|
||||
parseRawGattAdvertisements(raw_gatt_advertisements);
|
||||
ScopedPtr<Ptr<BLEAdvertisementSet>> parsed_gatt_advertisement_values(
|
||||
new BLEAdvertisementSet());
|
||||
|
||||
// Update state for each GATT advertisement.
|
||||
for (BLEAdvertisementMap::iterator pga_it =
|
||||
parsed_gatt_advertisements.begin();
|
||||
pga_it != parsed_gatt_advertisements.end(); ++pga_it) {
|
||||
const string& service_id = pga_it->first; // alias
|
||||
ConstPtr<BLEAdvertisement> gatt_advertisement = pga_it->second; // alias
|
||||
parsed_gatt_advertisement_values->insert(gatt_advertisement);
|
||||
|
||||
// TODO(ahlee): Update the java code to create old_advertisement_header
|
||||
// within the if/else block.
|
||||
AdvertisementHeaderMap::iterator ah_it =
|
||||
advertisement_headers_.find(gatt_advertisement);
|
||||
if (ah_it == advertisement_headers_.end()) {
|
||||
discovered_peripheral_callbacks_.find(service_id)
|
||||
->second->onPeripheralDiscovered(
|
||||
generateBlePeripheral(gatt_advertisement), service_id,
|
||||
gatt_advertisement->getData(), are_fast_advertisements);
|
||||
} else {
|
||||
ConstPtr<BLEAdvertisementHeader> old_advertisement_header =
|
||||
ah_it->second; // alias
|
||||
dpt::eraseOwnedPtrFromMap(advertisement_read_results_,
|
||||
old_advertisement_header);
|
||||
dpt::eraseOwnedPtrFromMap(gatt_advertisements_, old_advertisement_header);
|
||||
}
|
||||
|
||||
dpt::eraseOwnedPtrFromMap(advertisement_headers_, gatt_advertisement);
|
||||
advertisement_headers_.insert(
|
||||
std::make_pair(gatt_advertisement, advertisement_header));
|
||||
|
||||
advertisement_service_ids_.erase(gatt_advertisement);
|
||||
advertisement_service_ids_.insert(
|
||||
std::make_pair(gatt_advertisement, service_id));
|
||||
}
|
||||
|
||||
// Insert the list of read GATT advertisements for this advertisement header.
|
||||
dpt::eraseOwnedPtrFromMap(gatt_advertisements_, advertisement_header);
|
||||
gatt_advertisements_.insert(std::make_pair(
|
||||
advertisement_header, parsed_gatt_advertisement_values.release()));
|
||||
}
|
||||
|
||||
// Returns a map of service IDs to GATT advertisements who belong to a tracked
|
||||
// service ID.
|
||||
template <typename Platform>
|
||||
std::map<string, ConstPtr<BLEAdvertisement>>
|
||||
DiscoveredPeripheralTracker<Platform>::parseRawGattAdvertisements(
|
||||
const std::set<ConstPtr<ByteArray>>& raw_gatt_advertisements) {
|
||||
std::set<string> tracked_service_ids = getTrackedServiceIds();
|
||||
typedef std::map<string, ConstPtr<BLEAdvertisement>> BLEAdvertisementMap;
|
||||
BLEAdvertisementMap parsed_gatt_advertisements;
|
||||
for (std::set<ConstPtr<ByteArray>>::iterator rga_it =
|
||||
raw_gatt_advertisements.begin();
|
||||
rga_it != raw_gatt_advertisements.end(); ++rga_it) {
|
||||
/* RefCounted */ ConstPtr<BLEAdvertisement> gatt_advertisement =
|
||||
BLEAdvertisement::fromBytes(*rga_it);
|
||||
if (gatt_advertisement.isNull()) {
|
||||
// logger.atDebug().log("Unable to parse raw GATT advertisement %s",
|
||||
// *rga_it);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Make sure the advertisement belongs to a service ID we're tracking.
|
||||
for (typename std::set<string>::iterator tsi_it =
|
||||
tracked_service_ids.begin();
|
||||
tsi_it != tracked_service_ids.end(); ++tsi_it) {
|
||||
// If we already found a higher version advertisement for this service ID,
|
||||
// there's no point in comparing this advertisement against it.
|
||||
BLEAdvertisementMap::iterator pga_it =
|
||||
parsed_gatt_advertisements.find(*tsi_it);
|
||||
if (pga_it != parsed_gatt_advertisements.end()) {
|
||||
if (pga_it->second->getVersion() > gatt_advertisement->getVersion()) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Map the service ID to the advertisement if the service ID hashes match.
|
||||
ScopedPtr<ConstPtr<ByteArray>> service_id_hash(
|
||||
generateServiceIdHash(gatt_advertisement->getVersion(), *tsi_it));
|
||||
if (*service_id_hash == *(gatt_advertisement->getServiceIdHash())) {
|
||||
// logger.atDebug().log("Matched service ID %s to GATT advertisement
|
||||
// %s.", serviceId, gattAdvertisement);
|
||||
parsed_gatt_advertisements.insert(
|
||||
std::make_pair(*tsi_it, gatt_advertisement));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return parsed_gatt_advertisements;
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
void DiscoveredPeripheralTracker<Platform>::
|
||||
updateCommonStateForFoundBleAdvertisement(
|
||||
/* RefCounted */ ConstPtr<BLEAdvertisementHeader> advertisement_header,
|
||||
const string& mac_address) {
|
||||
typename GattAdvertisementMap::iterator ga_it =
|
||||
gatt_advertisements_.find(advertisement_header);
|
||||
if (ga_it == gatt_advertisements_.end()) {
|
||||
// logger.atDebug().log("No GATT advertisements found for advertisement
|
||||
// header %s.", advertisementHeader);
|
||||
return;
|
||||
}
|
||||
|
||||
Ptr<BLEAdvertisementSet> saved_gatt_advertisements = ga_it->second; // alias
|
||||
for (BLEAdvertisementSet::iterator sga_it =
|
||||
saved_gatt_advertisements->begin();
|
||||
sga_it != saved_gatt_advertisements->end(); ++sga_it) {
|
||||
ConstPtr<BLEAdvertisement> gatt_advertisement = *sga_it; // alias
|
||||
|
||||
AdvertisementServiceIdMap::iterator asi_it =
|
||||
advertisement_service_ids_.find(gatt_advertisement);
|
||||
if (asi_it == advertisement_service_ids_.end()) {
|
||||
continue;
|
||||
}
|
||||
const string& service_id = asi_it->second; // alias
|
||||
|
||||
// Make sure the stored GATT advertisement is still being tracked.
|
||||
std::set<string> tracked_service_ids = getTrackedServiceIds();
|
||||
if (tracked_service_ids.find(service_id) == tracked_service_ids.end()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// The iterator returned from find() is guaranteed to be valid because it's
|
||||
// tied to discovered_peripheral_callbacks_, whose keyset is checked through
|
||||
// getTrackedServiceIds() above.
|
||||
lost_entity_trackers_.find(service_id)
|
||||
->second->recordFoundEntity(gatt_advertisement);
|
||||
|
||||
// The iterator returned from find() is guaranteed to be valid because it's
|
||||
// tied to advertisement_service_ids_ which is checked at the beginning of
|
||||
// the for loop.
|
||||
mac_addresses_.erase(gatt_advertisement);
|
||||
mac_addresses_.insert(std::make_pair(gatt_advertisement, mac_address));
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
ConstPtr<ByteArray>
|
||||
DiscoveredPeripheralTracker<Platform>::generateAdvertisementHash(
|
||||
ConstPtr<ByteArray> advertisement_bytes) {
|
||||
return Utils::sha256Hash(hash_utils_.get(), advertisement_bytes,
|
||||
BLEAdvertisementHeader::kAdvertisementHashLength);
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
ConstPtr<ByteArray>
|
||||
DiscoveredPeripheralTracker<Platform>::generateServiceIdHash(
|
||||
BLEAdvertisement::Version::Value version, const string& service_id) {
|
||||
ScopedPtr<ConstPtr<ByteArray>> service_id_bytes(
|
||||
MakeConstPtr(new ByteArray(service_id.data(), service_id.size())));
|
||||
switch (version) {
|
||||
case BLEAdvertisement::Version::V1:
|
||||
return Utils::legacySha256HashOnlyForPrinting(
|
||||
hash_utils_.get(), service_id_bytes.get(),
|
||||
BLEPacket::kServiceIdHashLength);
|
||||
case BLEAdvertisement::Version::V2:
|
||||
// Fall through.
|
||||
case BLEAdvertisement::Version::UNKNOWN:
|
||||
// Fall through.
|
||||
default:
|
||||
// Use the latest known hashing scheme.
|
||||
return Utils::sha256Hash(hash_utils_.get(), service_id_bytes.get(),
|
||||
BLEPacket::kServiceIdHashLength);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
@@ -0,0 +1,218 @@
|
||||
#ifndef CORE_INTERNAL_MEDIUMS_DISCOVERED_PERIPHERAL_TRACKER_H_
|
||||
#define CORE_INTERNAL_MEDIUMS_DISCOVERED_PERIPHERAL_TRACKER_H_
|
||||
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <set>
|
||||
|
||||
#include "core/internal/mediums/advertisement_read_result.h"
|
||||
#include "core/internal/mediums/ble_advertisement.h"
|
||||
#include "core/internal/mediums/ble_advertisement_header.h"
|
||||
#include "core/internal/mediums/ble_peripheral.h"
|
||||
#include "core/internal/mediums/discovered_peripheral_callback.h"
|
||||
#include "core/internal/mediums/lost_entity_tracker.h"
|
||||
#include "platform/api/ble_v2.h"
|
||||
#include "platform/api/hash_utils.h"
|
||||
#include "platform/api/lock.h"
|
||||
#include "platform/api/system_clock.h"
|
||||
#include "platform/api/thread_utils.h"
|
||||
#include "platform/byte_array.h"
|
||||
#include "platform/port/string.h"
|
||||
#include "platform/ptr.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
// Manages all discovered peripheral logic for {@link BluetoothLowEnergy}. This
|
||||
// includes tracking found peripherals, lost peripherals, and MAC addresses
|
||||
// associated with those peripherals.
|
||||
//
|
||||
// See go/ble-on-lost for more information. It includes the algorithms used to
|
||||
// compute found and lost peripherals.
|
||||
template <typename Platform>
|
||||
class DiscoveredPeripheralTracker {
|
||||
public:
|
||||
DiscoveredPeripheralTracker();
|
||||
~DiscoveredPeripheralTracker();
|
||||
|
||||
void startTracking(
|
||||
const string& service_id,
|
||||
Ptr<DiscoveredPeripheralCallback> discovered_peripheral_callback,
|
||||
const string& fast_advertisement_service_uuid);
|
||||
void stopTracking(const string& service_id);
|
||||
|
||||
// GATT advertisement fetcher.
|
||||
class GattAdvertisementFetcher {
|
||||
public:
|
||||
virtual ~GattAdvertisementFetcher() {}
|
||||
|
||||
// Fetches relevant GATT advertisements for the peripheral found in {@link
|
||||
// DiscoveredPeripheralTracker#processFoundBleAdvertisement(BleSighting,
|
||||
// GattAdvertisementFetcher)}.
|
||||
virtual Ptr<AdvertisementReadResult<Platform>> fetchGattAdvertisements(
|
||||
Ptr<BLEPeripheralV2> ble_peripheral, std::int32_t num_slots,
|
||||
Ptr<AdvertisementReadResult<Platform>> advertisement_read_result) = 0;
|
||||
};
|
||||
void processFoundBleAdvertisement(
|
||||
Ptr<BLEPeripheralV2> ble_peripheral,
|
||||
ConstPtr<BLEAdvertisementData> advertisement_data,
|
||||
Ptr<GattAdvertisementFetcher> gatt_advertisement_fetcher);
|
||||
void processLostGattAdvertisements();
|
||||
|
||||
// TODO(ahlee): Add connecting logic.
|
||||
|
||||
private:
|
||||
static Ptr<BLEPeripheral> generateBlePeripheral(
|
||||
ConstPtr<BLEAdvertisement> gatt_advertisement);
|
||||
|
||||
static const std::int32_t kMaxSlots;
|
||||
static const std::int64_t kMinConnectionDelayMillis;
|
||||
static const char* kCopresenceServiceUuid;
|
||||
|
||||
std::set<string> getTrackedServiceIds();
|
||||
void clearDataForServiceId(const string& service_id);
|
||||
void clearGattAdvertisement(ConstPtr<BLEAdvertisement> gatt_advertisement);
|
||||
void handleFastAdvertisement(
|
||||
Ptr<BLEPeripheralV2> ble_peripheral,
|
||||
ConstPtr<BLEAdvertisementData> advertisement_data);
|
||||
void handleAdvertisementHeader(
|
||||
Ptr<BLEPeripheralV2> ble_peripheral,
|
||||
ConstPtr<BLEAdvertisementData> advertisement_data,
|
||||
Ptr<GattAdvertisementFetcher> gatt_advertisement_fetcher);
|
||||
string extractAdvertisementHeaderBytes(
|
||||
Ptr<BLEPeripheralV2> ble_peripheral,
|
||||
ConstPtr<BLEAdvertisementData> advertisement_data);
|
||||
ConstPtr<ByteArray> extractFastAdvertisementBytes(
|
||||
ConstPtr<BLEAdvertisementData> advertisement_data);
|
||||
/*RefCounted */ ConstPtr<BLEAdvertisementHeader>
|
||||
createFastAdvertisementHeader(ConstPtr<ByteArray> fast_advertisement_bytes);
|
||||
string createDummyAdvertisementHeaderBytes(
|
||||
Ptr<BLEPeripheralV2> ble_peripheral);
|
||||
bool isInterestingAdvertisementHeader(
|
||||
/* RefCounted */ ConstPtr<BLEAdvertisementHeader> advertisement_header);
|
||||
bool shouldReadFromAdvertisementGattServer(
|
||||
/* RefCounted */ ConstPtr<BLEAdvertisementHeader> advertisement_header);
|
||||
std::set<ConstPtr<ByteArray>> fetchRawGattAdvertisements(
|
||||
Ptr<BLEPeripheralV2> ble_peripheral,
|
||||
/* RefCounted */ ConstPtr<BLEAdvertisementHeader> advertisement_header,
|
||||
Ptr<GattAdvertisementFetcher> gatt_advertisement_fetcher);
|
||||
void handleRawGattAdvertisements(
|
||||
/* RefCounted */ ConstPtr<BLEAdvertisementHeader> advertisement_header,
|
||||
const std::set<ConstPtr<ByteArray>>& raw_gatt_advertisements,
|
||||
bool are_fast_advertisements);
|
||||
std::map<string, ConstPtr<BLEAdvertisement>> parseRawGattAdvertisements(
|
||||
const std::set<ConstPtr<ByteArray>>& raw_gatt_advertisements);
|
||||
void updateCommonStateForFoundBleAdvertisement(
|
||||
/* RefCounted */ ConstPtr<BLEAdvertisementHeader> advertisement_header,
|
||||
const string& mac_address);
|
||||
|
||||
// TODO(ahlee): Add in connecting logic.
|
||||
|
||||
// TODO(ahlee): Move these out to utils (also used by BLE V2).
|
||||
ConstPtr<ByteArray> generateAdvertisementHash(
|
||||
ConstPtr<ByteArray> advertisement_bytes);
|
||||
ConstPtr<ByteArray> generateServiceIdHash(
|
||||
BLEAdvertisement::Version::Value version, const string& service_id);
|
||||
|
||||
// ------------ GENERAL ------------
|
||||
ScopedPtr<Ptr<Lock>> lock_;
|
||||
ScopedPtr<Ptr<ThreadUtils>> thread_utils_;
|
||||
ScopedPtr<Ptr<SystemClock>> system_clock_;
|
||||
ScopedPtr<Ptr<HashUtils>> hash_utils_;
|
||||
|
||||
// ------------ SERVICE ID MAPS ------------
|
||||
// Entries in these maps all follow the same lifecycle. Entries are added in
|
||||
// startTracking, and removed in stopTracking.
|
||||
|
||||
// Maps service IDs to DiscoveredPeripheralCallbacks. Tracks what service IDs
|
||||
// are currently active and gives us client callbacks to call.
|
||||
typedef std::map<string, Ptr<DiscoveredPeripheralCallback>>
|
||||
DiscoveredPeripheralCallbackMap;
|
||||
DiscoveredPeripheralCallbackMap discovered_peripheral_callbacks_;
|
||||
|
||||
// Maps service IDs to LostEntityTrackers. Used to periodically compute lost
|
||||
// GATT advertisements, grouped by service ID.
|
||||
typedef std::map<string, Ptr<LostEntityTracker<Platform, BLEAdvertisement>>>
|
||||
LostEntityTrackerMap;
|
||||
LostEntityTrackerMap lost_entity_trackers_;
|
||||
|
||||
// Maps service IDs to BLE service UUIDs. Used to check for fast
|
||||
// advertisements delivered through BLE advertisement service data, under the
|
||||
// given UUID.
|
||||
// UUIDs are represented as strings in this map because they are coming from
|
||||
// AdvertisingOptions and our UUID class is an internal concept that we don't
|
||||
// want to expose to clients.
|
||||
typedef std::map<string, string> FastAdvertisementServiceUUIDMap;
|
||||
FastAdvertisementServiceUUIDMap fast_advertisement_service_uuids_;
|
||||
|
||||
// ------------ ADVERTISEMENT HEADER MAPS ------------
|
||||
|
||||
// Maps advertisement headers to AdvertisementReadResults. Tells us when to
|
||||
// retry reading a GATT advertisement. If no entry exists for a particular
|
||||
// header, we should try reading a GATT advertisement. Entries are added
|
||||
// whenever a GATT advertisement read is attempted, and removed when GATT
|
||||
// advertisements are lost. Entries are also removed whenever
|
||||
// gattAdvertisements removes its entry.
|
||||
//
|
||||
// The map is also cleared whenever startTracking is called, due to client
|
||||
// changes. For example, say clients A and B start scanning and discover
|
||||
// advertisements A and B (for both clients) on advertisement header 1. Then,
|
||||
// A restarts scanning, causing us to clear stale advertisement A. However,
|
||||
// since B was still scanning, we don't remove advertisement header 1 from the
|
||||
// map. This causes us to never re-read advertisement A.
|
||||
typedef std::map</* RefCounted */ ConstPtr<BLEAdvertisementHeader>,
|
||||
Ptr<AdvertisementReadResult<Platform>>>
|
||||
AdvertisementReadResultMap;
|
||||
AdvertisementReadResultMap advertisement_read_results_;
|
||||
|
||||
// Maps advertisement headers to a set of GATT advertisements from a single
|
||||
// peripheral. Used to retrieve GATT advertisements that we need to reprocess
|
||||
// every time a header is seen. Entries are added when GATT advertisements are
|
||||
// read, removed when all associated GATT advertisements are lost or become
|
||||
// stale, and replaced when the advertisement header is updated for a single
|
||||
// remote peripheral.
|
||||
typedef std::set</* RefCounted */ ConstPtr<BLEAdvertisement>>
|
||||
BLEAdvertisementSet;
|
||||
typedef std::map</* RefCounted */ ConstPtr<BLEAdvertisementHeader>,
|
||||
Ptr<BLEAdvertisementSet>>
|
||||
GattAdvertisementMap;
|
||||
GattAdvertisementMap gatt_advertisements_;
|
||||
|
||||
// ------------ GATT ADVERTISEMENT MAPS ------------
|
||||
// Entries in these maps all follow the same lifecycle. Entries are added when
|
||||
// GATT advertisements are read, and removed when GATT advertisements are lost
|
||||
// or become stale.
|
||||
|
||||
// Maps GATT advertisements to the service ID it's associated with. Tracks
|
||||
// what GATT advertisements are currently active. Used to determine which
|
||||
// LostEntityTracker to invoke when advertisements are rediscovered.
|
||||
typedef std::map</* RefCounted */ ConstPtr<BLEAdvertisement>, string>
|
||||
AdvertisementServiceIdMap;
|
||||
AdvertisementServiceIdMap advertisement_service_ids_;
|
||||
|
||||
// Maps GATT advertisements to advertisement headers. Used to efficiently find
|
||||
// advertisement headers to delete when GATT advertisements are updated. This
|
||||
// is a reverse map of gatt_advertisements_.
|
||||
typedef std::map</* RefCounted */ ConstPtr<BLEAdvertisement>,
|
||||
/* RefCounted */ ConstPtr<BLEAdvertisementHeader>>
|
||||
AdvertisementHeaderMap;
|
||||
AdvertisementHeaderMap advertisement_headers_;
|
||||
|
||||
// Maps GATT advertisements to MAC addresses. Used when we need to make a
|
||||
// socket connection based off of the GATT advertisement alone. Entries are
|
||||
// modified every time a GATT advertisement's advertisement header is seen.
|
||||
typedef std::map</* RefCounted */ ConstPtr<BLEAdvertisement>, string>
|
||||
MacAddressMap;
|
||||
MacAddressMap mac_addresses_;
|
||||
};
|
||||
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
|
||||
#include "core/internal/mediums/discovered_peripheral_tracker.cc"
|
||||
|
||||
#endif // CORE_INTERNAL_MEDIUMS_DISCOVERED_PERIPHERAL_TRACKER_H_
|
||||
@@ -0,0 +1,56 @@
|
||||
#include "core/internal/mediums/lost_entity_tracker.h"
|
||||
|
||||
#include "platform/synchronized.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
template <typename Platform, typename Entity>
|
||||
LostEntityTracker<Platform, Entity>::LostEntityTracker()
|
||||
: lock_(Platform::createLock()),
|
||||
current_entities_(),
|
||||
previously_found_entities_() {}
|
||||
|
||||
template <typename Platform, typename Entity>
|
||||
LostEntityTracker<Platform, Entity>::~LostEntityTracker() {
|
||||
previously_found_entities_.clear();
|
||||
current_entities_.clear();
|
||||
}
|
||||
|
||||
template <typename Platform, typename Entity>
|
||||
void LostEntityTracker<Platform, Entity>::recordFoundEntity(
|
||||
ConstPtr<Entity> entity) {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
current_entities_.insert(entity);
|
||||
}
|
||||
|
||||
template <typename Platform, typename Entity>
|
||||
typename LostEntityTracker<Platform, Entity>::EntitySet
|
||||
LostEntityTracker<Platform, Entity>::computeLostEntities() {
|
||||
Synchronized s(lock_.get());
|
||||
|
||||
// The set of lost entities is the previously found set MINUS the currently
|
||||
// found set.
|
||||
for (typename EntitySet::iterator it = current_entities_.begin();
|
||||
it != current_entities_.end(); ++it) {
|
||||
previously_found_entities_.erase(*it);
|
||||
}
|
||||
EntitySet lost_entities(previously_found_entities_.begin(),
|
||||
previously_found_entities_.end());
|
||||
|
||||
// Update our previous and current sets.
|
||||
previously_found_entities_.clear();
|
||||
previously_found_entities_.insert(current_entities_.begin(),
|
||||
current_entities_.end());
|
||||
current_entities_.clear();
|
||||
|
||||
return lost_entities;
|
||||
}
|
||||
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
@@ -0,0 +1,49 @@
|
||||
#ifndef CORE_INTERNAL_MEDIUMS_LOST_ENTITY_TRACKER_H_
|
||||
#define CORE_INTERNAL_MEDIUMS_LOST_ENTITY_TRACKER_H_
|
||||
|
||||
#include <set>
|
||||
|
||||
#include "platform/api/lock.h"
|
||||
#include "platform/ptr.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
|
||||
// Tracks "lost" entities based on a manual update/compute model. Used by
|
||||
// mediums that only report found devices. Lost entities are computed based off
|
||||
// of whether a specific entity was rediscovered since the last call to
|
||||
// computeLostEntities.
|
||||
//
|
||||
// Note: Entity must overload the < and == operators.
|
||||
template <typename Platform, typename Entity>
|
||||
class LostEntityTracker {
|
||||
public:
|
||||
typedef std::set<ConstPtr<Entity> > EntitySet;
|
||||
|
||||
LostEntityTracker();
|
||||
~LostEntityTracker();
|
||||
|
||||
// Records the given entity as being recently found, whether or not this is
|
||||
// our first time discovering the entity.
|
||||
void recordFoundEntity(ConstPtr<Entity> entity);
|
||||
|
||||
// Computes and returns the set of entities considered lost since the last
|
||||
// time this method was called.
|
||||
EntitySet computeLostEntities();
|
||||
|
||||
private:
|
||||
ScopedPtr<Ptr<Lock> > lock_;
|
||||
EntitySet current_entities_;
|
||||
EntitySet previously_found_entities_;
|
||||
};
|
||||
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
|
||||
#include "core/internal/mediums/lost_entity_tracker.cc"
|
||||
|
||||
#endif // CORE_INTERNAL_MEDIUMS_LOST_ENTITY_TRACKER_H_
|
||||
@@ -0,0 +1,121 @@
|
||||
#include "core/internal/mediums/lost_entity_tracker.h"
|
||||
|
||||
#include "platform/impl/default/default_platform.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
namespace mediums {
|
||||
namespace {
|
||||
|
||||
struct TestEntity {
|
||||
int id;
|
||||
|
||||
explicit TestEntity(int givenId) : id(givenId) {}
|
||||
|
||||
bool operator<(const TestEntity &other) const { return id < other.id; }
|
||||
};
|
||||
|
||||
TEST(LostEntityTracker, NoEntitiesLost) {
|
||||
LostEntityTracker<DefaultPlatform, TestEntity> lost_entity_tracker;
|
||||
ScopedPtr<ConstPtr<TestEntity> > entity_1(MakeConstPtr(new TestEntity(1)));
|
||||
ScopedPtr<ConstPtr<TestEntity> > entity_2(MakeConstPtr(new TestEntity(2)));
|
||||
ScopedPtr<ConstPtr<TestEntity> > entity_3(MakeConstPtr(new TestEntity(3)));
|
||||
|
||||
// Discover some entities.
|
||||
lost_entity_tracker.recordFoundEntity(entity_1.get());
|
||||
lost_entity_tracker.recordFoundEntity(entity_2.get());
|
||||
lost_entity_tracker.recordFoundEntity(entity_3.get());
|
||||
|
||||
// Make sure none are lost on the first round.
|
||||
ASSERT_TRUE(lost_entity_tracker.computeLostEntities().empty());
|
||||
|
||||
// Rediscover the same entities.
|
||||
lost_entity_tracker.recordFoundEntity(entity_1.get());
|
||||
lost_entity_tracker.recordFoundEntity(entity_2.get());
|
||||
lost_entity_tracker.recordFoundEntity(entity_3.get());
|
||||
|
||||
// Make sure we still didn't lose any entities.
|
||||
ASSERT_TRUE(lost_entity_tracker.computeLostEntities().empty());
|
||||
}
|
||||
|
||||
TEST(LostEntityTracker, AllEntitiesLost) {
|
||||
LostEntityTracker<DefaultPlatform, TestEntity> lost_entity_tracker;
|
||||
ScopedPtr<ConstPtr<TestEntity> > entity_1(MakeConstPtr(new TestEntity(1)));
|
||||
ScopedPtr<ConstPtr<TestEntity> > entity_2(MakeConstPtr(new TestEntity(2)));
|
||||
ScopedPtr<ConstPtr<TestEntity> > entity_3(MakeConstPtr(new TestEntity(3)));
|
||||
|
||||
// Discover some entities.
|
||||
lost_entity_tracker.recordFoundEntity(entity_1.get());
|
||||
lost_entity_tracker.recordFoundEntity(entity_2.get());
|
||||
lost_entity_tracker.recordFoundEntity(entity_3.get());
|
||||
|
||||
// Make sure none are lost on the first round.
|
||||
ASSERT_TRUE(lost_entity_tracker.computeLostEntities().empty());
|
||||
|
||||
// Go through a round without rediscovering any entities.
|
||||
typename LostEntityTracker<DefaultPlatform, TestEntity>::EntitySet
|
||||
lost_entities = lost_entity_tracker.computeLostEntities();
|
||||
ASSERT_TRUE(lost_entities.find(entity_1.get()) != lost_entities.end());
|
||||
ASSERT_TRUE(lost_entities.find(entity_2.get()) != lost_entities.end());
|
||||
ASSERT_TRUE(lost_entities.find(entity_3.get()) != lost_entities.end());
|
||||
}
|
||||
|
||||
TEST(LostEntityTracker, SomeEntitiesLost) {
|
||||
LostEntityTracker<DefaultPlatform, TestEntity> lost_entity_tracker;
|
||||
ScopedPtr<ConstPtr<TestEntity> > entity_1(MakeConstPtr(new TestEntity(1)));
|
||||
ScopedPtr<ConstPtr<TestEntity> > entity_2(MakeConstPtr(new TestEntity(2)));
|
||||
ScopedPtr<ConstPtr<TestEntity> > entity_3(MakeConstPtr(new TestEntity(3)));
|
||||
|
||||
// Discover some entities.
|
||||
lost_entity_tracker.recordFoundEntity(entity_1.get());
|
||||
lost_entity_tracker.recordFoundEntity(entity_2.get());
|
||||
|
||||
// Make sure none are lost on the first round.
|
||||
ASSERT_TRUE(lost_entity_tracker.computeLostEntities().empty());
|
||||
|
||||
// Go through the next round only rediscovering one of our entities and
|
||||
// discovering an additional entity as well. Then, verify that only one entity
|
||||
// was lost after the check.
|
||||
lost_entity_tracker.recordFoundEntity(entity_1.get());
|
||||
lost_entity_tracker.recordFoundEntity(entity_3.get());
|
||||
typename LostEntityTracker<DefaultPlatform, TestEntity>::EntitySet
|
||||
lost_entities = lost_entity_tracker.computeLostEntities();
|
||||
ASSERT_TRUE(lost_entities.find(entity_1.get()) == lost_entities.end());
|
||||
ASSERT_TRUE(lost_entities.find(entity_2.get()) != lost_entities.end());
|
||||
ASSERT_TRUE(lost_entities.find(entity_3.get()) == lost_entities.end());
|
||||
}
|
||||
|
||||
TEST(LostEntityTracker, SameEntityMultipleCopies) {
|
||||
LostEntityTracker<DefaultPlatform, TestEntity> lost_entity_tracker;
|
||||
ScopedPtr<ConstPtr<TestEntity> > entity_1(MakeConstPtr(new TestEntity(1)));
|
||||
ScopedPtr<ConstPtr<TestEntity> > entity_1_copy(
|
||||
MakeConstPtr(new TestEntity(1)));
|
||||
|
||||
// Discover an entity.
|
||||
lost_entity_tracker.recordFoundEntity(entity_1.get());
|
||||
|
||||
// Make sure none are lost on the first round.
|
||||
ASSERT_TRUE(lost_entity_tracker.computeLostEntities().empty());
|
||||
|
||||
// Rediscover the same entity, but through a copy of it.
|
||||
lost_entity_tracker.recordFoundEntity(entity_1_copy.get());
|
||||
|
||||
// Make sure none are lost on the second round.
|
||||
ASSERT_TRUE(lost_entity_tracker.computeLostEntities().empty());
|
||||
|
||||
// Go through a round without rediscovering any entities and verify that we
|
||||
// lost an entity equivalent to both copies of it.
|
||||
typename LostEntityTracker<DefaultPlatform, TestEntity>::EntitySet
|
||||
lost_entities = lost_entity_tracker.computeLostEntities();
|
||||
ASSERT_EQ(lost_entities.size(), 1);
|
||||
ASSERT_TRUE(lost_entities.find(entity_1.get()) != lost_entities.end());
|
||||
ASSERT_TRUE(lost_entities.find(entity_1_copy.get()) != lost_entities.end());
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace mediums
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
@@ -0,0 +1,42 @@
|
||||
#include "core/internal/mediums/mediums.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
|
||||
template <typename Platform>
|
||||
Mediums<Platform>::Mediums()
|
||||
: bluetooth_radio_(new BluetoothRadio<Platform>()),
|
||||
bluetooth_classic_(
|
||||
new BluetoothClassic<Platform>(bluetooth_radio_.get())),
|
||||
ble_(new BLE<Platform>(bluetooth_radio_.get())),
|
||||
ble_v2_(new mediums::BLEV2<Platform>(bluetooth_radio_.get())) {}
|
||||
|
||||
template <typename Platform>
|
||||
Mediums<Platform>::~Mediums() {
|
||||
// Nothing to do.
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
Ptr<BluetoothRadio<Platform> > Mediums<Platform>::bluetoothRadio() const {
|
||||
return bluetooth_radio_.get();
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
Ptr<BluetoothClassic<Platform> > Mediums<Platform>::bluetoothClassic() const {
|
||||
return bluetooth_classic_.get();
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
Ptr<BLE<Platform> > Mediums<Platform>::ble() const {
|
||||
return ble_.get();
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
Ptr<mediums::BLEV2<Platform> > Mediums<Platform>::bleV2() const {
|
||||
return ble_v2_.get();
|
||||
}
|
||||
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
@@ -0,0 +1,52 @@
|
||||
#ifndef CORE_INTERNAL_MEDIUMS_MEDIUMS_H_
|
||||
#define CORE_INTERNAL_MEDIUMS_MEDIUMS_H_
|
||||
|
||||
#include "core/internal/mediums/ble.h"
|
||||
#include "core/internal/mediums/ble_v2.h"
|
||||
#include "core/internal/mediums/bluetooth_classic.h"
|
||||
#include "core/internal/mediums/bluetooth_radio.h"
|
||||
#include "platform/ptr.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
|
||||
// Facilitates convenient and reliable usage of various wireless mediums.
|
||||
template <typename Platform>
|
||||
class Mediums {
|
||||
public:
|
||||
Mediums();
|
||||
// Reverts all the mediums to their original state.
|
||||
~Mediums();
|
||||
|
||||
// Returns a handle to the Bluetooth radio.
|
||||
Ptr<BluetoothRadio<Platform> > bluetoothRadio() const;
|
||||
// Returns a handle to the Bluetooth Classic medium.
|
||||
Ptr<BluetoothClassic<Platform> > bluetoothClassic() const;
|
||||
// Returns a handle to the Bluetooth Low Energy (BLE) medium.
|
||||
Ptr<BLE<Platform> > ble() const;
|
||||
// Returns a handle to V2 of the Bluetooth Low Energy (BLE) medium.
|
||||
Ptr<mediums::BLEV2<Platform> > bleV2() const;
|
||||
|
||||
private:
|
||||
// The order of declaration is critical for both construction and
|
||||
// destruction.
|
||||
//
|
||||
// 1) Construction: The individual mediums have a dependency on the
|
||||
// corresponding radio, so the radio must be initialized first.
|
||||
//
|
||||
// 2) Destruction: The individual mediums should be shut down before the
|
||||
// corresponding radio.
|
||||
ScopedPtr<Ptr<BluetoothRadio<Platform> > > bluetooth_radio_;
|
||||
ScopedPtr<Ptr<BluetoothClassic<Platform> > > bluetooth_classic_;
|
||||
ScopedPtr<Ptr<BLE<Platform> > > ble_;
|
||||
ScopedPtr<Ptr<mediums::BLEV2<Platform> > > ble_v2_;
|
||||
};
|
||||
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
|
||||
#include "core/internal/mediums/mediums.cc"
|
||||
|
||||
#endif // CORE_INTERNAL_MEDIUMS_MEDIUMS_H_
|
||||
@@ -0,0 +1,73 @@
|
||||
#include "core/internal/mediums/utils.h"
|
||||
|
||||
#include <sstream>
|
||||
|
||||
#include "platform/exception.h"
|
||||
#include "absl/strings/escaping.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
|
||||
void Utils::closeSocket(Ptr<BluetoothServerSocket> socket,
|
||||
const std::string& type, const std::string& name) {
|
||||
if (!socket.isNull()) {
|
||||
Exception::Value e = socket->close();
|
||||
if (Exception::NONE != e) {
|
||||
if (Exception::IO == e) {
|
||||
// TODO(reznor): log.atWarning().withCause(e).log("Failed to close
|
||||
// %sSocket %s", type, name);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// TODO(reznor): log.atVerbose().log("Closed %sSocket %s", type, name);
|
||||
}
|
||||
}
|
||||
|
||||
ConstPtr<ByteArray> Utils::sha256Hash(Ptr<HashUtils> hash_utils,
|
||||
ConstPtr<ByteArray> source,
|
||||
size_t length) {
|
||||
if (source.isNull()) {
|
||||
return ConstPtr<ByteArray>();
|
||||
}
|
||||
|
||||
ScopedPtr<ConstPtr<ByteArray>> full_hash(
|
||||
hash_utils->sha256(std::string(source->getData(), source->size())));
|
||||
return MakeConstPtr(new ByteArray(full_hash->getData(), length));
|
||||
}
|
||||
|
||||
ConstPtr<ByteArray> Utils::legacySha256HashOnlyForPrinting(
|
||||
Ptr<HashUtils> hash_utils, ConstPtr<ByteArray> source, size_t length) {
|
||||
if (source.isNull()) {
|
||||
return ConstPtr<ByteArray>();
|
||||
}
|
||||
|
||||
std::string formatted_hex_string = Utils::bytesToPrintableHexString(source);
|
||||
ScopedPtr<ConstPtr<ByteArray>> formatted_hex_byte_array(MakeConstPtr(
|
||||
new ByteArray(formatted_hex_string.data(), formatted_hex_string.size())));
|
||||
return Utils::sha256Hash(hash_utils, formatted_hex_byte_array.get(), length);
|
||||
}
|
||||
|
||||
std::string Utils::bytesToPrintableHexString(ConstPtr<ByteArray> bytes) {
|
||||
std::string hex_string(
|
||||
absl::BytesToHexString(std::string(bytes->getData(), bytes->size())));
|
||||
|
||||
// Print out the byte array as a space separated listing of hex bytes.
|
||||
std::ostringstream formatted_hex_string_stream;
|
||||
formatted_hex_string_stream << "[ ";
|
||||
for (int i = 0; i < hex_string.size(); i += 2) {
|
||||
formatted_hex_string_stream << "0x";
|
||||
// This is safe because we have the guarantee that hex_string is of even
|
||||
// length (because a hex encoding will always be double the size of its
|
||||
// input).
|
||||
formatted_hex_string_stream << hex_string[i] << hex_string[i + 1];
|
||||
formatted_hex_string_stream << " ";
|
||||
}
|
||||
formatted_hex_string_stream << "]";
|
||||
|
||||
return formatted_hex_string_stream.str();
|
||||
}
|
||||
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
@@ -0,0 +1,32 @@
|
||||
#ifndef CORE_INTERNAL_MEDIUMS_UTILS_H_
|
||||
#define CORE_INTERNAL_MEDIUMS_UTILS_H_
|
||||
|
||||
#include "platform/api/bluetooth_classic.h"
|
||||
#include "platform/api/hash_utils.h"
|
||||
#include "platform/byte_array.h"
|
||||
#include "platform/port/string.h"
|
||||
#include "platform/ptr.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
|
||||
class Utils {
|
||||
public:
|
||||
static void closeSocket(Ptr<BluetoothServerSocket> socket,
|
||||
const std::string& type, const std::string& name);
|
||||
static ConstPtr<ByteArray> sha256Hash(Ptr<HashUtils> hash_utils,
|
||||
ConstPtr<ByteArray> source,
|
||||
size_t length);
|
||||
static ConstPtr<ByteArray> legacySha256HashOnlyForPrinting(
|
||||
Ptr<HashUtils> hash_utils, ConstPtr<ByteArray> source, size_t length);
|
||||
|
||||
private:
|
||||
static std::string bytesToPrintableHexString(ConstPtr<ByteArray> bytes);
|
||||
};
|
||||
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
|
||||
#endif // CORE_INTERNAL_MEDIUMS_UTILS_H_
|
||||
@@ -0,0 +1,100 @@
|
||||
#include "core/internal/mediums/uuid.h"
|
||||
|
||||
#include <iomanip>
|
||||
#include <sstream>
|
||||
|
||||
#include "platform/api/hash_utils.h"
|
||||
#include "platform/ptr.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
|
||||
template <typename Platform>
|
||||
UUID<Platform>::UUID(const string& data) {
|
||||
// Based on the Java counterpart at
|
||||
// http://androidxref.com/8.0.0_r4/xref/libcore/ojluni/src/main/java/java/util/UUID.java#162.
|
||||
ScopedPtr<Ptr<HashUtils> > scoped_hash_utils(Platform::createHashUtils());
|
||||
ScopedPtr<ConstPtr<ByteArray> > scoped_md5_bytes(
|
||||
scoped_hash_utils->md5(data));
|
||||
data_.assign(scoped_md5_bytes->getData(), scoped_md5_bytes->size());
|
||||
|
||||
data_[6] &= 0x0f; // Clear version.
|
||||
data_[6] |= 0x30; // Set to version 3.
|
||||
data_[8] &= 0x3f; // Clear variant.
|
||||
data_[8] |= 0x80; // Set to IETF variant.
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
UUID<Platform>::UUID(std::int64_t most_sig_bits, std::int64_t least_sig_bits) {
|
||||
// Base on the Java counterpart at
|
||||
// http://androidxref.com/8.0.0_r4/xref/libcore/ojluni/src/main/java/java/util/UUID.java#104.
|
||||
data_.reserve(sizeof(most_sig_bits) + sizeof(least_sig_bits));
|
||||
|
||||
data_[0] = static_cast<char>((most_sig_bits >> 56) & 0x0ff);
|
||||
data_[1] = static_cast<char>((most_sig_bits >> 48) & 0x0ff);
|
||||
data_[2] = static_cast<char>((most_sig_bits >> 40) & 0x0ff);
|
||||
data_[3] = static_cast<char>((most_sig_bits >> 32) & 0x0ff);
|
||||
data_[4] = static_cast<char>((most_sig_bits >> 24) & 0x0ff);
|
||||
data_[5] = static_cast<char>((most_sig_bits >> 16) & 0x0ff);
|
||||
data_[6] = static_cast<char>((most_sig_bits >> 8) & 0x0ff);
|
||||
data_[7] = static_cast<char>((most_sig_bits >> 0) & 0x0ff);
|
||||
|
||||
data_[8] = static_cast<char>((least_sig_bits >> 56) & 0x0ff);
|
||||
data_[9] = static_cast<char>((least_sig_bits >> 48) & 0x0ff);
|
||||
data_[10] = static_cast<char>((least_sig_bits >> 40) & 0x0ff);
|
||||
data_[11] = static_cast<char>((least_sig_bits >> 32) & 0x0ff);
|
||||
data_[12] = static_cast<char>((least_sig_bits >> 24) & 0x0ff);
|
||||
data_[13] = static_cast<char>((least_sig_bits >> 16) & 0x0ff);
|
||||
data_[14] = static_cast<char>((least_sig_bits >> 8) & 0x0ff);
|
||||
data_[15] = static_cast<char>((least_sig_bits >> 0) & 0x0ff);
|
||||
}
|
||||
|
||||
template <typename Platform>
|
||||
UUID<Platform>::~UUID() {}
|
||||
|
||||
template <typename Platform>
|
||||
string UUID<Platform>::str() {
|
||||
// Based on the Java counterpart at
|
||||
// http://androidxref.com/8.0.0_r4/xref/libcore/ojluni/src/main/java/java/util/UUID.java#375.
|
||||
|
||||
// The masking with 0x0ff is essential because we're taking 8-bit bytes and
|
||||
// casting them to integers (which, depending on the platform, are 16- or
|
||||
// 32-bits wide); without that, we get a leading FF (16-bit) or FFFFFF
|
||||
// (32-bit) when the MSB of the 8-bit byte is 1.
|
||||
//
|
||||
// And the cast to an integer is required because std::hex only takes effect
|
||||
// on integral types (and no, uint8_t doesn't activate it).
|
||||
#define BYTE_TO_HEX(b) \
|
||||
std::setfill('0') << std::setw(2) << std::hex \
|
||||
<< (static_cast<unsigned int>(b) & 0x0ff)
|
||||
|
||||
std::ostringstream md5_hex;
|
||||
|
||||
md5_hex << BYTE_TO_HEX(data_[0]);
|
||||
md5_hex << BYTE_TO_HEX(data_[1]);
|
||||
md5_hex << BYTE_TO_HEX(data_[2]);
|
||||
md5_hex << BYTE_TO_HEX(data_[3]);
|
||||
md5_hex << "-";
|
||||
md5_hex << BYTE_TO_HEX(data_[4]);
|
||||
md5_hex << BYTE_TO_HEX(data_[5]);
|
||||
md5_hex << "-";
|
||||
md5_hex << BYTE_TO_HEX(data_[6]);
|
||||
md5_hex << BYTE_TO_HEX(data_[7]);
|
||||
md5_hex << "-";
|
||||
md5_hex << BYTE_TO_HEX(data_[8]);
|
||||
md5_hex << BYTE_TO_HEX(data_[9]);
|
||||
md5_hex << "-";
|
||||
md5_hex << BYTE_TO_HEX(data_[10]);
|
||||
md5_hex << BYTE_TO_HEX(data_[11]);
|
||||
md5_hex << BYTE_TO_HEX(data_[12]);
|
||||
md5_hex << BYTE_TO_HEX(data_[13]);
|
||||
md5_hex << BYTE_TO_HEX(data_[14]);
|
||||
md5_hex << BYTE_TO_HEX(data_[15]);
|
||||
|
||||
return md5_hex.str();
|
||||
}
|
||||
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
@@ -0,0 +1,39 @@
|
||||
#ifndef CORE_INTERNAL_MEDIUMS_UUID_H_
|
||||
#define CORE_INTERNAL_MEDIUMS_UUID_H_
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "platform/port/string.h"
|
||||
|
||||
namespace location {
|
||||
namespace nearby {
|
||||
namespace connections {
|
||||
|
||||
// A type 3 name-based
|
||||
// (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
|
||||
// UUID.
|
||||
//
|
||||
// https://developer.android.com/reference/java/util/UUID.html
|
||||
template <typename Platform>
|
||||
class UUID {
|
||||
public:
|
||||
explicit UUID(const string& data);
|
||||
UUID(std::int64_t most_sig_bits, std::int64_t least_sig_bits);
|
||||
~UUID();
|
||||
|
||||
// Returns the canonical textual representation
|
||||
// (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of the
|
||||
// UUID.
|
||||
string str();
|
||||
|
||||
private:
|
||||
string data_;
|
||||
};
|
||||
|
||||
} // namespace connections
|
||||
} // namespace nearby
|
||||
} // namespace location
|
||||
|
||||
#include "core/internal/mediums/uuid.cc"
|
||||
|
||||
#endif // CORE_INTERNAL_MEDIUMS_UUID_H_
|
||||
Reference in New Issue
Block a user