Roll forward to cl/338482889

Signed-off-by: Alexey Polyudov <apolyudov@google.com>
Change-Id: I9850950db8bd84f0904ea1a413151887f52098cf
This commit is contained in:
Alexey Polyudov
2020-10-22 10:47:34 -07:00
parent d68e53cf03
commit 2155b3ddeb
542 changed files with 15219 additions and 42295 deletions
+54 -46
View File
@@ -1,69 +1,77 @@
package(default_visibility = [
"//core:__subpackages__",
"//platform:__subpackages__",
"//location/nearby/setup/core:__subpackages__",
])
cc_library(
name = "api",
name = "types",
hdrs = [
"atomic_boolean.h",
"atomic_reference.h",
"atomic_reference_def.h",
"cancelable.h",
"condition_variable.h",
"count_down_latch.h",
"crypto.h",
"executor.h",
"future.h",
"input_file.h",
"listenable_future.h",
"log_message.h",
"mutex.h",
"output_file.h",
"scheduled_executor.h",
"settable_future.h",
"submittable_executor.h",
"system_clock.h",
],
visibility = [
"//platform/base:__pkg__",
"//platform/impl:__subpackages__",
"//platform/public:__pkg__",
],
deps = [
"//platform/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",
"condition_variable.h",
"count_down_latch.h",
"executor.h",
"future.h",
"hash_utils.h",
"input_file.h",
"input_stream.h",
"listenable_future.h",
"lock.h",
"multi_thread_executor.h",
"output_file.h",
"output_stream.h",
"platform.h",
"scheduled_executor.h",
"server_sync.h",
"settable_future.h",
"settable_future_def.h",
"single_thread_executor.h",
"socket.h",
"submittable_executor.h",
"submittable_executor_def.h",
"system_clock.h",
"thread_utils.h",
"webrtc.h",
"wifi.h",
"wifi_lan.h",
],
visibility = [
"//platform/base:__pkg__",
"//platform/impl:__subpackages__",
"//platform/public:__pkg__",
],
deps = [
"//platform:types",
"//platform/port:down_cast",
"//platform/port:string",
"//proto/connections:offline_wire_formats_portable_proto",
"//platform/base",
"//absl/strings",
"//absl/types:any",
"//absl/types:optional",
"//webrtc/api:libjingle_peerconnection_api",
],
)
cc_library(
name = "lock",
hdrs = ["lock.h"],
name = "platform",
hdrs = [
"platform.h",
],
visibility = [
"//platform:__subpackages__",
"//platform/base:__pkg__",
"//platform/impl:__subpackages__",
"//platform/public:__pkg__",
],
deps = [
":comm",
":types",
"//platform/base",
"//absl/strings",
],
)
cc_library(
name = "condition_variable",
hdrs = ["condition_variable.h"],
visibility = [
"//platform:__subpackages__",
],
deps = ["//platform:types"],
)
+8 -5
View File
@@ -3,18 +3,21 @@
namespace location {
namespace nearby {
namespace api {
// A boolean value that may be updated atomically.
//
// https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicBoolean.html
class AtomicBoolean {
public:
virtual ~AtomicBoolean() {}
virtual ~AtomicBoolean() = default;
virtual bool get() = 0;
virtual void set(bool value) = 0;
// Atomically read and return current value.
virtual bool Get() const = 0;
// Atomically exchange original value with a new one. Return previous value.
virtual bool Set(bool value) = 0;
};
} // namespace api
} // namespace nearby
} // namespace location
+10 -33
View File
@@ -1,48 +1,25 @@
#ifndef PLATFORM_API_ATOMIC_REFERENCE_H_
#define PLATFORM_API_ATOMIC_REFERENCE_H_
#include "platform/api/atomic_reference_def.h"
#include "platform/api/platform.h"
#include "platform/ptr.h"
#include "absl/types/any.h"
#include <cstdint>
namespace location {
namespace nearby {
namespace api {
// "Common" part of implementation.
// Placed here for textual compatibility to minimize scope of changes.
// Can be (and should be) moved to a separate file outside "api" folder.
// TODO(apolyudov): for API v2.0
namespace platform {
namespace impl {
template <typename T>
class AtomicReferenceImpl : public AtomicReference<T> {
// Type that allows 32-bit atomic reads and writes.
class AtomicUint32 {
public:
explicit AtomicReferenceImpl(T initial_value) {
atomic_ = platform::ImplementationPlatform::createAtomicReferenceAny(
absl::any(initial_value));
}
virtual ~AtomicUint32() = default;
~AtomicReferenceImpl() override = default;
// Atomically reads and returns stored value.
virtual std::uint32_t Get() const = 0;
void set(T new_value) override { atomic_->set(absl::any(new_value)); }
T get() override { return absl::any_cast<T>(atomic_->get()); }
private:
Ptr<AtomicReference<absl::any>> atomic_;
// Atomically stores value.
virtual void Set(std::uint32_t value) = 0;
};
} // namespace impl
template <typename T>
Ptr<AtomicReference<T>> ImplementationPlatform::createAtomicReference(
T initial_value) {
return Ptr<AtomicReference<T>>(
new impl::AtomicReferenceImpl<T>{initial_value});
}
} // namespace platform
} // namespace api
} // namespace nearby
} // namespace location
-27
View File
@@ -1,27 +0,0 @@
#ifndef PLATFORM_API_ATOMIC_REFERENCE_DEF_H_
#define PLATFORM_API_ATOMIC_REFERENCE_DEF_H_
namespace location {
namespace nearby {
// An object reference that may be updated atomically.
//
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicReference.html
//
// Platform must implentent non-template static member functions
// Ptr<AtomicReference<size_t>> CreateAtomicReferenceSizeT()
// Ptr<AtomicReference<std::shared_ptr<void>>> CreateAtomicReferencePtr()
// in the location::nearby::platform::ImplementationPlatform class.
template <typename T>
class AtomicReference {
public:
virtual ~AtomicReference() = default;
virtual T get() = 0;
virtual void set(T value) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_ATOMIC_REFERENCE_DEF_H_
+61 -76
View File
@@ -2,122 +2,107 @@
#define PLATFORM_API_BLE_H_
#include "platform/api/bluetooth_classic.h"
#include "platform/api/input_stream.h"
#include "platform/api/output_stream.h"
#include "platform/byte_array.h"
#include "platform/ptr.h"
#include "platform/base/byte_array.h"
#include "platform/base/input_stream.h"
#include "platform/base/output_stream.h"
namespace location {
namespace nearby {
namespace api {
// Opaque wrapper over a BLE peripheral. Must contain enough data about a
// particular BLE device to connect to its GATT server.
class BLEPeripheral {
class BlePeripheral {
public:
virtual ~BLEPeripheral() {}
virtual ~BlePeripheral() = default;
// The returned Ptr is not owned by the caller, and can be invalidated once
// the corresponding BLEPeripheral object is destroyed.
virtual Ptr<BluetoothDevice> getBluetoothDevice() = 0;
virtual std::string GetName() const = 0;
virtual ByteArray GetAdvertisementBytes(
const std::string& service_id) const = 0;
};
class BLESocket {
class BleSocket {
public:
virtual ~BLESocket() {}
virtual ~BleSocket() = default;
// Returns the InputStream of the BLESocket, or a null Ptr<InputStream>
// on error.
// Returns the InputStream of the BleSocket.
// On error, returned stream will report Exception::kIo on any operation.
//
// The returned Ptr is not owned by the caller, and can be invalidated once
// the BLESocket object is destroyed.
virtual Ptr<InputStream> getInputStream() = 0;
// The returned object is not owned by the caller, and can be invalidated once
// the BleSocket object is destroyed.
virtual InputStream& GetInputStream() = 0;
// Returns the OutputStream of the BLESocket, or a null
// Ptr<OutputStream> on error.
// Returns the OutputStream of the BleSocket.
// On error, returned stream will report Exception::kIo on any operation.
//
// The returned Ptr is not owned by the caller, and can be invalidated once
// the BLESocket object is destroyed.
virtual Ptr<OutputStream> getOutputStream() = 0;
// The returned object is not owned by the caller, and can be invalidated once
// the BleSocket object is destroyed.
virtual OutputStream& GetOutputStream() = 0;
// Conforms to the same contract as
// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#close().
//
// Returns Exception::IO on error, Exception::NONE otherwise.
virtual Exception::Value close() = 0;
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
virtual Exception Close() = 0;
// The returned Ptr is not owned by the caller, and can be invalidated once
// the BLESocket object is destroyed.
virtual Ptr<BLEPeripheral> getRemotePeripheral() = 0;
// Returns valid BlePeripheral pointer if there is a connection, and
// nullptr otherwise.
virtual BlePeripheral* GetRemotePeripheral() = 0;
};
// Container of operations that can be performed over the BLE medium.
class BLEMedium {
class BleMedium {
public:
virtual ~BLEMedium() {}
virtual ~BleMedium() = default;
// Takes ownership of (and is responsible for destroying) the passed-in
// 'advertisement'.
virtual bool startAdvertising(const std::string& service_id,
ConstPtr<ByteArray> advertisement) = 0;
virtual void stopAdvertising(const std::string& service_id) = 0;
virtual bool StartAdvertising(
const std::string& service_id, const ByteArray& advertisement_bytes,
const std::string& fast_advertisement_service_uuid) = 0;
virtual bool StopAdvertising(const std::string& service_id) = 0;
class DiscoveredPeripheralCallback {
public:
virtual ~DiscoveredPeripheralCallback() {}
// The Ptrs provided in these callback methods will be owned (and
// destroyed) by the recipient of the callback methods (i.e. the creator of
// the concrete DiscoveredPeripheralCallback object).
virtual void onPeripheralDiscovered(Ptr<BLEPeripheral> ble_peripheral,
const std::string& service_id,
ConstPtr<ByteArray> advertisement) = 0;
virtual void onPeripheralLost(Ptr<BLEPeripheral> ble_peripheral,
const std::string& service_id) = 0;
// Callback that is invoked when a discovered peripheral is found or lost.
struct DiscoveredPeripheralCallback {
std::function<void(BlePeripheral& peripheral, const std::string& service_id,
bool fast_advertisement)>
peripheral_discovered_cb =
DefaultCallback<BlePeripheral&, const std::string&, bool>();
std::function<void(BlePeripheral& peripheral,
const std::string& service_id)>
peripheral_lost_cb =
DefaultCallback<BlePeripheral&, const std::string&>();
};
// Returns true once the BLE scan has been initiated.
//
// Does not take ownership of the passed-in discovered_peripheral_callback --
// destroying that is up to the caller.
virtual bool startScanning(
const std::string& service_id,
Ptr<DiscoveredPeripheralCallback> discovered_peripheral_callback) = 0;
virtual bool StartScanning(const std::string& service_id,
const std::string& fast_advertisement_service_uuid,
DiscoveredPeripheralCallback callback) = 0;
// Returns true once BLE scanning for service_id is well and truly stopped;
// after this returns, there must be no more invocations of the
// DiscoveredPeripheralCallback passed in to startScanning() for service_id.
//
// Does not need to bother with destroying the DiscoveredPeripheralCallback
// passed in to startScanning() -- that's the job of the caller.
virtual void stopScanning(const std::string& service_id) = 0;
// DiscoveredPeripheralCallback passed in to StartScanning() for service_id.
virtual bool StopScanning(const std::string& service_id) = 0;
// Callback that is invoked when a new connection is accepted.
class AcceptedConnectionCallback {
public:
virtual ~AcceptedConnectionCallback() {}
// The Ptr provided in this callback method will be owned (and
// destroyed) by the recipient of the callback methods (i.e. the creator of
// the concrete AcceptedConnectionCallback object).
virtual void onConnectionAccepted(Ptr<BLESocket> socket,
const std::string& service_id) = 0;
struct AcceptedConnectionCallback {
std::function<void(BleSocket& socket, const std::string& service_id)>
accepted_cb = DefaultCallback<BleSocket&, const std::string&>();
};
// Returns true once BLE socket connection requests to service_id can be
// accepted.
//
// Does not take ownership of the passed-in accepted_connection_callback --
// destroying that is up to the caller.
virtual bool startAcceptingConnections(
const std::string& service_id,
Ptr<AcceptedConnectionCallback> accepted_connection_callback) = 0;
virtual void stopAcceptingConnections(const std::string& service_id) = 0;
virtual bool StartAcceptingConnections(
const std::string& service_id, AcceptedConnectionCallback callback) = 0;
virtual bool StopAcceptingConnections(const std::string& service_id) = 0;
// The returned Ptr will be owned (and destroyed) by the caller. Returns
// a null Ptr<BleSocket> on error.
virtual Ptr<BLESocket> connect(Ptr<BLEPeripheral> ble_peripheral,
const std::string& service_id) = 0;
// Connects to a BLE peripheral.
// On success, returns a new BleSocket.
// On error, returns nullptr.
virtual std::unique_ptr<BleSocket> Connect(BlePeripheral& peripheral,
const std::string& service_id) = 0;
};
} // namespace api
} // namespace nearby
} // namespace location
+130 -142
View File
@@ -4,15 +4,19 @@
#include <cstdint>
#include <limits>
#include <map>
#include <memory>
#include <set>
#include <string>
#include "platform/byte_array.h"
#include "platform/exception.h"
#include "platform/port/string.h"
#include "platform/ptr.h"
#include "platform/base/byte_array.h"
#include "platform/base/exception.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
namespace location {
namespace nearby {
namespace api {
namespace ble_v2 {
// https://developer.android.com/reference/android/bluetooth/le/AdvertiseData
//
@@ -21,16 +25,16 @@ namespace nearby {
// All service UUIDs will conform to the 16-bit Bluetooth base UUID,
// 0000xxxx-0000-1000-8000-00805F9B34FB. This makes it possible to store two
// byte service UUIDs in the advertisement.
struct BLEAdvertisementData {
typedef std::int8_t TXPowerLevel;
struct BleAdvertisementData {
using TxPowerLevel = int8_t;
static constexpr TXPowerLevel UNSPECIFIED_TX_POWER_LEVEL =
std::numeric_limits<TXPowerLevel>::min();
static const TxPowerLevel kUnspecifiedTxPowerLevel =
std::numeric_limits<TxPowerLevel>::min();
bool is_connectable;
// When set to UNSPECIFIED_TX_POWER_LEVEL, TX power should not be included in
// When set to kUnspecifiedTxPowerLevel, TX power should not be included in
// the advertisement data.
TXPowerLevel tx_power_level;
TxPowerLevel tx_power_level;
// When set to an empty string, local name should not be included in the
// advertisement data.
std::string local_name;
@@ -38,75 +42,64 @@ struct BLEAdvertisementData {
// not be included in the advertisement data.
std::set<std::string> service_uuids;
// Maps service UUIDs to their service data.
// Ownership of the map values is tied to ownership of BLEAdvertisementData.
std::map<std::string, ConstPtr<ByteArray>> service_data;
std::map<std::string, ByteArray> service_data;
};
// Opaque wrapper over a BLE peripheral. Must be able to uniquely identify a
// peripheral so that we can connect to its GATT server.
//
// BLEPeripheralV2 should always be created as a RefCountedPtr because ownership
// is shared between the per-platform implementation and the internals of Nearby
// Connections.
class BLEPeripheralV2 {
class BlePeripheral {
public:
virtual ~BLEPeripheralV2() {}
virtual ~BlePeripheral() {}
// https://developer.android.com/reference/android/bluetooth/BluetoothDevice#getAddress()
//
// This should be the MAC address when possible. If the implementation is
// unable to retrieve that, any unique identifier should suffice.
virtual std::string getId() = 0;
virtual std::string GetId() const = 0;
};
// https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic
//
// Representation of a GATT characteristic.
//
// GATTCharacteristics are RefCounted so that ownership can be shared between
// the per-platform implementation and C++ internals. All GATTCharacteristics
// should be created with MakeRefCountedPtr().
class GATTCharacteristic {
class GattCharacteristic {
public:
virtual ~GATTCharacteristic() {}
virtual ~GattCharacteristic() {}
// Possible permissions of a GATT characteristic.
struct Permission {
enum Value {
UNKNOWN = 0,
READ = 1,
WRITE = 2,
};
enum class Permission {
kUnknown = 0,
kRead = 1,
kWrite = 2,
kLast,
};
// Possible properties of a GATT characteristic.
struct Property {
enum Value {
UNKNOWN = 0,
READ = 1,
WRITE = 2,
INDICATE = 3,
};
enum class Property {
kUnknown = 0,
kRead = 1,
kWrite = 2,
kIndicate = 3,
kLast,
};
// Returns the UUID of this characteristic.
virtual std::string getUUID() = 0;
virtual std::string GetUuid() = 0;
// Returns the UUID of the containing GATT service.
virtual std::string getServiceUUID() = 0;
virtual std::string GetServiceUuid() = 0;
};
// https://developer.android.com/reference/android/bluetooth/BluetoothGatt
//
// Representation of a client GATT connection to a remote GATT server.
class ClientGATTConnection {
class ClientGattConnection {
public:
virtual ~ClientGATTConnection() {}
virtual ~ClientGattConnection() {}
// https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#getDevice()
//
// Retrieves the BLE peripheral that this connection is tied to.
virtual Ptr<BLEPeripheralV2> getPeripheral() = 0;
virtual BlePeripheral& GetPeripheral() = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#discoverServices()
//
@@ -114,49 +107,49 @@ class ClientGATTConnection {
// Returns whether or not discovery finished successfully.
//
// This function should block until discovery has finished.
virtual bool discoverServices() = 0;
virtual bool DiscoverServices() = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#getService(java.util.UUID)
// https://developer.android.com/reference/android/bluetooth/BluetoothGattService.html#getCharacteristic(java.util.UUID)
//
// Retrieves a GATT characteristic. A null Ptr is returned upon error.
// Retrieves a GATT characteristic. On error, does not return a value.
//
// discoverServices() should be called before this method to fetch all
// DiscoverServices() should be called before this method to fetch all
// available services and characteristics first.
//
// 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 Ptr<GATTCharacteristic> getCharacteristic(
const std::string& service_uuid,
const std::string& characteristic_uuid) = 0;
virtual absl::optional<GattCharacteristic> GetCharacteristic(
absl::string_view service_uuid,
absl::string_view characteristic_uuid) = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#readCharacteristic(android.bluetooth.BluetoothGattCharacteristic)
// https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html#getValue()
//
// Reads a GATT characteristic. A null ConstPtr is returned upon error.
virtual ConstPtr<ByteArray> readCharacteristic(
Ptr<GATTCharacteristic> characteristic) = 0;
// Reads a GATT characteristic. No value is returned upon error.
virtual absl::optional<ByteArray> ReadCharacteristic(
const GattCharacteristic& characteristic) = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html#setValue(byte[])
// https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#writeCharacteristic(android.bluetooth.BluetoothGattCharacteristic)
//
// Sends a remote characteristic write request to the server and returns
// whether or not it was successful.
virtual bool writeCharacteristic(Ptr<GATTCharacteristic> characteristic,
ConstPtr<ByteArray> value) = 0;
virtual bool WriteCharacteristic(const GattCharacteristic& characteristic,
const ByteArray& value) = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#disconnect()
//
// Disconnects a GATT connection.
virtual void disconnect() = 0;
virtual void Disconnect() = 0;
};
// https://developer.android.com/reference/android/bluetooth/BluetoothGattServer
//
// Representation of a server GATT connection to a remote GATT client.
class ServerGATTConnection {
class ServerGattConnection {
public:
virtual ~ServerGATTConnection() {}
virtual ~ServerGattConnection() {}
// https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html#setValue(byte[])
// https://developer.android.com/reference/android/bluetooth/BluetoothGattServer.html#notifyCharacteristicChanged(android.bluetooth.BluetoothDevice,%20android.bluetooth.BluetoothGattCharacteristic,%20boolean)
@@ -165,47 +158,47 @@ class ServerGATTConnection {
// has changed with the given value. Returns whether or not it was successful.
//
// The value sent does not have to reflect the locally stored characteristic
// value. To update the local value, call GATTServer::updateCharacteristic.
virtual bool sendCharacteristic(Ptr<GATTCharacteristic> characteristic,
ConstPtr<ByteArray> value) = 0;
// value. To update the local value, call GattServer::UpdateCharacteristic.
virtual bool SendCharacteristic(const GattCharacteristic& characteristic,
const ByteArray& value) = 0;
};
// Callback for asynchronous events on the client side of a GATT connection.
class ClientGATTConnectionLifecycleCallback {
class ClientGattConnectionLifeCycleCallback {
public:
virtual ~ClientGATTConnectionLifecycleCallback() {}
virtual ~ClientGattConnectionLifeCycleCallback() {}
// Called when the client is disconnected from the GATT server.
virtual void onDisconnected(Ptr<ClientGATTConnection> connection) = 0;
virtual void OnDisconnected(ClientGattConnection* connection) = 0;
};
// Callback for asynchronous events on the server side of a GATT connection.
class ServerGATTConnectionLifecycleCallback {
class ServerGattConnectionLifeCycleCallback {
public:
virtual ~ServerGATTConnectionLifecycleCallback() {}
virtual ~ServerGattConnectionLifeCycleCallback() {}
// Called when a remote peripheral connected to us and subscribed to one of
// our characteristics.
virtual void onCharacteristicSubscription(
Ptr<ServerGATTConnection> connection,
Ptr<GATTCharacteristic> characteristic) = 0;
virtual void OnCharacteristicSubscription(
ServerGattConnection* connection,
const GattCharacteristic& characteristic) = 0;
// Called when a remote peripheral unsubscribed from one of our
// characteristics.
virtual void onCharacteristicUnsubscription(
Ptr<ServerGATTConnection> connection,
Ptr<GATTCharacteristic> characteristic) = 0;
virtual void OnCharacteristicUnsubscription(
ServerGattConnection* connection,
const GattCharacteristic& characteristic) = 0;
};
// https://developer.android.com/reference/android/bluetooth/BluetoothGattServer
//
// Representation of a BLE GATT server.
class GATTServer {
class GattServer {
public:
virtual ~GATTServer() {}
virtual ~GattServer() {}
// Creates a characteristic and adds it to the GATT server under the given
// characteristic and service UUIDs. Returns a null Ptr upon error.
// characteristic and service UUIDs. Returns no value upon error.
//
// Characteristics of the same service UUID should be put under one
// service rather than many services with the same UUID.
@@ -215,12 +208,11 @@ class GATTServer {
// 0x2902 and a WRITE permission. This allows remote clients to write to this
// 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 Ptr<GATTCharacteristic> createCharacteristic(
const std::string& service_uuid,
const std::string& characteristic_uuid,
const std::set<GATTCharacteristic::Permission::Value>& permissions,
const std::set<GATTCharacteristic::Property::Value>& properties) = 0;
// https://www.bluetooth.com/specifications/Gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.Gatt.client_characteristic_configuration.xml
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;
// https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html#setValue(byte[])
//
@@ -228,67 +220,66 @@ class GATTServer {
// was successful.
// Takes ownership of (and is responsible for destroying) the passed-in
// 'value'.
virtual bool updateCharacteristic(Ptr<GATTCharacteristic> characteristic,
ConstPtr<ByteArray> value) = 0;
virtual bool UpdateCharacteristic(const GattCharacteristic& characteristic,
const ByteArray& value) = 0;
// Stops a GATT server.
virtual void stop() = 0;
virtual void Stop() = 0;
};
// A BLE socket representation.
class BLESocketV0 {
class BleSocket {
public:
virtual ~BLESocketV0() {}
virtual ~BleSocket() {}
// Returns the remote BLE peripheral tied to this socket.
virtual Ptr<BLEPeripheralV2> getRemotePeripheral() = 0;
virtual BlePeripheral& GetRemotePeripheral() = 0;
// Writes a message on the socket and blocks until finished. Returns
// Exception::IO upon error, and Exception::NONE otherwise.
virtual Exception::Value write(ConstPtr<ByteArray> message) = 0;
// Exception::kIo upon error, and Exception::kSuccess otherwise.
virtual Exception Write(const ByteArray& message) = 0;
// Closes the socket and blocks until finished. Returns Exception::IO upon
// error, and Exception::NONE otherwise.
virtual Exception::Value close() = 0;
// Closes the socket and blocks until finished. Returns Exception::kIo upon
// error, and Exception::kSuccess otherwise.
virtual Exception Close() = 0;
};
// Callback for asynchronous events on a BLESocketV0 object.
class BLESocketLifecycleCallback {
// Callback for asynchronous events on a BleSocket object.
class BleSocketLifeCycleCallback {
public:
virtual ~BLESocketLifecycleCallback() {}
virtual ~BleSocketLifeCycleCallback() {}
// Called when a message arrives on a socket.
virtual void onMessageReceived(Ptr<BLESocketV0> socket,
ConstPtr<ByteArray> message) = 0;
virtual void OnMessageReceived(BleSocket* socket,
const ByteArray& message) = 0;
// Called when a socket gets disconnected.
virtual void onDisconnected(Ptr<BLESocketV0> socket) = 0;
virtual void OnDisconnected(BleSocket* socket) = 0;
};
// Callback for asynchronous events on the server side of a BLESocketV0 object.
class ServerBLESocketLifecycleCallback : public BLESocketLifecycleCallback {
// Callback for asynchronous events on the server side of a BleSocket object.
class ServerBleSocketLifeCycleCallback : public BleSocketLifeCycleCallback {
public:
~ServerBLESocketLifecycleCallback() override {}
~ServerBleSocketLifeCycleCallback() override {}
// Called when a new incoming socket has been established.
virtual void onSocketEstablished(Ptr<BLESocketV0> socket) = 0;
virtual void OnSocketEstablished(BleSocket* socket) = 0;
};
// The main BLE medium used inside of Nearby. This serves as the entry point for
// all BLE and GATT related operations.
class BLEMediumV2 {
class BleMedium {
public:
virtual ~BLEMediumV2() {}
using Mtu = uint32_t;
typedef std::uint32_t MTU;
virtual ~BleMedium() {}
// Coarse representation of power settings throughout all BLE operations.
struct PowerMode {
enum Value {
UNKNOWN = 0,
LOW = 1,
HIGH = 2,
};
enum class PowerMode {
kUnknown = 0,
kLow = 1,
kHigh = 2,
kLast,
};
// https://developer.android.com/reference/android/bluetooth/le/BluetoothLeAdvertiser.html#startAdvertising(android.bluetooth.le.AdvertiseSettings,%20android.bluetooth.le.AdvertiseData,%20android.bluetooth.le.AdvertiseData,%20android.bluetooth.le.AdvertiseCallback)
@@ -302,15 +293,14 @@ class BLEMediumV2 {
// HIGH:
// - Advertising interval = ~100ms
// - TX power = high
virtual bool startAdvertising(
ConstPtr<BLEAdvertisementData> advertisement_data,
ConstPtr<BLEAdvertisementData> scan_response,
PowerMode::Value power_mode) = 0;
virtual bool StartAdvertising(const BleAdvertisementData& advertisement_data,
const BleAdvertisementData& scan_response,
PowerMode power_mode) = 0;
// https://developer.android.com/reference/android/bluetooth/le/BluetoothLeAdvertiser.html#stopAdvertising(android.bluetooth.le.AdvertiseCallback)
//
// Stops advertising.
virtual void stopAdvertising() = 0;
virtual void StopAdvertising() = 0;
// https://developer.android.com/reference/android/bluetooth/le/ScanCallback
//
@@ -329,11 +319,11 @@ class BLEMediumV2 {
// Every discovery of an advertisement should be reported, even if the
// advertisement was discovered before.
//
// Ownership of the BLEAdvertisementData transfers to the caller at this
// Ownership of the BleAdvertisementData transfers to the caller at this
// point.
virtual void onAdvertisementFound(
Ptr<BLEPeripheralV2> peripheral,
ConstPtr<BLEAdvertisementData> advertisement_data) = 0;
virtual void OnAdvertisementFound(
BlePeripheral* peripheral,
const BleAdvertisementData& advertisement_data) = 0;
};
// https://developer.android.com/reference/android/bluetooth/le/BluetoothLeScanner.html#startScan(java.util.List%3Candroid.bluetooth.le.ScanFilter%3E,%20android.bluetooth.le.ScanSettings,%20android.bluetooth.le.ScanCallback)
@@ -347,35 +337,34 @@ class BLEMediumV2 {
// HIGH:
// - Scan window = ~4096ms
// - Scan interval = ~4096ms
virtual bool startScanning(const std::set<std::string>& service_uuids,
PowerMode::Value power_mode,
Ptr<ScanCallback> scan_callback) = 0;
virtual bool StartScanning(const std::set<std::string>& service_uuids,
PowerMode power_mode,
const ScanCallback& scan_callback) = 0;
// https://developer.android.com/reference/android/bluetooth/le/BluetoothLeScanner.html#stopScan(android.bluetooth.le.ScanCallback)
//
// Stops scanning.
virtual void stopScanning() = 0;
virtual void StopScanning() = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothManager#openGattServer(android.content.Context,%20android.bluetooth.BluetoothGattServerCallback)
//
// Starts a GATT server. Returns a null Ptr upon error.
virtual Ptr<GATTServer> startGATTServer(
Ptr<ServerGATTConnectionLifecycleCallback>
connection_lifecycle_callback) = 0;
// Starts a GATT server. Returns a nullptr upon error.
virtual std::unique_ptr<GattServer> StartGattServer(
const ServerGattConnectionLifeCycleCallback& callback) = 0;
// Starts listening for incoming BLE sockets and returns false upon error.
virtual bool startListeningForIncomingBLESockets(
Ptr<ServerBLESocketLifecycleCallback> socket_lifecycle_callback) = 0;
virtual bool StartListeningForIncomingBleSockets(
const ServerBleSocketLifeCycleCallback& callback) = 0;
// Stops listening for incoming BLE sockets.
virtual void stopListeningForIncomingBLESockets() = 0;
virtual void StopListeningForIncomingBleSockets() = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#connectGatt(android.content.Context,%20boolean,%20android.bluetooth.BluetoothGattCallback)
// https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#requestConnectionPriority(int)
// https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#requestMtu(int)
//
// Connects to a GATT server and negotiates the specified connection
// parameters. Returns a null Ptr upon error.
// parameters. Returns nullptr upon error.
//
// Both connection interval and MTU can be negotiated on a best-effort basis.
//
@@ -384,20 +373,19 @@ class BLEMediumV2 {
// - Connection interval = ~11.25ms - 15ms
// HIGH:
// - Connection interval = ~100ms - 125ms
virtual Ptr<ClientGATTConnection> connectToGATTServer(
Ptr<BLEPeripheralV2> peripheral,
MTU mtu,
PowerMode::Value power_mode,
Ptr<ClientGATTConnectionLifecycleCallback>
connection_lifecycle_callback) = 0;
virtual std::unique_ptr<ClientGattConnection> ConnectToGattServer(
BlePeripheral* peripheral, Mtu mtu, PowerMode power_mode,
const ClientGattConnectionLifeCycleCallback& callback) = 0;
// Establishes a BLE socket to the specified remote peripheral. Returns a null
// Ptr on error.
virtual Ptr<BLESocketV0> establishBLESocket(
Ptr<BLEPeripheralV2> ble_peripheral,
Ptr<BLESocketLifecycleCallback> socket_lifecycle_callback) = 0;
// Establishes a BLE socket to the specified remote peripheral. Returns
// nullptr on error.
virtual std::unique_ptr<BleSocket> EstablishBleSocket(
BlePeripheral* peripheral,
const BleSocketLifeCycleCallback& callback) = 0;
};
} // namespace ble_v2
} // namespace api
} // namespace nearby
} // namespace location
+26 -23
View File
@@ -1,57 +1,60 @@
#ifndef PLATFORM_API_BLUETOOTH_ADAPTER_H_
#define PLATFORM_API_BLUETOOTH_ADAPTER_H_
#include "platform/port/string.h"
#include "platform/ptr.h"
#include <string>
#include "absl/strings/string_view.h"
namespace location {
namespace nearby {
namespace api {
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html
class BluetoothAdapter {
public:
virtual ~BluetoothAdapter() {}
virtual ~BluetoothAdapter() = default;
// Eligible statuses of the BluetoothAdapter.
struct Status {
enum Value {
DISABLED,
ENABLED,
};
enum class Status {
kDisabled,
kEnabled,
};
// Synchronously sets the status of the BluetoothAdapter to 'status', and
// returns true if the operation was a success.
virtual bool setStatus(Status::Value status) = 0;
virtual bool SetStatus(Status status) = 0;
// Returns true if the BluetoothAdapter's current status is
// Status::Value::ENABLED.
virtual bool isEnabled() = 0;
// Status::Value::kEnabled.
virtual bool IsEnabled() const = 0;
// Scan modes of a BluetoothAdapter, as described at
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getScanMode().
struct ScanMode {
enum Value {
UNKNOWN,
CONNECTABLE_DISCOVERABLE,
};
enum class ScanMode {
kUnknown,
kNone,
kConnectable,
kConnectableDiscoverable,
};
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getScanMode()
//
// Returns ScanMode::UNKNOWN on error.
virtual ScanMode::Value getScanMode() = 0;
// Returns ScanMode::kUnknown on error.
virtual ScanMode GetScanMode() const = 0;
// Synchronously sets the scan mode of the adapter, and returns true if the
// operation was a success.
virtual bool setScanMode(ScanMode::Value scan_mode) = 0;
virtual bool SetScanMode(ScanMode scan_mode) = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getName()
//
// Returns a null Ptr<string> on error.
virtual Ptr<std::string> getName() = 0;
// Returns an empty string on error
virtual std::string GetName() const = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#setName(java.lang.String)
virtual bool setName(const std::string& name) = 0;
virtual bool SetName(absl::string_view name) = 0;
// Returns BT MAC address assigned to this adapter.
virtual std::string GetMacAddress() const = 0;
};
} // namespace api
} // namespace nearby
} // namespace location
+70 -65
View File
@@ -1,107 +1,112 @@
#ifndef PLATFORM_API_BLUETOOTH_CLASSIC_H_
#define PLATFORM_API_BLUETOOTH_CLASSIC_H_
#include "platform/api/input_stream.h"
#include "platform/api/output_stream.h"
#include "platform/byte_array.h"
#include "platform/exception.h"
#include "platform/port/string.h"
#include "platform/ptr.h"
#include <memory>
#include <string>
#include "platform/base/byte_array.h"
#include "platform/base/exception.h"
#include "platform/base/input_stream.h"
#include "platform/base/listeners.h"
#include "platform/base/output_stream.h"
namespace location {
namespace nearby {
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() = 0;
virtual std::string GetName() const = 0;
// Returns BT MAC address assigned to this device.
virtual std::string GetMacAddress() const = 0;
};
// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html.
class BluetoothSocket {
public:
virtual ~BluetoothSocket() {}
virtual ~BluetoothSocket() = default;
// Returns the InputStream of the BluetoothSocket, or a null Ptr<InputStream>
// on error.
//
// The returned Ptr is not owned by the caller, and can be invalidated once
// the BluetoothSocket object is destroyed.
virtual Ptr<InputStream> getInputStream() = 0;
// 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 OutputStream of the BluetoothSocket, or a null
// Ptr<OutputStream> on error.
//
// The returned Ptr is not owned by the caller, and can be invalidated once
// the BluetoothSocket object is destroyed.
virtual Ptr<OutputStream> getOutputStream() = 0;
// Returns the InputStream of this connected BluetoothSocket.
virtual InputStream& GetInputStream() = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#close()
//
// Returns Exception::IO on error, Exception::NONE otherwise.
virtual Exception::Value close() = 0;
// Returns the OutputStream of this connected BluetoothSocket.
virtual OutputStream& GetOutputStream() = 0;
// 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()
//
// The returned Ptr is not owned by the caller, and can be invalidated once
// the BluetoothSocket object is destroyed.
virtual Ptr<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()
//
// The returned Ptr will be owned (and destroyed) by the caller. Returns
// Exception::IO on error.
virtual ExceptionOr<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()
//
// Returns Exception::IO on error, Exception::NONE otherwise.
virtual Exception::Value close() = 0;
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
virtual Exception Close() = 0;
};
// Container of operations that can be performed over the Bluetooth Classic
// medium.
class BluetoothClassicMedium {
public:
virtual ~BluetoothClassicMedium() {}
virtual ~BluetoothClassicMedium() = default;
class DiscoveryCallback {
public:
virtual ~DiscoveryCallback() {}
// The Ptrs provided in these callback methods will be owned (and
// destroyed) by the recipient of the callback methods (i.e. the creator of
// the concrete DiscoveryCallback object).
virtual void onDeviceDiscovered(Ptr<BluetoothDevice> device) = 0;
virtual void onDeviceNameChanged(Ptr<BluetoothDevice> device) = 0;
virtual void onDeviceLost(Ptr<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(Ptr<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().
//
// Does not need to bother with destroying the DiscoveryCallback passed in to
// startDiscovery() -- that's the job of the caller.
virtual bool stopDiscovery() = 0;
// StartDiscovery().
virtual bool StopDiscovery() = 0;
// A combination of
// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createInsecureRfcommSocketToServiceRecord
@@ -114,11 +119,10 @@ class BluetoothClassicMedium {
// (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
// UUID.
//
// The returned Ptr will be owned (and destroyed) by the caller. Returns
// Exception::IO on error.
virtual ExceptionOr<Ptr<BluetoothSocket>> connectToService(
Ptr<BluetoothDevice> remote_device,
const std::string& 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
//
@@ -128,13 +132,14 @@ class BluetoothClassicMedium {
// (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
// UUID.
//
// The returned Ptr will be owned (and destroyed) by the caller. Returns
// Exception::IO on error.
virtual ExceptionOr<Ptr<BluetoothServerSocket>> listenForService(
const std::string& service_name,
const std::string& service_uuid) = 0;
// Returns nullptr error.
virtual std::unique_ptr<BluetoothServerSocket> ListenForService(
const std::string& service_name, const std::string& service_uuid) = 0;
virtual BluetoothDevice* GetRemoteDevice(const std::string& mac_address) = 0;
};
} // namespace api
} // namespace nearby
} // namespace location
+21
View File
@@ -0,0 +1,21 @@
#ifndef PLATFORM_API_CANCELABLE_H_
#define PLATFORM_API_CANCELABLE_H_
namespace location {
namespace nearby {
namespace api {
// An interface to provide a cancellation mechanism for objects that represent
// long-running operations.
class Cancelable {
public:
virtual ~Cancelable() = default;
virtual bool Cancel() = 0;
};
} // namespace api
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_CANCELABLE_H_
+16 -5
View File
@@ -1,10 +1,12 @@
#ifndef PLATFORM_API_CONDITION_VARIABLE_H_
#define PLATFORM_API_CONDITION_VARIABLE_H_
#include "platform/exception.h"
#include "platform/base/exception.h"
#include "absl/time/clock.h"
namespace location {
namespace nearby {
namespace api {
// The ConditionVariable class is a synchronization primitive that can be used
// to block a thread, or multiple threads at the same time, until another thread
@@ -14,12 +16,21 @@ class ConditionVariable {
public:
virtual ~ConditionVariable() {}
// https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#notify--
virtual void notify() = 0;
// https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#wait--
virtual Exception::Value wait() = 0; // throws Exception::INTERRUPTED
// Notifies all the waiters that condition state has changed.
virtual void Notify() = 0;
// Waits indefinitely for Notify to be called.
// May return prematurely in case of interrupt, if supported by platform.
// Returns kSuccess, or kInterrupted on interrupt.
virtual Exception Wait() = 0;
// Waits while timeout has not expired for Notify to be called.
// May return prematurely in case of interrupt, if supported by platform.
// Returns kSuccess, or kInterrupted on interrupt.
virtual Exception Wait(absl::Duration timeout) = 0;
};
} // namespace api
} // namespace nearby
} // namespace location
+9 -6
View File
@@ -3,10 +3,12 @@
#include <cstdint>
#include "platform/exception.h"
#include "platform/base/exception.h"
#include "absl/time/time.h"
namespace location {
namespace nearby {
namespace api {
// A synchronization aid that allows one or more threads to wait until a set of
// operations being performed in other threads completes.
@@ -14,14 +16,15 @@ namespace nearby {
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html
class CountDownLatch {
public:
virtual ~CountDownLatch() {}
virtual ~CountDownLatch() = default;
virtual Exception::Value await() = 0; // throws Exception::INTERRUPTED
virtual ExceptionOr<bool> await(
std::int32_t timeout_millis) = 0; // throws Exception::INTERRUPTED
virtual void countDown() = 0;
virtual Exception Await() = 0; // throws Exception::kInterrupted
virtual ExceptionOr<bool> Await(
absl::Duration timeout) = 0; // throws Exception::kInterrupted
virtual void CountDown() = 0;
};
} // namespace api
} // namespace nearby
} // namespace location
+24
View File
@@ -0,0 +1,24 @@
#ifndef PLATFORM_API_CRYPTO_H_
#define PLATFORM_API_CRYPTO_H_
#include "platform/base/byte_array.h"
#include "absl/strings/string_view.h"
namespace location {
namespace nearby {
// A provider of standard hashing algorithms.
class Crypto {
public:
// Initialize global crypto state.
static void Init();
// Return MD5 hash of input.
static ByteArray Md5(absl::string_view input);
// Return SHA256 hash of input.
static ByteArray Sha256(absl::string_view input);
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_CRYPTO_H_
+12 -6
View File
@@ -1,25 +1,31 @@
#ifndef PLATFORM_API_EXECUTOR_H_
#define PLATFORM_API_EXECUTOR_H_
#include "platform/ptr.h"
#include "platform/runnable.h"
#include "platform/base/runnable.h"
namespace location {
namespace nearby {
namespace api {
int GetCurrentTid();
// This abstract class is the superclass of all classes representing an
// Executor.
class Executor {
public:
virtual ~Executor() {}
// Before returning from destructor, executor must wait for all pending
// jobs to finish.
virtual ~Executor() = default;
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-
virtual void Execute(Runnable&& runnable) = 0;
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown--
virtual void shutdown() = 0;
virtual void Shutdown() = 0;
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-
virtual void execute(Ptr<Runnable> runnable) = 0;
virtual int GetTid(int index) const = 0;
};
} // namespace api
} // namespace nearby
} // namespace location
+10 -9
View File
@@ -1,12 +1,12 @@
#ifndef PLATFORM_API_FUTURE_H_
#define PLATFORM_API_FUTURE_H_
#include <cstdint>
#include "platform/exception.h"
#include "platform/base/exception.h"
#include "absl/time/clock.h"
namespace location {
namespace nearby {
namespace api {
// A Future represents the result of an asynchronous computation.
//
@@ -14,17 +14,18 @@ namespace nearby {
template <typename T>
class Future {
public:
virtual ~Future() {}
virtual ~Future() = default;
virtual ExceptionOr<T>
get() = 0; // throws Exception::INTERRUPTED, Exception::EXECUTION
// throws Exception::kInterrupted, Exception::kExecution
virtual ExceptionOr<T> Get() = 0;
// throws Exception::INTERRUPTED, Exception::EXECUTION
// throws Exception::TIMEOUT if |timeout_ms| is exceeded while waiting for
// throws Exception::kInterrupted, Exception::kExecution
// throws Exception::kTimeout if timeout is exceeded while waiting for
// result.
virtual ExceptionOr<T> get(std::int64_t timeout_ms) = 0;
virtual ExceptionOr<T> Get(absl::Duration timeout) = 0;
};
} // namespace api
} // namespace nearby
} // namespace location
-23
View File
@@ -1,23 +0,0 @@
#ifndef PLATFORM_API_HASH_UTILS_H_
#define PLATFORM_API_HASH_UTILS_H_
#include "platform/byte_array.h"
#include "platform/port/string.h"
#include "platform/ptr.h"
namespace location {
namespace nearby {
// A provider of standard hashing algorithms.
class HashUtils {
public:
virtual ~HashUtils() {}
virtual ConstPtr<ByteArray> md5(const std::string& input) = 0;
virtual ConstPtr<ByteArray> sha256(const std::string& input) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_HASH_UTILS_H_
+11 -15
View File
@@ -1,29 +1,25 @@
#ifndef PLATFORM_API_INPUT_FILE_H_
#define PLATFORM_API_INPUT_FILE_H_
#include "platform/byte_array.h"
#include "platform/exception.h"
#include "platform/ptr.h"
#include <cstdint>
#include "platform/base/byte_array.h"
#include "platform/base/exception.h"
#include "platform/base/input_stream.h"
namespace location {
namespace nearby {
namespace api {
// An InputFile represents a readable file on the system.
class InputFile {
class InputFile : public InputStream {
public:
virtual ~InputFile() {}
// The returned ConstPtr will be owned (and destroyed) by the caller.
// When we have exhausted reading the file and no bytes remain, read will
// always return an empty ConstPtr for which isNull() is true.
virtual ExceptionOr<ConstPtr<ByteArray>> read(
std::int64_t size) = 0; // throws Exception::IO when the file cannot be
// opened or read.
virtual std::string getFilePath() const = 0;
virtual std::int64_t getTotalSize() const = 0;
virtual void close() = 0;
~InputFile() override = default;
virtual std::string GetFilePath() const = 0;
virtual std::int64_t GetTotalSize() const = 0;
};
} // namespace api
} // namespace nearby
} // namespace location
-31
View File
@@ -1,31 +0,0 @@
#ifndef PLATFORM_API_INPUT_STREAM_H_
#define PLATFORM_API_INPUT_STREAM_H_
#include <cstdint>
#include "platform/byte_array.h"
#include "platform/exception.h"
#include "platform/ptr.h"
namespace location {
namespace nearby {
// An InputStream represents an input stream of bytes.
//
// https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html
class InputStream {
public:
virtual ~InputStream() {}
// The returned ConstPtr will be owned (and destroyed) by the caller.
virtual ExceptionOr<ConstPtr<ByteArray>> read() = 0; // throws Exception::IO
// The returned ConstPtr will be owned (and destroyed) by the caller.
virtual ExceptionOr<ConstPtr<ByteArray>> read(
std::int64_t size) = 0; // throws Exception::IO
virtual Exception::Value close() = 0; // throws Exception::IO
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_INPUT_STREAM_H_
+10 -6
View File
@@ -1,14 +1,17 @@
#ifndef PLATFORM_API_LISTENABLE_FUTURE_H_
#define PLATFORM_API_LISTENABLE_FUTURE_H_
#include <functional>
#include <memory>
#include "platform/api/executor.h"
#include "platform/api/future.h"
#include "platform/exception.h"
#include "platform/ptr.h"
#include "platform/runnable.h"
#include "platform/base/exception.h"
#include "platform/base/runnable.h"
namespace location {
namespace nearby {
namespace api {
// A Future that accepts completion listeners.
//
@@ -16,12 +19,13 @@ namespace nearby {
template <typename T>
class ListenableFuture : public Future<T> {
public:
~ListenableFuture() override {}
~ListenableFuture() override = default;
// Executor is shared among multiple runnables. It is not owned by any future.
virtual void addListener(Ptr<Runnable> runnable, Executor* executor) = 0;
virtual void AddListener(Runnable runnable,
Executor* executor) = 0;
};
} // namespace api
} // namespace nearby
} // namespace location
-22
View File
@@ -1,22 +0,0 @@
#ifndef PLATFORM_API_LOCK_H_
#define PLATFORM_API_LOCK_H_
namespace location {
namespace nearby {
// A lock is a tool for controlling access to a shared resource by multiple
// threads.
//
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Lock.html
class Lock {
public:
virtual ~Lock() {}
virtual void lock() = 0;
virtual void unlock() = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_LOCK_H_
+41
View File
@@ -0,0 +1,41 @@
#ifndef PLATFORM_API_LOG_MESSAGE_H_
#define PLATFORM_API_LOG_MESSAGE_H_
#include <iostream>
namespace location {
namespace nearby {
namespace api {
// A log message that prints to appropraite destination when ~LogMessage() is
// called.
class LogMessage {
public:
enum class Severity {
kInfo = 0,
kWarning = 1,
kError = 2,
kFatal = 3, // Terminates the process after logging
};
// Configures minimum severity to be logged.
static void SetMinLogSeverity(Severity severity);
// Returns if a log with |severity| should be logged based on
// SetMinLogSeverity and additional platform requirements.
static bool ShouldCreateLogMessage(Severity severity);
virtual ~LogMessage() = default;
// Printf like logging.
virtual void Print(const char* format, ...) = 0;
// Returns a stream for std::cout like logging.
virtual std::ostream& Stream() = 0;
};
} // namespace api
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_LOG_MESSAGE_H_
-21
View File
@@ -1,21 +0,0 @@
#ifndef PLATFORM_API_MULTI_THREAD_EXECUTOR_H_
#define PLATFORM_API_MULTI_THREAD_EXECUTOR_H_
#include "platform/api/submittable_executor.h"
namespace location {
namespace nearby {
// An Executor that reuses a fixed number of threads operating off a shared
// unbounded queue.
//
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool-int-
class MultiThreadExecutor : public SubmittableExecutor {
public:
~MultiThreadExecutor() override = default;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_MULTI_THREAD_EXECUTOR_H_
+41
View File
@@ -0,0 +1,41 @@
#ifndef PLATFORM_API_MUTEX_H_
#define PLATFORM_API_MUTEX_H_
#include "absl/base/thread_annotations.h"
namespace location {
namespace nearby {
namespace api {
// A lock is a tool for controlling access to a shared resource by multiple
// threads.
//
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Lock.html
class ABSL_LOCKABLE Mutex {
public:
// Mode to pass to implementation constructor.
// kRegular - produces a regular mutex: disallows multiple locks from
// the same thread; optionally, detects double locks in
// debug mode.
// This is the default option.
// kRecursive - produces recursive mutex: allows multiple locks from the
// same thread.
// kRegularNoCheck - produces a regular mutex: disallows double locks,
// but does not check for deadlocks.
enum class Mode {
kRegular = 0,
kRecursive = 1,
kRegularNoCheck = 2,
};
virtual ~Mutex() {}
virtual void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() = 0;
virtual void Unlock() ABSL_UNLOCK_FUNCTION() = 0;
};
} // namespace api
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_MUTEX_H_
+7 -11
View File
@@ -1,25 +1,21 @@
#ifndef PLATFORM_API_OUTPUT_FILE_H_
#define PLATFORM_API_OUTPUT_FILE_H_
#include "platform/byte_array.h"
#include "platform/exception.h"
#include "platform/ptr.h"
#include "platform/base/byte_array.h"
#include "platform/base/exception.h"
#include "platform/base/output_stream.h"
namespace location {
namespace nearby {
namespace api {
// An OutputFile represents a writable file on the system.
class OutputFile {
class OutputFile : public OutputStream {
public:
virtual ~OutputFile() {}
// Takes ownership of the passed-in ConstPtr, and ensures that it is destroyed
// even upon error (i.e. when the return value is not Exception::NONE).
virtual Exception::Value write(
ConstPtr<ByteArray> data) = 0; // throws Exception::IO
virtual void close() = 0;
~OutputFile() override = default;
};
} // namespace api
} // namespace nearby
} // namespace location
-29
View File
@@ -1,29 +0,0 @@
#ifndef PLATFORM_API_OUTPUT_STREAM_H_
#define PLATFORM_API_OUTPUT_STREAM_H_
#include "platform/byte_array.h"
#include "platform/exception.h"
#include "platform/ptr.h"
namespace location {
namespace nearby {
// An OutputStream represents an output stream of bytes.
//
// https://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html
class OutputStream {
public:
virtual ~OutputStream() {}
// Takes ownership of the passed-in ConstPtr, and ensures that it is destroyed
// even upon error (i.e. when the return value is not Exception::NONE).
virtual Exception::Value write(
ConstPtr<ByteArray> data) = 0; // throws Exception::IO
virtual Exception::Value flush() = 0; // throws Exception::IO
virtual Exception::Value close() = 0; // throws Exception::IO
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_OUTPUT_STREAM_H_
+55 -68
View File
@@ -2,108 +2,95 @@
#define PLATFORM_API_PLATFORM_H_
#include <cstdint>
#include <memory>
#include <string>
#include "platform/api/atomic_boolean.h"
#include "platform/api/atomic_reference_def.h"
#include "platform/api/atomic_reference.h"
#include "platform/api/ble.h"
#include "platform/api/ble_v2.h"
#include "platform/api/bluetooth_adapter.h"
#include "platform/api/bluetooth_classic.h"
#include "platform/api/condition_variable.h"
#include "platform/api/count_down_latch.h"
#include "platform/api/hash_utils.h"
#include "platform/api/crypto.h"
#include "platform/api/input_file.h"
#include "platform/api/lock.h"
#include "platform/api/log_message.h"
#include "platform/api/mutex.h"
#include "platform/api/output_file.h"
#include "platform/api/scheduled_executor.h"
#include "platform/api/server_sync.h"
#include "platform/api/settable_future_def.h"
#include "platform/api/submittable_executor_def.h"
#include "platform/api/settable_future.h"
#include "platform/api/submittable_executor.h"
#include "platform/api/system_clock.h"
#include "platform/api/thread_utils.h"
#include "platform/api/webrtc.h"
#include "platform/api/wifi.h"
#include "platform/api/wifi_lan.h"
// Project-specific basic types, that are not part of API.
// TODO(apolyudov): replace with c++ standard types.
#include "platform/port/string.h"
#include "platform/ptr.h"
#include "absl/types/any.h"
#include "platform/base/payload_id.h"
#include "absl/strings/string_view.h"
namespace location {
namespace nearby {
namespace platform {
namespace api {
// API rework notes:
// https://docs.google.com/spreadsheets/d/1erZNkX7pX8s5jWTHdxgjntxTMor3BGiY2H_fC_ldtoQ/edit#gid=381357998
class ImplementationPlatform {
public:
// Class Templates in platform code.
//
// Platform interface does not support templates directly.
// This is a design decision. The purpose is to have type isolation
// between platform library (or simply platform) and core library.
// Another goal is to make a platform implementation a black box,
// which does not leak implementation details in any form, be that types,
// methods, or variables.
//
// Core library code does provide platform-specific class templates
// on top of (a non-templated) platform support.
//
// For every common library template that needs platform support,
// platform must provide an absl::any specialization of class template:
template <typename T>
static Ptr<AtomicReference<T>> createAtomicReference(T initial_value = T{});
template <typename T>
static Ptr<SettableFuture<T>> createSettableFuture();
// General platform support:
// - atomic variables (boolean, and any other copyable type)
// - synchronization primitives:
// - mutex (regular, and recursive)
// - condition variable (must work with regular mutex only)
// - Future<T> : to synchronize on Callable<T> scheduled to execute.
// - CountDownLatch : to ensure at least N threads are waiting.
// - file I/O
// - Logging
// AtomicReference<T>
static Ptr<AtomicReference<absl::any>> createAtomicReferenceAny(
absl::any initial_value);
// Atomics:
// =======
// SettableFuture<T>
static Ptr<SettableFuture<absl::any>> createSettableFutureAny();
// Atomic boolean: special case. Uses native platform atomics.
// Does not use locking.
// Does not use dynamic memory allocations in operations.
static std::unique_ptr<AtomicBoolean> CreateAtomicBoolean(bool initial_value);
// Non-template methods: general platform support.
static Ptr<AtomicBoolean> createAtomicBoolean(bool initial_value);
static Ptr<CountDownLatch> createCountDownLatch(std::int32_t count);
static Ptr<Lock> createLock();
static Ptr<ConditionVariable> createConditionVariable(Ptr<Lock> lock);
static Ptr<HashUtils> createHashUtils();
static Ptr<ThreadUtils> createThreadUtils();
static Ptr<SystemClock> createSystemClock();
static Ptr<InputFile> createInputFile(std::int64_t payload_id,
std::int64_t total_size);
static Ptr<OutputFile> createOutputFile(std::int64_t payload_id);
// Supports enums and integers up to 32-bit.
// Does not use locking, if platform supports 32-bit atimics natively.
// Does not use dynamic memory allocations in operations.
static std::unique_ptr<AtomicUint32> CreateAtomicUint32(std::uint32_t value);
static std::unique_ptr<CountDownLatch> CreateCountDownLatch(
std::int32_t count);
static std::unique_ptr<Mutex> CreateMutex(Mutex::Mode mode);
static std::unique_ptr<ConditionVariable> CreateConditionVariable(
Mutex* mutex);
static std::unique_ptr<InputFile> CreateInputFile(PayloadId payload_id,
std::int64_t total_size);
static std::unique_ptr<OutputFile> CreateOutputFile(PayloadId payload_id);
static std::unique_ptr<LogMessage> CreateLogMessage(
const char* file, int line, LogMessage::Severity severity);
// Java-like Executors
// Type aliases used to API 1.0 compatibility.
// They will be retired soon.
// TODO(apolyudov): cleanup.
using SingleThreadExecutorType = SubmittableExecutor;
using MultiThreadExecutorType = SubmittableExecutor;
using ScheduledExecutorType = ScheduledExecutor;
static Ptr<SubmittableExecutor> createSingleThreadExecutor();
static Ptr<SubmittableExecutor> createMultiThreadExecutor(
static std::unique_ptr<SubmittableExecutor> CreateSingleThreadExecutor();
static std::unique_ptr<SubmittableExecutor> CreateMultiThreadExecutor(
std::int32_t max_concurrency);
static Ptr<ScheduledExecutor> createScheduledExecutor();
static std::unique_ptr<ScheduledExecutor> CreateScheduledExecutor();
// Protocol implementations, domain-specific support
static Ptr<BluetoothAdapter> createBluetoothAdapter();
static Ptr<WifiMedium> createWifiMedium();
static Ptr<BluetoothClassicMedium> createBluetoothClassicMedium();
static Ptr<BLEMedium> createBLEMedium();
static Ptr<BLEMediumV2> createBLEMediumV2();
static Ptr<ServerSyncMedium> createServerSyncMedium();
static Ptr<WifiLanMedium> createWifiLanMedium();
static Ptr<WebRtcSignalingMessenger> createWebRtcSignalingMessenger(
const std::string& self_id);
static std::string getDeviceId();
static std::unique_ptr<BluetoothAdapter> CreateBluetoothAdapter();
static std::unique_ptr<BluetoothClassicMedium> CreateBluetoothClassicMedium(
BluetoothAdapter&);
static std::unique_ptr<BleMedium> CreateBleMedium(BluetoothAdapter&);
static std::unique_ptr<ble_v2::BleMedium> CreateBleV2Medium(
BluetoothAdapter&);
static std::unique_ptr<ServerSyncMedium> CreateServerSyncMedium();
static std::unique_ptr<WifiMedium> CreateWifiMedium();
static std::unique_ptr<WifiLanMedium> CreateWifiLanMedium();
static std::unique_ptr<WebRtcMedium> CreateWebRtcMedium();
};
} // namespace platform
} // namespace api
} // namespace nearby
} // namespace location
+15 -8
View File
@@ -2,27 +2,34 @@
#define PLATFORM_API_SCHEDULED_EXECUTOR_H_
#include <cstdint>
#include <functional>
#include <memory>
#include "platform/api/submittable_executor_def.h"
#include "platform/cancelable.h"
#include "platform/ptr.h"
#include "platform/runnable.h"
#include "platform/api/cancelable.h"
#include "platform/api/executor.h"
#include "platform/base/runnable.h"
#include "absl/time/time.h"
namespace location {
namespace nearby {
namespace api {
// An Executor that can schedule commands to run after a given delay, or to
// execute periodically.
//
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html
class ScheduledExecutor : public SubmittableExecutor {
class ScheduledExecutor : public Executor {
public:
~ScheduledExecutor() override = default;
virtual Ptr<Cancelable> schedule(Ptr<Runnable> runnable,
std::int64_t delay_millis) = 0;
// Cancelable is kept both in the executor context, and in the caller context.
// We want Cancelable to live until both caller and executor are done with it.
// Exclusive ownership model does not work for this case;
// using std:shared_ptr<> instead if std::unique_ptr<>.
virtual std::shared_ptr<Cancelable> Schedule(Runnable&& runnable,
absl::Duration duration) = 0;
};
} // namespace api
} // namespace nearby
} // namespace location
+25 -27
View File
@@ -3,61 +3,59 @@
#include <string>
#include "platform/byte_array.h"
#include "platform/ptr.h"
#include "platform/base/byte_array.h"
#include "absl/strings/string_view.h"
namespace location {
namespace nearby {
namespace api {
// Abstraction that represents a Nearby endpoint exchanging data through
// ServerSync Medium.
class ServerSyncDevice {
public:
virtual ~ServerSyncDevice() {}
virtual ~ServerSyncDevice() = default;
virtual std::string getName() = 0;
virtual std::string getGuid() = 0;
virtual std::string getOwnGuid() = 0;
virtual std::string GetName() const = 0;
virtual std::string GetGuid() const = 0;
virtual std::string GetOwnGuid() const = 0;
};
// Container of operations that can be performed over the Server Sync medium.
// Container of operations that can be performed over the Chrome Sync medium.
class ServerSyncMedium {
public:
virtual ~ServerSyncMedium() {}
virtual ~ServerSyncMedium() = default;
// Takes ownership of (and is responsible for destroying) the passed-in
// 'endpoint_info'.
virtual bool startAdvertising(const std::string& service_id,
const std::string& endpoint_id,
ConstPtr<ByteArray> endpoint_info) = 0;
virtual void stopAdvertising(const std::string& service_id) = 0;
virtual bool StartAdvertising(absl::string_view service_id,
absl::string_view endpoint_id,
const ByteArray& endpoint_info) = 0;
virtual void StopAdvertising(absl::string_view service_id) = 0;
class DiscoveredDeviceCallback {
public:
virtual ~DiscoveredDeviceCallback() {}
virtual ~DiscoveredDeviceCallback() = default;
// Called on a new ServerSyncDevice discovery.
virtual void onDeviceDiscovered(Ptr<ServerSyncDevice> device,
const std::string& service_id,
const std::string& endpoint_id,
ConstPtr<ByteArray> endpoint_info) = 0;
virtual void OnDeviceDiscovered(ServerSyncDevice* device,
absl::string_view service_id,
absl::string_view endpoint_id,
const ByteArray& endpoint_info) = 0;
// Called when ServerSyncDevice is no longer reachable.
virtual void onDeviceLost(Ptr<ServerSyncDevice> device,
const std::string& service_id) = 0;
virtual void OnDeviceLost(ServerSyncDevice* device,
absl::string_view service_id) = 0;
};
// Returns true once the Chrome Sync scan has been initiated.
virtual bool startDiscovery(
const std::string& service_id,
Ptr<DiscoveredDeviceCallback> discovered_device_callback) = 0;
virtual bool StartDiscovery(
absl::string_view service_id,
const DiscoveredDeviceCallback& discovered_device_callback) = 0;
// Returns true once Chrome Sync scan for service_id is well and truly
// stopped; after this returns, there must be no more invocations of the
// DiscoveredDeviceCallback passed in to startScanning() for service_id.
virtual void stopDiscovery(const std::string& service_id) = 0;
virtual void StopDiscovery(absl::string_view service_id) = 0;
};
} // namespace api
} // namespace nearby
} // namespace location
+18 -49
View File
@@ -1,65 +1,34 @@
#ifndef PLATFORM_API_SETTABLE_FUTURE_H_
#define PLATFORM_API_SETTABLE_FUTURE_H_
#include "platform/api/platform.h"
#include "platform/api/settable_future_def.h"
#include "platform/exception.h"
#include "platform/ptr.h"
#include "platform/runnable.h"
#include "absl/types/any.h"
#include "platform/api/listenable_future.h"
#include "platform/base/exception.h"
namespace location {
namespace nearby {
namespace api {
// "Common" part of implementation.
// Placed here for textual compatibility to minimize scope of changes.
// Can be (and should be) moved to a separate file outside "api" folder.
// TODO(apolyudov): for API v2.0
namespace platform {
namespace impl {
// A SettableFuture is a type of Future whose result can be set.
//
// https://google.github.io/guava/releases/20.0/api/docs/com/google/common/util/concurrent/SettableFuture.html
template <typename T>
class SettableFutureImpl : public SettableFuture<T> {
class SettableFuture : public ListenableFuture<T> {
public:
SettableFutureImpl() {
future_ = platform::ImplementationPlatform::createSettableFutureAny();
}
~SettableFuture() override = default;
~SettableFutureImpl() override = default;
// Completes the future successfully. The value is returned to any waiters.
// Returns true, if value was set.
// Returns false, if Future is already in "done" state.
virtual bool Set(T value) = 0;
bool set(T value) override { return future_->set(absl::any(value)); }
bool setException(Exception exception) override {
return future_->setException(exception);
}
void addListener(Ptr<Runnable> runnable, Executor* executor) override {
future_->addListener(runnable, executor);
}
ExceptionOr<T> get() override { return CommonGet(future_->get()); }
ExceptionOr<T> get(std::int64_t timeout_ms) override {
return CommonGet(future_->get(timeout_ms));
}
private:
ExceptionOr<T> CommonGet(ExceptionOr<absl::any> ret_val) {
if (ret_val.exception() != Exception::kSuccess) {
return ExceptionOr<T>{ret_val.exception()};
}
return ExceptionOr<T>{absl::any_cast<T>(ret_val.result())};
}
Ptr<SettableFuture<absl::any>> future_;
// Completes the future unsuccessfully. The exception value is returned to any
// waiters.
// Returns true, if exception was set.
// Returns false, if Future is already in "done" state.
virtual bool SetException(Exception exception) = 0;
};
} // namespace impl
template <typename T>
Ptr<SettableFuture<T>> ImplementationPlatform::createSettableFuture() {
return Ptr<SettableFuture<T>>(new impl::SettableFutureImpl<T>{});
}
} // namespace platform
} // namespace api
} // namespace nearby
} // namespace location
-31
View File
@@ -1,31 +0,0 @@
#ifndef PLATFORM_API_SETTABLE_FUTURE_DEF_H_
#define PLATFORM_API_SETTABLE_FUTURE_DEF_H_
#include "platform/api/listenable_future.h"
#include "platform/exception.h"
namespace location {
namespace nearby {
// A SettableFuture is a type of Future whose result can be set.
//
// https://google.github.io/guava/releases/20.0/api/docs/com/google/common/util/concurrent/SettableFuture.html
//
// Platform must implentent non-template static member functions
// Ptr<SettableFuture<size_t>> CreateSettableFutureSizeT()
// Ptr<SettableFuture<std::shared_ptr<void>>> CreateSettableFuturePtr()
// in the location::nearby::platform::ImplementationPlatform class.
template <typename T>
class SettableFuture : public ListenableFuture<T> {
public:
~SettableFuture() override = default;
virtual bool set(T value) = 0;
virtual bool setException(Exception exception) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_SETTABLE_FUTURE_DEF_H_
-21
View File
@@ -1,21 +0,0 @@
#ifndef PLATFORM_API_SINGLE_THREAD_EXECUTOR_H_
#define PLATFORM_API_SINGLE_THREAD_EXECUTOR_H_
#include "platform/api/submittable_executor.h"
namespace location {
namespace nearby {
// An Executor that uses a single worker thread operating off an unbounded
// queue.
//
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newSingleThreadExecutor--
class SingleThreadExecutor : public SubmittableExecutor {
public:
~SingleThreadExecutor() override = default;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_SINGLE_THREAD_EXECUTOR_H_
-26
View File
@@ -1,26 +0,0 @@
#ifndef PLATFORM_API_SOCKET_H_
#define PLATFORM_API_SOCKET_H_
#include "platform/api/input_stream.h"
#include "platform/api/output_stream.h"
#include "platform/ptr.h"
namespace location {
namespace nearby {
// A socket is an endpoint for communication between two machines.
//
// https://docs.oracle.com/javase/8/docs/api/java/net/Socket.html
class Socket {
public:
virtual ~Socket() {}
virtual Ptr<InputStream> getInputStream() = 0;
virtual Ptr<OutputStream> getOutputStream() = 0;
virtual void close() = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_SOCKET_H_
+17 -26
View File
@@ -2,40 +2,31 @@
#define PLATFORM_API_SUBMITTABLE_EXECUTOR_H_
#include <functional>
#include <memory>
#include "platform/api/executor.h"
#include "platform/api/future.h"
#include "platform/api/platform.h"
#include "platform/api/settable_future.h"
#include "platform/api/submittable_executor_def.h"
#include "platform/exception.h"
#include "platform/base/runnable.h"
namespace location {
namespace nearby {
namespace api {
// "Common" part of implementation.
// Placed here for textual compatibility to minimize scope of changes.
// Can be (and should be) moved to a separate file outside "api" folder.
// TODO(apolyudov): for API v2.0
template <typename T>
Ptr<Future<T>> SubmittableExecutor::submit(Ptr<Callable<T>> callable) {
using Platform = platform::ImplementationPlatform;
Ptr<SettableFuture<T>> future{Platform::createSettableFuture<T>()};
bool submitted = DoSubmit([callable, future]() {
ExceptionOr<T> result = callable->call();
if (result.ok()) {
future->set(std::move(result.result()));
} else {
future->setException({result.exception()});
}
});
if (!submitted) {
// Raise Exception::kExecution if we are shutting down.
future->setException({Exception::kExecution});
}
return future;
}
// Main interface to be used by platform as a base class for
// - MultiThreadExecutorWrapper
// - SingleThreadExecutorWrapper
// Platform must override bool submit(std::function<void()>) method.
class SubmittableExecutor : public Executor {
public:
~SubmittableExecutor() override = default;
// Submit a callable (with no delay).
// Returns true, if callable was submitted, false otherwise.
// Callable is not submitted if shutdown is in progress.
virtual bool DoSubmit(Runnable&& wrapped_callable) = 0;
};
} // namespace api
} // namespace nearby
} // namespace location
@@ -1,35 +0,0 @@
#ifndef PLATFORM_API_SUBMITTABLE_EXECUTOR_DEF_H_
#define PLATFORM_API_SUBMITTABLE_EXECUTOR_DEF_H_
#include <functional>
#include "platform/api/executor.h"
#include "platform/api/future.h"
#include "platform/callable.h"
#include "platform/ptr.h"
namespace location {
namespace nearby {
// Main interface to be used by platform as a base class for
// - MultiThreadExecutorWrapper
// - SingleThreadExecutorWrapper
// Platform must override bool submit(std::function<void()>) method.
class SubmittableExecutor : public Executor {
public:
~SubmittableExecutor() override = default;
template <typename T>
Ptr<Future<T>> submit(Ptr<Callable<T>> callable);
protected:
// Submit a callable (with no delay).
// Returns true, if callable was submitted, false otherwise.
// Callable is not submitted if shutdown is in progress.
virtual bool DoSubmit(std::function<void()> wrapped_callable) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_SUBMITTABLE_EXECUTOR_DEF_H_
+9 -8
View File
@@ -1,19 +1,20 @@
#ifndef PLATFORM_API_SYSTEM_CLOCK_H_
#define PLATFORM_API_SYSTEM_CLOCK_H_
#include <cstdint>
#include "platform/base/exception.h"
#include "absl/time/clock.h"
namespace location {
namespace nearby {
class SystemClock {
class SystemClock final {
public:
virtual ~SystemClock() {}
// Returns the time (in milliseconds) since the system was booted, and
// includes deep sleep. This clock should be guaranteed to be monotonic, and
// should continue to tick even when the CPU is in power saving modes.
virtual std::int64_t elapsedRealtime() = 0;
// Initialize global system state.
static void Init();
// Returns current absolute time. It is guaranteed to be monotonic.
static absl::Time ElapsedRealtime();
// Pauses current thread for the specified duration.
static Exception Sleep(absl::Duration duration);
};
} // namespace nearby
-23
View File
@@ -1,23 +0,0 @@
#ifndef PLATFORM_API_THREAD_UTILS_H_
#define PLATFORM_API_THREAD_UTILS_H_
#include <cstdint>
#include "platform/exception.h"
namespace location {
namespace nearby {
class ThreadUtils {
public:
virtual ~ThreadUtils() {}
// https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#sleep(long)
virtual Exception::Value sleep(
std::int64_t millis) = 0; // throws Exception::INTERRUPTED
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_THREAD_UTILS_H_
+31 -26
View File
@@ -1,45 +1,50 @@
#ifndef PLATFORM_API_WEBRTC_H_
#define PLATFORM_API_WEBRTC_H_
#include <vector>
#include <memory>
#include "platform/byte_array.h"
#include "platform/ptr.h"
#include "proto/connections/offline_wire_formats.pb.h"
#include "proto/connections/offline_wire_formats.pb.h"
#include "platform/base/byte_array.h"
#include "absl/strings/string_view.h"
#include "webrtc/api/peer_connection_interface.h"
namespace location {
namespace nearby {
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 bool SendMessage(absl::string_view peer_id,
const ByteArray& message) = 0;
virtual void onSignalingMessage(ConstPtr<ByteArray> message) = 0;
};
class IceServersListener {
public:
virtual ~IceServersListener() = default;
virtual void OnIceServersFetched(
std::vector<Ptr<webrtc::PeerConnectionInterface::IceServer>>
ice_servers) = 0;
};
virtual bool registerSignaling() = 0;
virtual bool unregisterSignaling() = 0;
virtual bool sendMessage(const std::string& peer_id,
ConstPtr<ByteArray> message) = 0;
virtual bool startReceivingMessages(
Ptr<SignalingMessageListener> listener) = 0;
virtual void getIceServers(Ptr<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,
const connections::LocationHint& location_hint) = 0;
};
} // namespace api
} // namespace nearby
} // namespace location
+33 -34
View File
@@ -2,47 +2,49 @@
#define PLATFORM_API_WIFI_H_
#include <cstdint>
#include <string>
#include <vector>
#include "platform/port/string.h"
#include "platform/ptr.h"
#include "absl/strings/string_view.h"
namespace location {
namespace nearby {
namespace api {
// Possible authentication types for a WiFi network.
struct WifiAuthType {
enum Value {
UNKNOWN = 0,
OPEN = 1,
WPA_PSK = 2,
WEP = 3,
};
enum class WifiAuthType {
// WiFi Authentication type; either none (non-secured a.k.a. open) link, or
// WPA PSK (WiFi Protected Access PreShared Key), or
// see https://en.wikipedia.org/wiki/Wi-Fi_Protected_Access
// WEP (Wired Equivalent Privacy);
// see https://en.wikipedia.org/wiki/Wired_Equivalent_Privacy
kUnknown = 0,
kOpen = 1,
kWpaPsk = 2,
kWep = 3,
};
// Possible statuses of a device's connection to a WiFi network.
struct WifiConnectionStatus {
enum Value {
UNKNOWN = 0,
CONNECTED = 1,
CONNECTION_FAILURE = 2,
AUTH_FAILURE = 3,
};
enum class WifiConnectionStatus {
kUnknown = 0,
kConnected = 1,
kConnectionFailure = 2,
kAuthFailure = 3,
};
// Represents a WiFi network found during a call to WifiMedium#scan().
class WifiScanResult {
public:
virtual ~WifiScanResult() {}
virtual ~WifiScanResult() = default;
// Gets the SSID of this WiFi network.
virtual std::string getSSID() const = 0;
virtual std::string GetSsid() const = 0;
// Gets the signal strength of this WiFi network in dBm.
virtual std::int32_t getSignalStrengthDbm() const = 0;
virtual std::int32_t GetSignalStrengthDbm() const = 0;
// Gets the frequency band of this WiFi network in MHz.
virtual std::int32_t getFrequencyMhz() const = 0;
virtual std::int32_t GetFrequencyMhz() const = 0;
// Gets the authentication type of this WiFi network.
virtual WifiAuthType::Value getAuthType() const = 0;
virtual WifiAuthType GetAuthType() const = 0;
};
// Container of operations that can be performed over the WiFi medium.
@@ -52,26 +54,22 @@ class WifiMedium {
class ScanResultCallback {
public:
virtual ~ScanResultCallback() {}
virtual ~ScanResultCallback() = default;
// The ConstPtr<WifiScanResult> objects contained in scan_results will be
// owned (and destroyed) by the recipient of the callback methods (i.e. the
// creator of the concrete ScanResultCallback object).
virtual void onScanResults(
const std::vector<ConstPtr<WifiScanResult>>& scan_results) = 0;
virtual void OnScanResults(
const std::vector<WifiScanResult>& scan_results) = 0;
};
// Does not take ownership of the passed-in scan_result_callback -- destroying
// that is up to the caller.
virtual bool scan(Ptr<ScanResultCallback> scan_result_callback) = 0;
virtual bool Scan(const ScanResultCallback& scan_result_callback) = 0;
// If 'password' is an empty string, none has been provided. Returns
// WifiConnectionStatus::CONNECTED on success, or the appropriate failure code
// otherwise.
virtual WifiConnectionStatus::Value connectToNetwork(
const std::string& ssid,
const std::string& password,
WifiAuthType::Value auth_type) = 0;
virtual WifiConnectionStatus ConnectToNetwork(absl::string_view ssid,
absl::string_view password,
WifiAuthType auth_type) = 0;
// Blocks until it's certain of there being a connection to the internet, or
// returns false if it fails to do so.
@@ -79,12 +77,13 @@ class WifiMedium {
// How this method wants to verify said connection is totally up to it (so it
// can feel free to ping whatever server, download whatever resource, etc.
// that it needs to gain confidence that the internet is reachable hereon in).
virtual bool verifyInternetConnectivity() = 0;
virtual bool VerifyInternetConnectivity() = 0;
// Returns the local device's IP address in the IPv4 dotted-quad format.
virtual std::string getIPAddress() = 0;
virtual std::string GetIpAddress() = 0;
};
} // namespace api
} // namespace nearby
} // namespace location
+71 -48
View File
@@ -1,49 +1,61 @@
#ifndef PLATFORM_API_WIFI_LAN_H_
#define PLATFORM_API_WIFI_LAN_H_
#include "platform/api/input_stream.h"
#include "platform/api/output_stream.h"
#include "platform/byte_array.h"
#include "platform/exception.h"
#include "platform/port/string.h"
#include "platform/ptr.h"
#include <string>
#include "platform/base/byte_array.h"
#include "platform/base/input_stream.h"
#include "platform/base/listeners.h"
#include "platform/base/output_stream.h"
#include "absl/strings/string_view.h"
namespace location {
namespace nearby {
namespace api {
// Opaque wrapper over a WifiLan service which contains encoded service name.
// Opaque wrapper over a WifiLan service which contains packed
// |WifiLanServiceInfo| string name.
class WifiLanService {
public:
virtual ~WifiLanService() = default;
virtual std::string GetName() = 0;
// Returns the packed string of |WifiLanServiceInfo|. Note that the packed
// string would not include TXTRecord, which inheritor should save it in
// another store.
virtual std::string GetServiceName() const = 0;
// Returns the packed string of endpoint info with named key.
virtual std::string GetTxtRecord(const std::string& key) const = 0;
// Returns the local device's <IP address, port> as a pair.
// IP address is in byte sequence, in network order.
virtual std::pair<std::string, int> GetServiceAddress() const = 0;
};
class WifiLanSocket {
public:
virtual ~WifiLanSocket() = default;
// Returns the InputStream of the WifiLanSocket, or a null Ptr<InputStream>
// on error.
// Returns the InputStream of the WifiLanSocket.
// On error, returned stream will report Exception::kIo on any operation.
//
// The returned Ptr is not owned by the caller, and can be invalidated once
// The returned object is not owned by the caller, and can be invalidated once
// the WifiLanSocket object is destroyed.
virtual Ptr<InputStream> GetInputStream() = 0;
virtual InputStream& GetInputStream() = 0;
// Returns the OutputStream of the WifiLanSocket, or a null
// Ptr<OutputStream> on error.
// Returns the OutputStream of the WifiLanSocket.
// On error, returned stream will report Exception::kIo on any operation.
//
// The returned Ptr is not owned by the caller, and can be invalidated once
// The returned object is not owned by the caller, and can be invalidated once
// the WifiLanSocket object is destroyed.
virtual Ptr<OutputStream> GetOutputStream() = 0;
virtual OutputStream& GetOutputStream() = 0;
// Returns Exception::IO on error, Exception::NONE otherwise.
virtual Exception::Value Close() = 0;
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
virtual Exception Close() = 0;
// The returned Ptr is not owned by the caller, and can be invalidated once
// the WifiLanSocket object is destroyed.
virtual Ptr<WifiLanService> GetRemoteWifiLanService() = 0;
// Returns valid WifiLanService pointer if there is a connection, and
// nullptr otherwise.
virtual WifiLanService* GetRemoteWifiLanService() = 0;
};
// Container of operations that can be performed over the WifiLan medium.
@@ -52,44 +64,55 @@ class WifiLanMedium {
virtual ~WifiLanMedium() = default;
virtual bool StartAdvertising(
absl::string_view service_id,
absl::string_view wifi_lan_service_info_name) = 0;
virtual void StopAdvertising(absl::string_view service_id) = 0;
const std::string& service_id,
const std::string& wifi_lan_service_info_name,
const std::string& endpoint_info_name) = 0;
virtual bool StopAdvertising(const std::string& service_id) = 0;
// Callback for WifiLan discover results.
class DiscoveredServiceCallback {
public:
virtual ~DiscoveredServiceCallback() = default;
virtual void OnServiceDiscovered(Ptr<WifiLanService> wifi_lan_service) = 0;
virtual void OnServiceLost(Ptr<WifiLanService> wifi_lan_service) = 0;
// Callback that is invoked when a discovered service is found or lost.
struct DiscoveredServiceCallback {
std::function<void(WifiLanService& wifi_lan_service,
const std::string& service_id)>
service_discovered_cb =
DefaultCallback<WifiLanService&, const std::string&>();
std::function<void(WifiLanService& wifi_lan_service,
const std::string& service_id)>
service_lost_cb =
DefaultCallback<WifiLanService&, const std::string&>();
};
virtual bool StartDiscovery(
absl::string_view service_id,
Ptr<DiscoveredServiceCallback> discovered_service_callback) = 0;
virtual void StopDiscovery(absl::string_view service_id) = 0;
// Returns true once the WifiLan discovery has been initiated.
virtual bool StartDiscovery(const std::string& service_id,
DiscoveredServiceCallback callback) = 0;
class AcceptedConnectionCallback {
public:
virtual ~AcceptedConnectionCallback() = default;
// Returns true once WifiLan discovery for service_id is well and truly
// stopped; after this returns, there must be no more invocations of the
// DiscoveredServiceCallback passed in to StartDiscovery() for service_id.
virtual bool StopDiscovery(const std::string& service_id) = 0;
// The Ptr provided in this callback method will be owned (and
// destroyed) by the recipient of the callback methods (i.e. the creator of
// the concrete AcceptedConnectionCallback object).
virtual void OnConnectionAccepted(Ptr<WifiLanSocket> socket,
absl::string_view service_id) = 0;
// Callback that is invoked when a new connection is accepted.
struct AcceptedConnectionCallback {
std::function<void(WifiLanSocket& socket, const std::string& service_id)>
accepted_cb = DefaultCallback<WifiLanSocket&, const std::string&>();
};
// Returns true once WifiLan socket connection requests to service_id can be
// accepted.
virtual bool StartAcceptingConnections(
absl::string_view service_id,
Ptr<AcceptedConnectionCallback> accepted_connection_callback) = 0;
virtual void StopAcceptingConnections(absl::string_view service_id) = 0;
const std::string& service_id, AcceptedConnectionCallback callback) = 0;
virtual bool StopAcceptingConnections(const std::string& service_id) = 0;
virtual Ptr<WifiLanSocket> Connect(Ptr<WifiLanService> wifi_lan_service,
absl::string_view service_id) = 0;
// Connects to a WifiLan service.
// On success, returns a new WifiLanSocket.
// On error, returns nullptr.
virtual std::unique_ptr<WifiLanSocket> Connect(
WifiLanService& service, const std::string& service_id) = 0;
virtual WifiLanService* FindRemoteService(const std::string& ip_address,
int port) = 0;
};
} // namespace api
} // namespace nearby
} // namespace location