Roll forward to cl/314549634

Change-Id: I4d1e7eacd5fa4078a094571ad6d5f51e422535ff
This commit is contained in:
Himanshu Jaju
2020-06-03 11:18:32 -07:00
committed by Alexey Polyudov
parent ae1c427b99
commit cffbc04508
92 changed files with 3804 additions and 697 deletions
+42 -11
View File
@@ -1,12 +1,8 @@
cc_library(
name = "api",
name = "types",
hdrs = [
"atomic_boolean.h",
"atomic_reference.h",
"ble.h",
"ble_v2.h",
"bluetooth_adapter.h",
"bluetooth_classic.h",
"cancelable.h",
"condition_variable.h",
"count_down_latch.h",
@@ -17,12 +13,32 @@ cc_library(
"listenable_future.h",
"mutex.h",
"output_file.h",
"platform.h",
"scheduled_executor.h",
"server_sync.h",
"settable_future.h",
"submittable_executor.h",
"system_clock.h",
],
visibility = [
"//platform_v2/base:__pkg__",
"//platform_v2/impl:__subpackages__",
"//platform_v2/public:__pkg__",
],
deps = [
"//platform_v2/base",
"//absl/base:core_headers",
"//absl/strings",
"//absl/time",
],
)
cc_library(
name = "comm",
hdrs = [
"ble.h",
"ble_v2.h",
"bluetooth_adapter.h",
"bluetooth_classic.h",
"server_sync.h",
"webrtc.h",
"wifi.h",
"wifi_lan.h",
@@ -30,14 +46,29 @@ cc_library(
visibility = [
"//platform_v2/base:__pkg__",
"//platform_v2/impl:__subpackages__",
"//platform_v2/public:__subpackages__",
"//platform_v2/public:__pkg__",
],
deps = [
"//platform_v2/base",
"//absl/base:core_headers",
"//absl/strings",
"//absl/time",
"//absl/types:optional",
"//webrtc/api:libjingle_peerconnection_api",
],
)
cc_library(
name = "platform",
hdrs = [
"platform.h",
],
visibility = [
"//platform_v2/impl:__subpackages__",
"//platform_v2/public:__pkg__",
],
deps = [
":comm",
":types",
"//absl/strings",
"//absl/types:any",
"//webrtc/files/stable/webrtc/api:libjingle_peerconnection_api",
],
)
+4 -4
View File
@@ -5,13 +5,13 @@
#include <limits>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include "platform_v2/base/byte_array.h"
#include "platform_v2/base/exception.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
namespace location {
namespace nearby {
@@ -119,7 +119,7 @@ class ClientGattConnection {
//
// It is okay for duplicate services to exist, as long as the specified
// characteristic UUID is unique among all services of the same UUID.
virtual std::optional<GattCharacteristic> GetCharacteristic(
virtual absl::optional<GattCharacteristic> GetCharacteristic(
absl::string_view service_uuid,
absl::string_view characteristic_uuid) = 0;
@@ -127,7 +127,7 @@ class ClientGattConnection {
// https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html#getValue()
//
// Reads a GATT characteristic. No value is returned upon error.
virtual std::optional<ByteArray> ReadCharacteristic(
virtual absl::optional<ByteArray> ReadCharacteristic(
const GattCharacteristic& characteristic) = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html#setValue(byte[])
@@ -209,7 +209,7 @@ class GattServer {
// descriptor and subscribe for characteristic changes. For more information
// about this descriptor, please go to:
// https://www.bluetooth.com/specifications/Gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.Gatt.client_characteristic_configuration.xml
virtual std::optional<GattCharacteristic> CreateCharacteristic(
virtual absl::optional<GattCharacteristic> CreateCharacteristic(
absl::string_view service_uuid, absl::string_view characteristic_uuid,
const std::set<GattCharacteristic::Permission>& permissions,
const std::set<GattCharacteristic::Property>& properties) = 0;
+48 -33
View File
@@ -7,8 +7,8 @@
#include "platform_v2/base/byte_array.h"
#include "platform_v2/base/exception.h"
#include "platform_v2/base/input_stream.h"
#include "platform_v2/base/listeners.h"
#include "platform_v2/base/output_stream.h"
#include "absl/strings/string_view.h"
namespace location {
namespace nearby {
@@ -17,7 +17,7 @@ namespace api {
// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html.
class BluetoothDevice {
public:
virtual ~BluetoothDevice() {}
virtual ~BluetoothDevice() = default;
// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#getName()
virtual std::string GetName() const = 0;
@@ -26,32 +26,45 @@ class BluetoothDevice {
// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html.
class BluetoothSocket {
public:
virtual ~BluetoothSocket() {}
virtual ~BluetoothSocket() = default;
// Returns the InputStream of the BluetoothSocket.
// NOTE:
// It is an undefined behavior if GetInputStream() or GetOutputStream() is
// called for a not-connected BluetoothSocket, i.e. any object that is not
// returned by BluetoothClassicMedium::ConnectToService() for client side or
// BluetoothServerSocket::Accept() for server side of connection.
// Returns the InputStream of this connected BluetoothSocket.
virtual InputStream& GetInputStream() = 0;
// Returns the OutputStream of the BluetoothSocket.
// Returns the OutputStream of this connected BluetoothSocket.
virtual OutputStream& GetOutputStream() = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#close()
//
// Closes both input and output streams, marks Socket as closed.
// After this call object should be treated as not connected.
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
virtual Exception Close() = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#getRemoteDevice()
virtual BluetoothDevice& GetRemoteDevice() = 0;
// Returns valid BluetoothDevice pointer if there is a connection, and
// nullptr otherwise.
virtual BluetoothDevice* GetRemoteDevice() = 0;
};
// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html.
class BluetoothServerSocket {
public:
virtual ~BluetoothServerSocket() {}
virtual ~BluetoothServerSocket() = default;
// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#accept()
//
// returns Exception::kIo on error.
virtual ExceptionOr<std::unique_ptr<BluetoothSocket>> Accept() = 0;
// Blocks until either:
// - at least one incoming connection request is available, or
// - ServerSocket is closed.
// On success, returns connected socket, ready to exchange data.
// Returns nullptr on error.
// Once error is reported, it is permanent, and ServerSocket has to be closed.
virtual std::unique_ptr<BluetoothSocket> Accept() = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#close()
//
@@ -63,31 +76,33 @@ class BluetoothServerSocket {
// medium.
class BluetoothClassicMedium {
public:
virtual ~BluetoothClassicMedium() {}
virtual ~BluetoothClassicMedium() = default;
class DiscoveryCallback {
public:
virtual ~DiscoveryCallback() {}
// BluetoothDevice* is not owned by callbacks.
// Pointer is guaranteed to remain valid for the duration of a call.
virtual void OnDeviceDiscovered(BluetoothDevice* device) = 0;
virtual void OnDeviceNameChanged(BluetoothDevice* device) = 0;
virtual void OnDeviceLost(BluetoothDevice* device) = 0;
struct DiscoveryCallback {
// BluetoothDevice is a proxy object created as a result of BT discovery.
// Its lifetime spans between calls to device_discovered_cb and
// device_lost_cb.
// It is safe to use BluetoothDevice in device_discovered_cb() callback
// and at any time afterwards, until device_lost_cb() is called.
// It is not safe to use BluetoothDevice after returning from
// device_lost_cb() callback.
std::function<void(BluetoothDevice& device)> device_discovered_cb =
DefaultCallback<BluetoothDevice&>();
std::function<void(BluetoothDevice& device)> device_name_changed_cb =
DefaultCallback<BluetoothDevice&>();
std::function<void(BluetoothDevice& device)> device_lost_cb =
DefaultCallback<BluetoothDevice&>();
};
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#startDiscovery()
//
// Returns true once the process of discovery has been initiated.
//
// Does not take ownership of the passed-in discovery_callback -- destroying
// that is up to the caller.
virtual bool StartDiscovery(const DiscoveryCallback& discovery_callback) = 0;
virtual bool StartDiscovery(DiscoveryCallback discovery_callback) = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#cancelDiscovery()
//
// Returns true once discovery is well and truly stopped; after this returns,
// there must be no more invocations of the DiscoveryCallback passed in to
// startDiscovery().
// StartDiscovery().
virtual bool StopDiscovery() = 0;
// A combination of
@@ -101,10 +116,10 @@ class BluetoothClassicMedium {
// (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
// UUID.
//
// On success, returns a new BluetoothSocket, wrapped in a ExceptionOr object.
// On error, returns Exception object.
virtual ExceptionOr<std::unique_ptr<BluetoothSocket>> ConnectToService(
BluetoothDevice* remote_device, absl::string_view service_uuid) = 0;
// On success, returns a new BluetoothSocket.
// On error, returns nullptr.
virtual std::unique_ptr<BluetoothSocket> ConnectToService(
BluetoothDevice& remote_device, const std::string& service_uuid) = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#listenUsingInsecureRfcommWithServiceRecord
//
@@ -114,9 +129,9 @@ class BluetoothClassicMedium {
// (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
// UUID.
//
// Returns Exception::kIo on error.
virtual ExceptionOr<std::unique_ptr<BluetoothServerSocket>> ListenForService(
absl::string_view service_name, absl::string_view service_uuid) = 0;
// Returns nullptr error.
virtual std::unique_ptr<BluetoothServerSocket> ListenForService(
const std::string& service_name, const std::string& service_uuid) = 0;
};
} // namespace api
+7 -3
View File
@@ -14,7 +14,9 @@
#include "platform_v2/api/condition_variable.h"
#include "platform_v2/api/count_down_latch.h"
#include "platform_v2/api/crypto.h"
#include "platform_v2/api/input_file.h"
#include "platform_v2/api/mutex.h"
#include "platform_v2/api/output_file.h"
#include "platform_v2/api/scheduled_executor.h"
#include "platform_v2/api/server_sync.h"
#include "platform_v2/api/settable_future.h"
@@ -41,6 +43,7 @@ class ImplementationPlatform {
// - condition variable (must work with regular mutex only)
// - Future<T> : to synchronize on Callable<T> schduled to execute.
// - CountDownLatch : to ensure at least N threads are waiting.
// - file I/O
static std::unique_ptr<AtomicReference<absl::any>> CreateAtomicReferenceAny(
absl::any initial_value);
static std::unique_ptr<SettableFuture<absl::any>> CreateSettableFutureAny();
@@ -50,6 +53,9 @@ class ImplementationPlatform {
static std::unique_ptr<Mutex> CreateMutex(Mutex::Mode mode);
static std::unique_ptr<ConditionVariable> CreateConditionVariable(
Mutex* mutex);
static std::unique_ptr<InputFile> CreateInputFile(std::int64_t payload_id,
std::int64_t total_size);
static std::unique_ptr<OutputFile> CreateOutputFile(std::int64_t payload_id);
// Java-like Executors
static std::unique_ptr<SubmittableExecutor> CreateSingleThreadExecutor();
@@ -65,10 +71,8 @@ class ImplementationPlatform {
static std::unique_ptr<ServerSyncMedium> CreateServerSyncMedium();
static std::unique_ptr<WifiMedium> CreateWifiMedium();
static std::unique_ptr<WifiLanMedium> CreateWifiLanMedium();
static std::unique_ptr<WebRtcSignalingMessenger>
CreateWebRtcSignalingMessenger(absl::string_view self_id);
static std::unique_ptr<WebRtcMedium> CreateWebRtcMedium();
static std::string GetDeviceId();
static std::string GetPayloadPath(std::int64_t payload_id);
};
} // namespace api
+26 -26
View File
@@ -1,10 +1,11 @@
#ifndef PLATFORM_V2_API_WEBRTC_H_
#define PLATFORM_V2_API_WEBRTC_H_
#include <vector>
#include <memory>
#include "platform_v2/base/byte_array.h"
#include "webrtc/files/stable/webrtc/api/peer_connection_interface.h"
#include "absl/strings/string_view.h"
#include "webrtc/api/peer_connection_interface.h"
namespace location {
namespace nearby {
@@ -12,33 +13,32 @@ namespace api {
class WebRtcSignalingMessenger {
public:
using OnSignalingMessageCallback = std::function<void(const ByteArray&)>;
virtual ~WebRtcSignalingMessenger() = default;
/** Called whenever we receive an inbox message from tachyon. */
class SignalingMessageListener {
public:
virtual ~SignalingMessageListener() = default;
virtual void OnSignalingMessage(const ByteArray& message) = 0;
};
class IceServersListener {
public:
virtual ~IceServersListener() = default;
virtual void OnIceServersFetched(
std::vector<webrtc::PeerConnectionInterface::IceServer>
ice_servers) = 0;
};
virtual bool RegisterSignaling() = 0;
virtual bool UnregisterSignaling() = 0;
virtual bool SendMessage(std::string_view peer_id,
virtual bool SendMessage(absl::string_view peer_id,
const ByteArray& message) = 0;
virtual bool StartReceivingMessages(
const SignalingMessageListener& listener) = 0;
virtual void GetIceServers(
const IceServersListener& ice_servers_listener) = 0;
virtual bool StartReceivingMessages(OnSignalingMessageCallback listener) = 0;
virtual void StopReceivingMessages() = 0;
};
class WebRtcMedium {
public:
using PeerConnectionCallback =
std::function<void(rtc::scoped_refptr<webrtc::PeerConnectionInterface>)>;
virtual ~WebRtcMedium() = default;
// Creates and returns a new webrtc::PeerConnectionInterface object via
// |callback|.
virtual void CreatePeerConnection(webrtc::PeerConnectionObserver* observer,
PeerConnectionCallback callback) = 0;
// Returns a signaling messenger for sending WebRTC signaling messages.
virtual std::unique_ptr<WebRtcSignalingMessenger> GetSignalingMessenger(
absl::string_view self_id) = 0;
};
} // namespace api
+40 -1
View File
@@ -24,6 +24,7 @@ cc_library(
"//platform_v2/api:__subpackages__",
],
deps = [
"//absl/meta:type_traits",
"//absl/strings",
"//absl/time",
],
@@ -32,9 +33,11 @@ cc_library(
cc_library(
name = "util",
srcs = [
"base_input_stream.cc",
"base_pipe.cc",
],
hdrs = [
"base_input_stream.h",
"base_mutex_lock.h",
"base_pipe.h",
],
@@ -44,11 +47,47 @@ cc_library(
],
deps = [
":base",
"//platform_v2/api",
"//platform_v2/api:types",
"//absl/base:core_headers",
],
)
cc_library(
name = "logging",
hdrs = [
"logging.h",
],
visibility = [
"//platform_v2:__subpackages__",
],
deps = [
"//platform:logging",
],
)
cc_library(
name = "test_util",
testonly = True,
srcs = [
"medium_environment.cc",
],
hdrs = [
"medium_environment.h",
],
visibility = [
"//core_v2:__subpackages__",
"//platform_v2/impl:__subpackages__",
"//platform_v2/public:__pkg__",
],
deps = [
":base",
":logging",
"//platform_v2/api:comm",
"//platform_v2/public:types",
"//absl/container:flat_hash_map",
],
)
cc_test(
name = "platform_base_test",
srcs = [
+85
View File
@@ -0,0 +1,85 @@
#include "platform_v2/base/base_input_stream.h"
namespace location {
namespace nearby {
ExceptionOr<ByteArray> BaseInputStream::Read(std::int64_t size) {
if (!IsAvailable(size)) {
return ExceptionOr<ByteArray>{Exception::kIo};
}
ByteArray read_bytes{static_cast<size_t>(size)};
if (read_bytes.CopyAt(/*offset=*/0, buffer_,
/*source_offset=*/position_)) {
position_ += size;
return ExceptionOr<ByteArray>{read_bytes};
} else {
return ExceptionOr<ByteArray>{Exception::kIo};
}
}
std::uint8_t BaseInputStream::ReadUint8() {
constexpr int byte_size = sizeof(std::uint8_t);
ByteArray read_bytes = ReadBytes(byte_size);
if (read_bytes.Empty() || read_bytes.size() != byte_size) {
return -1;
}
return read_bytes.data()[0];
}
std::uint16_t BaseInputStream::ReadUint16() {
constexpr int byte_size = sizeof(std::uint16_t);
ByteArray read_bytes = ReadBytes(byte_size);
if (read_bytes.Empty() || read_bytes.size() != byte_size) {
return -1;
}
// Convert from network order.
const char *data = read_bytes.data();
return static_cast<uint16_t>(data[0]) << 8 | static_cast<uint16_t>(data[1]);
}
std::uint32_t BaseInputStream::ReadUint32() {
constexpr int byte_size = sizeof(std::uint32_t);
ByteArray read_bytes = ReadBytes(byte_size);
if (read_bytes.Empty() || read_bytes.size() != byte_size) {
return -1;
}
// Convert from network order.
const char *data = read_bytes.data();
return static_cast<uint32_t>(data[0]) << 24 |
static_cast<uint32_t>(data[1]) << 16 |
static_cast<uint32_t>(data[2]) << 8 | static_cast<uint32_t>(data[3]);
}
std::uint64_t BaseInputStream::ReadUint64() {
constexpr int byte_size = sizeof(std::uint64_t);
ByteArray read_bytes = ReadBytes(byte_size);
if (read_bytes.Empty() || read_bytes.size() != byte_size) {
return -1;
}
// Convert from network order.
const char *data = read_bytes.data();
return static_cast<uint64_t>(data[0]) << 56 |
static_cast<uint64_t>(data[1]) << 48 |
static_cast<uint64_t>(data[2]) << 40 |
static_cast<uint64_t>(data[3]) << 32 |
static_cast<uint64_t>(data[4]) << 24 |
static_cast<uint64_t>(data[5]) << 16 |
static_cast<uint64_t>(data[6]) << 8 | static_cast<uint64_t>(data[7]);
}
ByteArray BaseInputStream::ReadBytes(int size) {
ExceptionOr<ByteArray> read_bytes_result = Read(size);
if (!read_bytes_result.ok()) {
return ByteArray{};
}
return read_bytes_result.GetResult();
}
} // namespace nearby
} // namespace location
+44
View File
@@ -0,0 +1,44 @@
#ifndef PLATFORM_V2_BASE_BASE_INPUT_STREAM_H_
#define PLATFORM_V2_BASE_BASE_INPUT_STREAM_H_
#include "platform_v2/base/byte_array.h"
#include "platform_v2/base/exception.h"
#include "platform_v2/base/input_stream.h"
namespace location {
namespace nearby {
// A base {@link InputStream } for reading the contents of a byte array.
class BaseInputStream : public InputStream {
public:
explicit BaseInputStream(ByteArray &buffer) : buffer_{buffer} {}
BaseInputStream(const BaseInputStream &) = delete;
BaseInputStream &operator=(const BaseInputStream &) = delete;
~BaseInputStream() override { Close(); }
ExceptionOr<ByteArray> Read(std::int64_t size) override;
Exception Close() override {
// Do nothing.
return {Exception::kSuccess};
}
std::uint8_t ReadUint8();
std::uint16_t ReadUint16();
std::uint32_t ReadUint32();
std::uint64_t ReadUint64();
bool IsAvailable(int size) const {
return buffer_.size() - position_ >= size;
}
private:
ByteArray ReadBytes(int size);
ByteArray &buffer_;
int position_{0};
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_V2_BASE_BASE_INPUT_STREAM_H_
-1
View File
@@ -1,6 +1,5 @@
#include "platform_v2/base/base_pipe.h"
#include "platform_v2/api/platform.h"
#include "platform_v2/base/base_mutex_lock.h"
#include "platform_v2/base/input_stream.h"
#include "platform_v2/base/output_stream.h"
+3 -1
View File
@@ -19,7 +19,9 @@ class ByteArray {
ByteArray& operator=(ByteArray&&) = default;
// Create ByteArray from string.
explicit ByteArray(absl::string_view source) { data_ = source; }
explicit ByteArray(absl::string_view source) {
SetData(source.data(), source.size());
}
// Create default-initialized ByteArray of a given size.
explicit ByteArray(size_t size) { SetData(size); }
+3 -2
View File
@@ -1,9 +1,10 @@
#ifndef PLATFORM_V2_BASE_EXCEPTION_H_
#define PLATFORM_V2_BASE_EXCEPTION_H_
#include <type_traits>
#include <utility>
#include "absl/meta/type_traits.h"
namespace location {
namespace nearby {
@@ -64,7 +65,7 @@ class ExceptionOr {
ExceptionOr(Exception exception) : exception_{exception} {} // NOLINT
// If there exists explicit conversion from from U to T,
// then allow explicit conversion from ExceptionOr<U> to ExceptionOr<T>.
template <typename U, typename = std::void_t<decltype(T{std::declval<U>()})>>
template <typename U, typename = absl::void_t<decltype(T{std::declval<U>()})>>
explicit ExceptionOr<T>(ExceptionOr<U> value) {
if (!value.ok()) {
exception_ = value.GetException();
+6
View File
@@ -0,0 +1,6 @@
#ifndef PLATFORM_V2_BASE_LOGGING_H_
#define PLATFORM_V2_BASE_LOGGING_H_
#include "platform/logging.h"
#endif // PLATFORM_V2_BASE_LOGGING_H_
+191
View File
@@ -0,0 +1,191 @@
#include "platform_v2/base/medium_environment.h"
#include <atomic>
#include <cinttypes>
#include <new>
#include <type_traits>
#include "platform_v2/api/bluetooth_adapter.h"
#include "platform_v2/api/bluetooth_classic.h"
#include "platform_v2/base/logging.h"
#include "platform_v2/public/count_down_latch.h"
namespace location {
namespace nearby {
MediumEnvironment& MediumEnvironment::Instance() {
static std::aligned_storage_t<sizeof(MediumEnvironment),
alignof(MediumEnvironment)>
storage;
static MediumEnvironment* env = new (&storage) MediumEnvironment();
return *env;
}
void MediumEnvironment::Reset() {
RunOnMediumEnvironmentThread([this]() {
bluetooth_adapters_.clear();
bluetooth_mediums_.clear();
});
Sync();
}
void MediumEnvironment::Sync(bool enable_notifications) {
enable_notifications_ = enable_notifications;
int count = 0;
do {
CountDownLatch latch(1);
count = job_count_ + 1;
// We are about to schedule one last job.
// When it is done, counter must be equal to count.
// However, if pending jobs schedule anything else,
// it will be pending after us.
// If we want to ensure we are completely idle, then we have to
// repeat sync, until this becomes true.
RunOnMediumEnvironmentThread([&latch]() { latch.CountDown(); });
latch.Await();
} while (count < job_count_);
NEARBY_LOG(INFO, "MediumEnvironment::Sync(): done [count=%d]", count);
}
void MediumEnvironment::OnBluetoothAdapterChangedState(
api::BluetoothAdapter& adapter, api::BluetoothDevice& adapter_device,
std::string name, bool enabled, api::BluetoothAdapter::ScanMode mode) {
RunOnMediumEnvironmentThread([this, &adapter, &adapter_device,
name = std::move(name), enabled, mode]() {
NEARBY_LOG(INFO,
"[adapter=%p, device=%p] update: name=%s, enabled=%d, mode=%d",
&adapter, &adapter_device, name.c_str(), enabled, mode);
for (auto& [medium, info] : bluetooth_mediums_) {
// Do not send notification to medium that owns this adapter.
if (info.adapter == &adapter) continue;
NEARBY_LOG(INFO, "[adapter=%p, device=%p] notify: adapter=%p", &adapter,
&adapter_device, info.adapter);
OnDeviceStateChanged(info, adapter_device, name, mode, enabled);
}
// We don't care if there is an adapter already since all we store is a
// pointer. Pointer must remain valid for the duration of a Core session
// (since it is owned by the correspoinding Medium, and mediums lifetime
// matches Core lifetime).
bluetooth_adapters_.emplace(&adapter, &adapter_device);
});
}
void MediumEnvironment::OnDeviceStateChanged(
BluetoothMediumContext& info, api::BluetoothDevice& device,
const std::string& name, api::BluetoothAdapter::ScanMode mode,
bool enabled) {
auto item = info.devices.find(&device);
if (item == info.devices.end()) {
NEARBY_LOG(
INFO, "G3 OnDeviceStateChanged [device impl=%p]: new device; notify=%d",
&device, enable_notifications_.load());
if (mode == api::BluetoothAdapter::ScanMode::kConnectableDiscoverable &&
enabled) {
// New device is turned on, and is in discoverable state.
// Store device name, and report it as discovered.
info.devices.emplace(&device, name);
if (enable_notifications_) {
RunOnMediumEnvironmentThread(
[&info, &device]() { info.callback.device_discovered_cb(device); });
}
}
} else {
NEARBY_LOG(
INFO,
"G3 OnDeviceStateChanged [device impl=%p]: exisitng device; notify=%d",
&device, enable_notifications_.load());
auto& discovered_name = item->second;
if (mode == api::BluetoothAdapter::ScanMode::kConnectableDiscoverable &&
enabled) {
if (name != discovered_name) {
// Known device is turned on, and is in discoverable state.
// Store device name, and report it as renamed.
item->second = name;
if (enable_notifications_) {
RunOnMediumEnvironmentThread([&info, &device]() {
info.callback.device_name_changed_cb(device);
});
}
} else {
// Device is in discovery mode, so we are reporting it anyway.
if (enable_notifications_) {
RunOnMediumEnvironmentThread([&info, &device]() {
info.callback.device_discovered_cb(device);
});
}
}
}
if (!enabled) {
// Known device is turned off.
// Erase it from the map, and report as lost.
if (enable_notifications_) {
RunOnMediumEnvironmentThread(
[&info, &device]() { info.callback.device_lost_cb(device); });
}
info.devices.erase(item);
}
}
}
void MediumEnvironment::RunOnMediumEnvironmentThread(
std::function<void()> runnable) {
job_count_++;
executor_.Execute(std::move(runnable));
}
void MediumEnvironment::RegisterBluetoothMedium(
api::BluetoothClassicMedium& medium,
api::BluetoothAdapter& medium_adapter) {
RunOnMediumEnvironmentThread([this, &medium, &medium_adapter]() {
auto& context = bluetooth_mediums_
.insert({&medium,
BluetoothMediumContext{
.adapter = &medium_adapter,
}})
.first->second;
auto* owned_adapter = context.adapter;
NEARBY_LOG(INFO, "Registered: medium=%p; adapter=%p", &medium,
owned_adapter);
for (auto& [adapter, device] : bluetooth_adapters_) {
if (adapter == nullptr) continue;
OnDeviceStateChanged(context, *device, adapter->GetName(),
adapter->GetScanMode(), adapter->IsEnabled());
}
});
}
void MediumEnvironment::UpdateBluetoothMedium(
api::BluetoothClassicMedium& medium, BluetoothDiscoveryCallback callback) {
RunOnMediumEnvironmentThread([this, &medium,
callback = std::move(callback)]() {
auto item = bluetooth_mediums_.find(&medium);
if (item == bluetooth_mediums_.end()) return;
auto& context = item->second;
context.callback = std::move(callback);
auto* owned_adapter = context.adapter;
NEARBY_LOG(
INFO,
"Updated: this=%p; medium=%p; adapter=%p; name=%s; enabled=%d; mode=%d",
this, &medium, owned_adapter, owned_adapter->GetName().c_str(),
owned_adapter->IsEnabled(), owned_adapter->GetScanMode());
for (auto& [adapter, device] : bluetooth_adapters_) {
if (adapter == nullptr) continue;
OnDeviceStateChanged(context, *device, adapter->GetName(),
adapter->GetScanMode(), adapter->IsEnabled());
}
});
}
void MediumEnvironment::UnregisterBluetoothMedium(
api::BluetoothClassicMedium& medium) {
RunOnMediumEnvironmentThread([this, &medium]() {
auto item = bluetooth_mediums_.extract(&medium);
if (item.empty()) return;
auto& context = item.mapped();
NEARBY_LOG(INFO, "Unregistered medium for device=%s",
context.adapter->GetName().c_str());
});
}
} // namespace nearby
} // namespace location
+113
View File
@@ -0,0 +1,113 @@
#ifndef PLATFORM_V2_BASE_MEDIUM_ENVIRONMENT_H_
#define PLATFORM_V2_BASE_MEDIUM_ENVIRONMENT_H_
#include <atomic>
#include "platform_v2/api/bluetooth_adapter.h"
#include "platform_v2/api/bluetooth_classic.h"
#include "platform_v2/base/listeners.h"
#include "platform_v2/public/single_thread_executor.h"
#include "absl/container/flat_hash_map.h"
namespace location {
namespace nearby {
// MediumEnvironment is a simulated environment which allows multiple instances
// of simulated HW devices to "work" together as if they are physical.
// For each medium type it provides necessary methods to implement
// advertising, discovery and establishment of a data link.
// NOTE: this code depends on public:types target.
class MediumEnvironment {
public:
using BluetoothDiscoveryCallback =
api::BluetoothClassicMedium::DiscoveryCallback;
MediumEnvironment(const MediumEnvironment&) = delete;
MediumEnvironment& operator=(const MediumEnvironment&) = delete;
// Creates and returns a reference to the global test environment instance.
static MediumEnvironment& Instance();
// Clears state. No notifications are sent.
void Reset();
// Waits for all previously scheduled jobs to finish.
// This method works as a barrier that guarantees that after it returns, all
// the activities that started before it was called, or while it was running
// are ended. This means that system is at the state of relaxation when this
// code returns. It requires external stimulus to get out of relaxation state.
//
// If enable_notifications is true (default), simulation environment
// will send all future notification events to all registered objects,
// whenever protocol requires that. This is expected behavior.
// If enabled_notifications is false, future event notifications will not be
// sent to registered instances. This is useful for protocol shutdown,
// where we no longer care about notifications, and where notifications may
// otherwise be delivered after the notification source or target lifeteme has
// ended, and cause undefined behavior.
void Sync(bool enable_notifications = true);
// Adds an adapter to internal container.
// Notify BluetoothClassicMediums if any that adapter state has changed.
void OnBluetoothAdapterChangedState(api::BluetoothAdapter& adapter,
api::BluetoothDevice& adapter_device,
std::string name, bool enabled,
api::BluetoothAdapter::ScanMode mode);
// Adds medium-related info to allow for adapter discovery to work.
// This provides acccess to this medium from other mediums, when protocol
// expects they should communicate.
void RegisterBluetoothMedium(api::BluetoothClassicMedium& medium,
api::BluetoothAdapter& medium_adapter);
// Updates callback info to allow for dispatch of discovery events.
//
// Invokes callback asynchronously when any changes happen to discoverable
// devices, or if the defice is turned off, whether or not it is discoverable,
// if it was ever reported as discoverable.
//
// This should be called when discoverable state changes.
// with user-specified callback when discovery is enabled, and with default
// (empty) callback otherwise.
void UpdateBluetoothMedium(api::BluetoothClassicMedium& medium,
BluetoothDiscoveryCallback callback);
// Removes medium-related info. This should correspond to device power off.
void UnregisterBluetoothMedium(api::BluetoothClassicMedium& medium);
private:
struct BluetoothMediumContext {
BluetoothDiscoveryCallback callback;
api::BluetoothAdapter* adapter = nullptr;
// discovered device vs device name map.
absl::flat_hash_map<api::BluetoothDevice*, std::string> devices;
};
// This is a singleton object, for which destructor will never be called.
// Constructor will be invoked once from Instance() static method.
// Object is create in-place (with a placement new) to guarantee that
// destructor is not scheduled for execution at exit.
MediumEnvironment() = default;
~MediumEnvironment() = default;
void OnDeviceStateChanged(BluetoothMediumContext& info,
api::BluetoothDevice& device,
const std::string& name,
api::BluetoothAdapter::ScanMode mode, bool enabled);
void RunOnMediumEnvironmentThread(std::function<void()> runnable);
std::atomic_int job_count_ = 0;
std::atomic_bool enable_notifications_ = false;
SingleThreadExecutor executor_;
// The following data members are accessed in the context of a private
// executor_ thread.
absl::flat_hash_map<api::BluetoothAdapter*, api::BluetoothDevice*>
bluetooth_adapters_;
absl::flat_hash_map<api::BluetoothClassicMedium*, BluetoothMediumContext>
bluetooth_mediums_;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_V2_BASE_MEDIUM_ENVIRONMENT_H_
+65 -18
View File
@@ -1,38 +1,32 @@
cc_library(
name = "g3",
name = "types",
testonly = True,
srcs = [
"scheduled_executor.cc",
"system_clock.cc",
],
hdrs = [
"atomic_boolean.h",
"atomic_reference_any.h",
"bluetooth_adapter.cc",
"bluetooth_adapter.h",
"condition_variable.h",
"count_down_latch.h",
"medium_environment.cc",
"medium_environment.h",
"multi_thread_executor.h",
"mutex.h",
"platform.cc",
"scheduled_executor.cc",
"pipe.h",
"scheduled_executor.h",
"settable_future_any.h",
"single_thread_executor.h",
"system_clock.cc",
],
visibility = [
"//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
"//core_v2:__subpackages__",
"//platform_v2:__subpackages__",
"//platform_v2/impl/g3:__pkg__",
],
deps = [
":crypto", # build_cleaner: keep
"//platform_v2/api",
"//platform_v2/api:platform",
"//platform_v2/api:types",
"//platform_v2/base",
"//platform_v2/base:util",
"//platform_v2/impl/shared:posix_mutex",
"//absl/base:core_headers",
"//absl/container:flat_hash_map",
"//absl/container:flat_hash_set",
"//absl/memory",
"//absl/strings",
"//absl/synchronization",
"//absl/time",
"//absl/types:any",
@@ -40,8 +34,36 @@ cc_library(
],
)
cc_library(
name = "comm",
testonly = True,
srcs = [
"bluetooth_adapter.cc",
"webrtc.cc",
],
hdrs = [
"bluetooth_adapter.h",
"webrtc.h",
],
visibility = [
"//platform_v2/impl/g3:__pkg__",
],
deps = [
":types",
"//platform_v2/api:comm",
"//platform_v2/base:test_util",
"//absl/base:core_headers",
"//absl/strings",
"//absl/synchronization",
"//webrtc/api:create_peerconnection_factory", #buildcleaner: keep
"//webrtc/api:libjingle_peerconnection_api",
"//webrtc/api/task_queue:default_task_queue_factory",
],
)
cc_library(
name = "crypto",
testonly = True,
srcs = [
"crypto.cc",
],
@@ -49,9 +71,34 @@ cc_library(
"//platform_v2/g3:__pkg__",
],
deps = [
"//platform_v2/api",
"//platform_v2/api:types",
"//platform_v2/base",
"//absl/strings",
"//openssl:crypto",
],
)
cc_library(
name = "g3",
testonly = True,
srcs = [
"platform.cc",
],
visibility = [
"//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
"//core_v2:__subpackages__",
"//platform_v2:__subpackages__",
],
deps = [
":comm",
":crypto", # build_cleaner: keep
":types",
"//platform_v2/api:comm",
"//platform_v2/api:platform",
"//platform_v2/api:types",
"//platform_v2/impl/shared:file",
"//absl/base:core_headers",
"//absl/memory",
"//absl/time",
],
)
+37 -22
View File
@@ -2,7 +2,7 @@
#include <string>
#include "platform_v2/impl/g3/medium_environment.h"
#include "platform_v2/base/medium_environment.h"
namespace location {
namespace nearby {
@@ -11,15 +11,22 @@ namespace g3 {
BluetoothDevice::BluetoothDevice(BluetoothAdapter* adapter)
: adapter_(*adapter) {}
BluetoothAdapter::~BluetoothAdapter() { SetStatus(Status::kDisabled); }
std::string BluetoothDevice::GetName() const { return adapter_.GetName(); }
bool BluetoothAdapter::SetStatus(Status status) ABSL_LOCKS_EXCLUDED(mutex_) {
absl::MutexLock lock(&mutex_);
enabled_ = (status == Status::kEnabled);
RunOnCallbackThread([this]() {
auto& env = MediumEnvironment::Instance();
env.OnBluetoothAdapterChangedState(*this);
});
bool BluetoothAdapter::SetStatus(Status status) {
BluetoothAdapter::ScanMode mode;
bool enabled = status == Status::kEnabled;
std::string name;
{
absl::MutexLock lock(&mutex_);
enabled_ = enabled;
name = name_;
mode = mode_;
}
auto& env = MediumEnvironment::Instance();
env.OnBluetoothAdapterChangedState(*this, device_, name, enabled, mode);
return true;
}
@@ -34,13 +41,17 @@ BluetoothAdapter::ScanMode BluetoothAdapter::GetScanMode() const {
}
bool BluetoothAdapter::SetScanMode(BluetoothAdapter::ScanMode mode) {
absl::MutexLock lock(&mutex_);
if (enabled_) return false;
mode_ = mode;
RunOnCallbackThread([this]() {
auto& env = MediumEnvironment::Instance();
env.OnBluetoothAdapterChangedState(*this);
});
bool enabled;
std::string name;
{
absl::MutexLock lock(&mutex_);
mode_ = mode;
name = name_;
enabled = enabled_;
}
auto& env = MediumEnvironment::Instance();
env.OnBluetoothAdapterChangedState(*this, device_, std::move(name), enabled,
mode);
return true;
}
@@ -50,13 +61,17 @@ std::string BluetoothAdapter::GetName() const {
}
bool BluetoothAdapter::SetName(absl::string_view name) {
absl::MutexLock lock(&mutex_);
if (enabled_) return false;
name_ = name;
RunOnCallbackThread([this]() {
auto& env = MediumEnvironment::Instance();
env.OnBluetoothAdapterChangedState(*this);
});
BluetoothAdapter::ScanMode mode;
bool enabled;
{
absl::MutexLock lock(&mutex_);
name_ = name;
enabled = enabled_;
mode = mode_;
}
auto& env = MediumEnvironment::Instance();
env.OnBluetoothAdapterChangedState(*this, device_, std::string(name), enabled,
mode);
return true;
}
+3 -8
View File
@@ -24,7 +24,7 @@ class BluetoothDevice : public api::BluetoothDevice {
// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#getName()
std::string GetName() const override;
BluetoothAdapter& GetAdapter();
BluetoothAdapter& GetAdapter() { return adapter_; }
private:
// Only BluetoothAdapter may instantiate BluetoothDevice.
@@ -41,8 +41,8 @@ class BluetoothAdapter : public api::BluetoothAdapter {
using Status = api::BluetoothAdapter::Status;
using ScanMode = api::BluetoothAdapter::ScanMode;
BluetoothAdapter() = default;
~BluetoothAdapter() override = default;
explicit BluetoothAdapter() = default;
~BluetoothAdapter() override;
// Synchronously sets the status of the BluetoothAdapter to 'status', and
// returns true if the operation was a success.
@@ -71,16 +71,11 @@ class BluetoothAdapter : public api::BluetoothAdapter {
BluetoothDevice& GetDevice() { return device_; }
private:
void RunOnCallbackThread(std::function<void()> runnable) {
serial_executor_.Execute(std::move(runnable));
}
mutable absl::Mutex mutex_;
BluetoothDevice device_{this};
ScanMode mode_ ABSL_GUARDED_BY(mutex_) = ScanMode::kNone;
std::string name_ ABSL_GUARDED_BY(mutex_) = "unknown G3 BT device";
bool enabled_ ABSL_GUARDED_BY(mutex_) = false;
SingleThreadExecutor serial_executor_;
};
} // namespace g3
@@ -1,32 +0,0 @@
#include "platform_v2/impl/g3/medium_environment.h"
namespace location {
namespace nearby {
namespace g3 {
MediumEnvironment& MediumEnvironment::Instance() {
static std::aligned_storage_t<sizeof(MediumEnvironment),
alignof(MediumEnvironment)>
storage;
static MediumEnvironment* env = new (&storage) MediumEnvironment();
return *env;
}
void MediumEnvironment::Reset() {
absl::MutexLock lock(&mutex_);
bluetooth_adapters_.clear();
}
void MediumEnvironment::OnBluetoothAdapterChangedState(
BluetoothAdapter& adapter) {
absl::MutexLock lock(&mutex_);
// We don't care if there is an adapter already since all we store is a
// pointer.
bluetooth_adapters_.emplace(&adapter);
// TODO(apolyudov): Add event propagation code when Medium registration is
// implemented.
}
} // namespace g3
} // namespace nearby
} // namespace location
@@ -1,47 +0,0 @@
#ifndef PLATFORM_V2_IMPL_G3_MEDIUM_ENVIRONMENT_H_
#define PLATFORM_V2_IMPL_G3_MEDIUM_ENVIRONMENT_H_
#include <new>
#include <string>
#include <type_traits>
#include "platform_v2/api/bluetooth_classic.h"
#include "platform_v2/impl/g3/bluetooth_adapter.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/synchronization/mutex.h"
namespace location {
namespace nearby {
namespace g3 {
// MediumEnvironment is a simulated environment which allowes multiple instances
// of simulated HW devices to "work" together as if they are physical.
// For each medium type it provides necessary methods to implement
// advertising, discovery and establishment of a data link.
class MediumEnvironment {
public:
~MediumEnvironment() = default;
// Singleton constructor/accessor.
static MediumEnvironment& Instance();
// Clear state. No notifications are sent.
void Reset() ABSL_LOCKS_EXCLUDED(mutex_);
// Add an adapter to internal container.
// Notify BluetoothClassicMediums if any that adapter state has changed.
void OnBluetoothAdapterChangedState(BluetoothAdapter& adapter)
ABSL_LOCKS_EXCLUDED(mutex_);
private:
MediumEnvironment() = default;
absl::Mutex mutex_;
absl::flat_hash_set<BluetoothAdapter*> bluetooth_adapters_
ABSL_GUARDED_BY(mutex_);
};
} // namespace g3
} // namespace nearby
} // namespace location
#endif // PLATFORM_V2_IMPL_G3_MEDIUM_ENVIRONMENT_H_
+21 -9
View File
@@ -28,6 +28,8 @@
#include "platform_v2/impl/g3/scheduled_executor.h"
#include "platform_v2/impl/g3/settable_future_any.h"
#include "platform_v2/impl/g3/single_thread_executor.h"
#include "platform_v2/impl/g3/webrtc.h"
#include "platform_v2/impl/shared/file.h"
#include "absl/base/integral_types.h"
#include "absl/memory/memory.h"
#include "absl/time/time.h"
@@ -36,6 +38,12 @@ namespace location {
namespace nearby {
namespace api {
namespace {
std::string GetPayloadPath(std::int64_t payload_id) {
return "/tmp/" + std::to_string(payload_id);
}
} // namespace
std::unique_ptr<SubmittableExecutor>
ImplementationPlatform::CreateSingleThreadExecutor() {
return absl::make_unique<g3::SingleThreadExecutor>();
@@ -76,6 +84,17 @@ std::unique_ptr<AtomicBoolean> ImplementationPlatform::CreateAtomicBoolean(
return absl::make_unique<g3::AtomicBoolean>(initial_value);
}
std::unique_ptr<InputFile> ImplementationPlatform::CreateInputFile(
std::int64_t payload_id, std::int64_t total_size) {
return absl::make_unique<shared::InputFile>(GetPayloadPath(payload_id),
total_size);
}
std::unique_ptr<OutputFile> ImplementationPlatform::CreateOutputFile(
std::int64_t payload_id) {
return absl::make_unique<shared::OutputFile>(GetPayloadPath(payload_id));
}
std::unique_ptr<BluetoothClassicMedium>
ImplementationPlatform::CreateBluetoothClassicMedium() {
return std::unique_ptr<BluetoothClassicMedium>();
@@ -102,11 +121,8 @@ std::unique_ptr<WifiLanMedium> ImplementationPlatform::CreateWifiLanMedium() {
return std::unique_ptr<WifiLanMedium>();
}
std::unique_ptr<WebRtcSignalingMessenger>
ImplementationPlatform::CreateWebRtcSignalingMessenger(
absl::string_view self_id) {
return std::unique_ptr<WebRtcSignalingMessenger>(
/*new FCMSignalingMessenger()*/);
std::unique_ptr<WebRtcMedium> ImplementationPlatform::CreateWebRtcMedium() {
return absl::make_unique<g3::WebRtcMedium>();
}
std::unique_ptr<Mutex> ImplementationPlatform::CreateMutex(Mutex::Mode mode) {
@@ -127,10 +143,6 @@ std::string ImplementationPlatform::GetDeviceId() {
return "google3";
}
std::string ImplementationPlatform::GetPayloadPath(int64_t payload_id) {
return "/tmp/" + std::to_string(payload_id);
}
} // namespace api
} // namespace nearby
} // namespace location
+36
View File
@@ -0,0 +1,36 @@
#include "platform_v2/impl/g3/webrtc.h"
#include "webrtc/api/task_queue/default_task_queue_factory.h"
namespace location {
namespace nearby {
namespace g3 {
void WebRtcMedium::CreatePeerConnection(
webrtc::PeerConnectionObserver* observer, PeerConnectionCallback callback) {
webrtc::PeerConnectionInterface::RTCConfiguration rtc_config;
webrtc::PeerConnectionDependencies dependencies(observer);
std::unique_ptr<rtc::Thread> signaling_thread = rtc::Thread::Create();
signaling_thread->SetName("signaling_thread", nullptr);
RTC_CHECK(signaling_thread->Start()) << "Failed to start thread";
webrtc::PeerConnectionFactoryDependencies factory_dependencies;
factory_dependencies.task_queue_factory =
webrtc::CreateDefaultTaskQueueFactory();
factory_dependencies.signaling_thread = signaling_thread.release();
callback(webrtc::CreateModularPeerConnectionFactory(
std::move(factory_dependencies))
->CreatePeerConnection(rtc_config, std::move(dependencies)));
}
std::unique_ptr<api::WebRtcSignalingMessenger>
WebRtcMedium::GetSignalingMessenger(absl::string_view self_id) {
// TODO(bfranz): Implement
return nullptr;
}
} // namespace g3
} // namespace nearby
} // namespace location
+35
View File
@@ -0,0 +1,35 @@
#ifndef PLATFORM_V2_IMPL_G3_WEBRTC_H_
#define PLATFORM_V2_IMPL_G3_WEBRTC_H_
#include <memory>
#include "platform_v2/api/webrtc.h"
#include "absl/strings/string_view.h"
#include "webrtc/api/peer_connection_interface.h"
namespace location {
namespace nearby {
namespace g3 {
class WebRtcMedium : public api::WebRtcMedium {
public:
using PeerConnectionCallback = api::WebRtcMedium::PeerConnectionCallback;
WebRtcMedium() = default;
~WebRtcMedium() override = default;
// Creates and returns a new webrtc::PeerConnectionInterface object via
// |callback|.
void CreatePeerConnection(webrtc::PeerConnectionObserver* observer,
PeerConnectionCallback callback) override;
// Returns a signaling messenger for sending WebRTC signaling messages.
std::unique_ptr<api::WebRtcSignalingMessenger> GetSignalingMessenger(
absl::string_view self_id) override;
};
} // namespace g3
} // namespace nearby
} // namespace location
#endif // PLATFORM_V2_IMPL_G3_WEBRTC_H_
+26 -5
View File
@@ -9,10 +9,7 @@ cc_library(
visibility = [
"//platform_v2/impl:__subpackages__",
],
deps = [
"//platform_v2/api",
"//platform_v2/base",
],
deps = ["//platform_v2/api:types"],
)
cc_library(
@@ -28,7 +25,31 @@ cc_library(
],
deps = [
":posix_mutex",
"//platform_v2/api",
"//platform_v2/api:types",
],
)
cc_library(
name = "file",
srcs = ["file.cc"],
hdrs = ["file.h"],
visibility = [
"//platform_v2/impl:__subpackages__",
],
deps = [
"//platform_v2/api:types",
"//platform_v2/base",
"//absl/strings",
],
)
cc_test(
name = "file_test",
srcs = ["file_test.cc"],
deps = [
":file",
"//file/util:temp_path",
"//platform_v2/base",
"//testing/base/public:gunit_main",
],
)
@@ -1,4 +1,4 @@
#include "platform_v2/public/file.h"
#include "platform_v2/impl/shared/file.h"
#include <cstddef>
#include <memory>
@@ -8,6 +8,7 @@
namespace location {
namespace nearby {
namespace shared {
// InputFile
@@ -47,7 +48,7 @@ Exception InputFile::Close() {
// OutputFile
OutputFile::OutputFile(absl::string_view path) : file_(path) {}
OutputFile::OutputFile(absl::string_view path) : file_(std::string(path)) {}
Exception OutputFile::Write(const ByteArray& data) {
if (!file_.is_open()) {
@@ -75,5 +76,6 @@ Exception OutputFile::Close() {
return {Exception::kSuccess};
}
} // namespace shared
} // namespace nearby
} // namespace location
+53
View File
@@ -0,0 +1,53 @@
#ifndef PLATFORM_V2_IMPL_SHARED_FILE_H_
#define PLATFORM_V2_IMPL_SHARED_FILE_H_
#include <cstdint>
#include <fstream>
#include "platform_v2/api/input_file.h"
#include "platform_v2/api/output_file.h"
#include "platform_v2/base/exception.h"
#include "absl/strings/string_view.h"
namespace location {
namespace nearby {
namespace shared {
class InputFile final : public api::InputFile {
public:
explicit InputFile(const std::string& path, std::int64_t size);
~InputFile() override = default;
InputFile(InputFile&&) = default;
InputFile& operator=(InputFile&&) = default;
ExceptionOr<ByteArray> Read(std::int64_t size) override;
std::string GetFilePath() const override { return path_; }
std::int64_t GetTotalSize() const override { return total_size_; }
Exception Close() override;
private:
std::ifstream file_;
std::string path_;
std::int64_t total_size_;
};
class OutputFile final : public api::OutputFile {
public:
explicit OutputFile(absl::string_view path);
~OutputFile() override = default;
OutputFile(OutputFile&&) = default;
OutputFile& operator=(OutputFile&&) = default;
Exception Write(const ByteArray& data) override;
Exception Flush() override;
Exception Close() override;
private:
std::ofstream file_;
};
} // namespace shared
} // namespace nearby
} // namespace location
#endif // PLATFORM_V2_IMPL_SHARED_FILE_H_
@@ -1,4 +1,4 @@
#include "platform_v2/public/file.h"
#include "platform_v2/impl/shared/file.h"
#include <cstring>
#include <fstream>
@@ -11,6 +11,7 @@
namespace location {
namespace nearby {
namespace shared {
class FileTest : public ::testing::Test {
protected:
@@ -127,5 +128,6 @@ TEST_F(FileTest, OutputFile_Close) {
EXPECT_EQ(output_file.Write(bytes), Exception{Exception::kIo});
}
} // namespace shared
} // namespace nearby
} // namespace location
+27 -12
View File
@@ -1,13 +1,11 @@
cc_library(
name = "public",
name = "types",
srcs = [
"file.cc",
"pipe.cc",
],
hdrs = [
"atomic_boolean.h",
"atomic_reference.h",
"bluetooth_adapter.h",
"cancelable.h",
"cancelable_alarm.h",
"condition_variable.h",
@@ -26,19 +24,38 @@ cc_library(
],
visibility = [
"//core_v2:__subpackages__",
"//platform_v2/impl:__subpackages__",
"//platform_v2/base:__pkg__",
"//platform_v2/public:__pkg__",
],
deps = [
"//platform_v2/api",
"//platform_v2/api:platform",
"//platform_v2/api:types",
"//platform_v2/base",
"//platform_v2/base:util",
"//absl/base:core_headers",
"//absl/strings",
"//absl/time",
"//absl/types:any",
],
)
cc_library(
name = "comm",
hdrs = [
"bluetooth_adapter.h",
"webrtc.h",
],
visibility = [
"//core_v2:__subpackages__",
"//platform_v2/public:__pkg__",
],
deps = [
"//platform_v2/api:comm",
"//platform_v2/api:platform",
"//absl/strings",
"//webrtc/api:libjingle_peerconnection_api",
],
)
cc_library(
name = "logging",
hdrs = [
@@ -50,7 +67,7 @@ cc_library(
"//platform_v2:__subpackages__",
],
deps = [
"//platform:logging",
"//platform_v2/base:logging",
],
)
@@ -62,7 +79,6 @@ cc_test(
"bluetooth_adapter_test.cc",
"count_down_latch_test.cc",
"crypto_test.cc",
"file_test.cc",
"future_test.cc",
"logging_test.cc",
"multi_thread_executor_test.cc",
@@ -73,13 +89,12 @@ cc_test(
],
shard_count = 16,
deps = [
":comm",
":logging",
":public",
"//file/util:temp_path",
":types",
"//platform_v2/base",
"//platform_v2/impl/g3",
"//platform_v2/impl/g3", # build_cleaner: keep
"//testing/base/public:gunit_main",
"//absl/strings",
"//absl/synchronization",
"//absl/time",
],
+21 -15
View File
@@ -2,47 +2,53 @@
#define PLATFORM_V2_PUBLIC_FILE_H_
#include <cstdint>
#include <fstream>
#include <memory>
#include <string>
#include "platform_v2/api/input_file.h"
#include "platform_v2/api/output_file.h"
#include "platform_v2/api/platform.h"
#include "platform_v2/base/byte_array.h"
#include "platform_v2/base/exception.h"
#include "absl/strings/string_view.h"
namespace location {
namespace nearby {
class InputFile final : public api::InputFile {
public:
explicit InputFile(const std::string& path, std::int64_t size);
using Platform = api::ImplementationPlatform;
InputFile(std::int64_t payload_id, std::int64_t size)
: impl_(Platform::CreateInputFile(payload_id, size)) {}
~InputFile() override = default;
InputFile(InputFile&&) = default;
InputFile& operator=(InputFile&&) = default;
ExceptionOr<ByteArray> Read(std::int64_t size) override;
std::string GetFilePath() const override { return path_; }
std::int64_t GetTotalSize() const override { return total_size_; }
Exception Close() override;
ExceptionOr<ByteArray> Read(std::int64_t size) override {
return impl_->Read(size);
}
std::string GetFilePath() const override { return impl_->GetFilePath(); }
std::int64_t GetTotalSize() const override { return impl_->GetTotalSize(); }
Exception Close() override { return impl_->Close(); }
private:
std::ifstream file_;
std::string path_;
std::int64_t total_size_;
std::unique_ptr<api::InputFile> impl_;
};
class OutputFile final : public api::OutputFile {
public:
explicit OutputFile(absl::string_view path);
using Platform = api::ImplementationPlatform;
explicit OutputFile(std::int64_t payload_id)
: impl_(Platform::CreateOutputFile(payload_id)) {}
~OutputFile() override = default;
OutputFile(OutputFile&&) = default;
OutputFile& operator=(OutputFile&&) = default;
Exception Write(const ByteArray& data) override;
Exception Flush() override;
Exception Close() override;
Exception Write(const ByteArray& data) override { return impl_->Write(data); }
Exception Flush() override { return impl_->Flush(); }
Exception Close() override { return impl_->Close(); }
private:
std::ofstream file_;
std::unique_ptr<api::OutputFile> impl_;
};
} // namespace nearby
+2 -2
View File
@@ -33,7 +33,7 @@ class Future final : public api::SettableFuture<T> {
ExceptionOr<T> Get() override {
auto ret_val = impl_->Get();
if (ret_val.ok()) {
T result = std::any_cast<T>(ret_val.result());
T result = absl::any_cast<T>(ret_val.result());
return ExceptionOr<T>{result};
} else {
return ExceptionOr<T>{ret_val.exception()};
@@ -46,7 +46,7 @@ class Future final : public api::SettableFuture<T> {
ExceptionOr<T> Get(absl::Duration timeout) override {
auto ret_val = impl_->Get(timeout);
if (ret_val.ok()) {
T result = std::any_cast<T>(ret_val.result());
T result = absl::any_cast<T>(ret_val.result());
return ExceptionOr<T>{result};
} else {
return ExceptionOr<T>{ret_val.exception()};
+1 -1
View File
@@ -1,6 +1,6 @@
#ifndef PLATFORM_V2_PUBLIC_LOGGING_H_
#define PLATFORM_V2_PUBLIC_LOGGING_H_
#include "platform/logging.h"
#include "platform_v2/base/logging.h"
#endif // PLATFORM_V2_PUBLIC_LOGGING_H_
+44
View File
@@ -0,0 +1,44 @@
#ifndef PLATFORM_V2_PUBLIC_WEBRTC_H_
#define PLATFORM_V2_PUBLIC_WEBRTC_H_
#include <memory>
#include "platform_v2/api/platform.h"
#include "platform_v2/api/webrtc.h"
#include "webrtc/api/peer_connection_interface.h"
namespace location {
namespace nearby {
class WebRtcMedium final {
public:
using PeerConnectionCallback = api::WebRtcMedium::PeerConnectionCallback;
WebRtcMedium() : impl_(api::ImplementationPlatform::CreateWebRtcMedium()) {}
~WebRtcMedium() = default;
WebRtcMedium(WebRtcMedium&&) = delete;
WebRtcMedium& operator=(WebRtcMedium&&) = delete;
// Creates and returns a new webrtc::PeerConnectionInterface object via
// |callback|.
void CreatePeerConnection(webrtc::PeerConnectionObserver* observer,
PeerConnectionCallback callback) {
impl_->CreatePeerConnection(observer, std::move(callback));
}
// Returns a signaling messenger for sending WebRTC signaling messages.
std::unique_ptr<api::WebRtcSignalingMessenger> GetSignalingMessenger(
absl::string_view self_id) {
return impl_->GetSignalingMessenger(self_id);
}
bool IsValid() const { return impl_ != nullptr; }
private:
std::unique_ptr<api::WebRtcMedium> impl_;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_V2_PUBLIC_WEBRTC_H_