nearby: snapshot as of cl/296436629

Signed-off-by: Alexey Polyudov <apolyudov@google.com>
Change-Id: I2cf5bf225b76f4c1541954651f3a7544a14e0cec
This commit is contained in:
Alexey Polyudov
2020-04-04 12:52:31 -07:00
parent 598516303b
commit 204f76077d
195 changed files with 27318 additions and 0 deletions
+58
View File
@@ -0,0 +1,58 @@
package(default_visibility = [
"//core:__subpackages__",
"//platform:__subpackages__",
"//location/nearby/setup/core:__subpackages__",
])
cc_library(
name = "api",
hdrs = [
"atomic_boolean.h",
"atomic_reference.h",
"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",
"lock.h",
"multi_thread_executor.h",
"output_file.h",
"output_stream.h",
"scheduled_executor.h",
"settable_future.h",
"single_thread_executor.h",
"socket.h",
"submittable_executor.h",
"system_clock.h",
"thread_utils.h",
"wifi.h",
],
deps = [
"//platform:types",
"//platform/port:down_cast",
"//platform/port:string",
],
)
cc_library(
name = "lock",
hdrs = ["lock.h"],
visibility = [
"//platform:__subpackages__",
],
)
cc_library(
name = "condition_variable",
hdrs = ["condition_variable.h"],
visibility = [
"//platform:__subpackages__",
],
deps = ["//platform:types"],
)
+21
View File
@@ -0,0 +1,21 @@
#ifndef PLATFORM_API_ATOMIC_BOOLEAN_H_
#define PLATFORM_API_ATOMIC_BOOLEAN_H_
namespace location {
namespace nearby {
// 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 bool get() = 0;
virtual void set(bool value) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_ATOMIC_BOOLEAN_H_
+22
View File
@@ -0,0 +1,22 @@
#ifndef PLATFORM_API_ATOMIC_REFERENCE_H_
#define PLATFORM_API_ATOMIC_REFERENCE_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
template <typename T>
class AtomicReference {
public:
virtual ~AtomicReference() {}
virtual T get() = 0;
virtual void set(T value) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_ATOMIC_REFERENCE_H_
+124
View File
@@ -0,0 +1,124 @@
#ifndef PLATFORM_API_BLE_H_
#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"
namespace location {
namespace nearby {
// Opaque wrapper over a BLE peripheral. Must contain enough data about a
// particular BLE device to connect to its GATT server.
class BLEPeripheral {
public:
virtual ~BLEPeripheral() {}
// 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;
};
class BLESocket {
public:
virtual ~BLESocket() {}
// Returns the InputStream of the BLESocket, or a null Ptr<InputStream>
// on error.
//
// The returned Ptr is not owned by the caller, and can be invalidated once
// the BLESocket object is destroyed.
virtual Ptr<InputStream> getInputStream() = 0;
// Returns the OutputStream of the BLESocket, or a null
// Ptr<OutputStream> on error.
//
// The returned Ptr is not owned by the caller, and can be invalidated once
// the BLESocket object is destroyed.
virtual Ptr<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;
// The returned Ptr is not owned by the caller, and can be invalidated once
// the BLESocket object is destroyed.
virtual Ptr<BLEPeripheral> getRemotePeripheral() = 0;
};
// Container of operations that can be performed over the BLE medium.
class BLEMedium {
public:
virtual ~BLEMedium() {}
// 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;
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;
};
// 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;
// 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;
// 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;
};
// 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;
// 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;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_BLE_H_
+401
View File
@@ -0,0 +1,401 @@
#ifndef PLATFORM_API_BLE_V2_H_
#define PLATFORM_API_BLE_V2_H_
#include <cstdint>
#include <limits>
#include <map>
#include <set>
#include "platform/byte_array.h"
#include "platform/exception.h"
#include "platform/port/string.h"
#include "platform/ptr.h"
namespace location {
namespace nearby {
// https://developer.android.com/reference/android/bluetooth/le/AdvertiseData
//
// Bundle of data found in a BLE advertisement.
//
// 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;
static const TXPowerLevel UNSPECIFIED_TX_POWER_LEVEL =
std::numeric_limits<TXPowerLevel>::min();
bool is_connectable;
// When set to UNSPECIFIED_TX_POWER_LEVEL, TX power should not be included in
// the advertisement data.
TXPowerLevel tx_power_level;
// When set to an empty string, local name should not be included in the
// advertisement data.
std::string local_name;
// When set to an empty vector, the set of 16-bit service class UUIDs should
// 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;
};
// 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 {
public:
virtual ~BLEPeripheralV2() {}
// 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;
};
// 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 {
public:
virtual ~GATTCharacteristic() {}
// Possible permissions of a GATT characteristic.
struct Permission {
enum Value {
UNKNOWN = 0,
READ = 1,
WRITE = 2,
};
};
// Possible properties of a GATT characteristic.
struct Property {
enum Value {
UNKNOWN = 0,
READ = 1,
WRITE = 2,
INDICATE = 3,
};
};
// Returns the UUID of this characteristic.
virtual std::string getUUID() = 0;
// Returns the UUID of the containing GATT service.
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 {
public:
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;
// https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#discoverServices()
//
// Discovers all available services and characteristics on this connection.
// Returns whether or not discovery finished successfully.
//
// This function should block until discovery has finished.
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.
//
// 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;
// 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;
// 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;
// https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#disconnect()
//
// Disconnects a GATT connection.
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 {
public:
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)
//
// Sends a notification (via indication) to the client that a characteristic
// 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;
};
// Callback for asynchronous events on the client side of a GATT connection.
class ClientGATTConnectionLifecycleCallback {
public:
virtual ~ClientGATTConnectionLifecycleCallback() {}
// Called when the client is disconnected from the GATT server.
virtual void onDisconnected(Ptr<ClientGATTConnection> connection) = 0;
};
// Callback for asynchronous events on the server side of a GATT connection.
class ServerGATTConnectionLifecycleCallback {
public:
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;
// Called when a remote peripheral unsubscribed from one of our
// characteristics.
virtual void onCharacteristicUnsubscription(
Ptr<ServerGATTConnection> connection,
Ptr<GATTCharacteristic> characteristic) = 0;
};
// https://developer.android.com/reference/android/bluetooth/BluetoothGattServer
//
// Representation of a BLE GATT server.
class GATTServer {
public:
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.
//
// Characteristics of the same service UUID should be put under one
// service rather than many services with the same UUID.
//
// If the INDICATE property is included, the characteristic should include the
// official Bluetooth Client Characteristic Configuration descriptor with UUID
// 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://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html#setValue(byte[])
//
// Locally updates the value of a characteristic and returns whether or not it
// was successful.
// Takes ownership of (and is responsible for destroying) the passed-in
// 'value'.
virtual bool updateCharacteristic(Ptr<GATTCharacteristic> characteristic,
ConstPtr<ByteArray> value) = 0;
// Stops a GATT server.
virtual void stop() = 0;
};
// A BLE socket representation.
class BLESocketV0 {
public:
virtual ~BLESocketV0() {}
// Returns the remote BLE peripheral tied to this socket.
virtual Ptr<BLEPeripheralV2> 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;
// Closes the socket and blocks until finished. Returns Exception::IO upon
// error, and Exception::NONE otherwise.
virtual Exception::Value close() = 0;
};
// Callback for asynchronous events on a BLESocketV0 object.
class BLESocketLifecycleCallback {
public:
virtual ~BLESocketLifecycleCallback() {}
// Called when a message arrives on a socket.
virtual void onMessageReceived(Ptr<BLESocketV0> socket,
ConstPtr<ByteArray> message) = 0;
// Called when a socket gets disconnected.
virtual void onDisconnected(Ptr<BLESocketV0> socket) = 0;
};
// Callback for asynchronous events on the server side of a BLESocketV0 object.
class ServerBLESocketLifecycleCallback : public BLESocketLifecycleCallback {
public:
~ServerBLESocketLifecycleCallback() override {}
// Called when a new incoming socket has been established.
virtual void onSocketEstablished(Ptr<BLESocketV0> 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 {
public:
virtual ~BLEMediumV2() {}
typedef std::uint32_t MTU;
// Coarse representation of power settings throughout all BLE operations.
struct PowerMode {
enum Value {
UNKNOWN = 0,
LOW = 1,
HIGH = 2,
};
};
// 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)
//
// Starts BLE advertising and returns whether or not it was successful.
//
// Power mode should be interpreted in the following way:
// LOW:
// - Advertising interval = ~1000ms
// - TX power = low
// HIGH:
// - Advertising interval = ~100ms
// - TX power = high
virtual bool startAdvertising(
ConstPtr<BLEAdvertisementData> advertisement_data,
ConstPtr<BLEAdvertisementData> scan_response,
PowerMode::Value power_mode) = 0;
// https://developer.android.com/reference/android/bluetooth/le/BluetoothLeAdvertiser.html#stopAdvertising(android.bluetooth.le.AdvertiseCallback)
//
// Stops advertising.
virtual void stopAdvertising() = 0;
// https://developer.android.com/reference/android/bluetooth/le/ScanCallback
//
// Callback for BLE scan results.
class ScanCallback {
public:
virtual ~ScanCallback() {}
// https://developer.android.com/reference/android/bluetooth/le/ScanCallback.html#onScanResult(int,%20android.bluetooth.le.ScanResult)
//
// Called when a BLE advertisement is discovered.
//
// The passed in advertisement_data is the merged combination of both
// advertisement data and scan response.
//
// 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
// point.
virtual void onAdvertisementFound(
Ptr<BLEPeripheralV2> peripheral,
ConstPtr<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)
//
// Starts scanning and returns whether or not it was successful.
//
// Power mode should be interpreted in the following way:
// LOW:
// - Scan window = ~512ms
// - Scan interval = ~5120ms
// 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;
// https://developer.android.com/reference/android/bluetooth/le/BluetoothLeScanner.html#stopScan(android.bluetooth.le.ScanCallback)
//
// Stops scanning.
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 listening for incoming BLE sockets and returns false upon error.
virtual bool startListeningForIncomingBLESockets(
Ptr<ServerBLESocketLifecycleCallback> socket_lifecycle_callback) = 0;
// Stops listening for incoming BLE sockets.
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.
//
// Both connection interval and MTU can be negotiated on a best-effort basis.
//
// Power mode should be interpreted in the following way:
// LOW:
// - 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;
// 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;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_BLE_V2_H_
+58
View File
@@ -0,0 +1,58 @@
#ifndef PLATFORM_API_BLUETOOTH_ADAPTER_H_
#define PLATFORM_API_BLUETOOTH_ADAPTER_H_
#include "platform/port/string.h"
#include "platform/ptr.h"
namespace location {
namespace nearby {
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html
class BluetoothAdapter {
public:
virtual ~BluetoothAdapter() {}
// Eligible statuses of the BluetoothAdapter.
struct Status {
enum Value {
DISABLED,
ENABLED,
};
};
// 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;
// Returns true if the BluetoothAdapter's current status is
// Status::Value::ENABLED.
virtual bool isEnabled() = 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,
};
};
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getScanMode()
//
// Returns ScanMode::UNKNOWN on error.
virtual ScanMode::Value getScanMode() = 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;
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getName()
//
// Returns a null Ptr<string> on error.
virtual Ptr<std::string> getName() = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#setName(java.lang.String)
virtual bool setName(const std::string& name) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_BLUETOOTH_ADAPTER_H_
+139
View File
@@ -0,0 +1,139 @@
#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"
namespace location {
namespace nearby {
// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html.
class BluetoothDevice {
public:
virtual ~BluetoothDevice() {}
// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#getName()
virtual std::string getName() = 0;
};
// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html.
class BluetoothSocket {
public:
virtual ~BluetoothSocket() {}
// 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;
// 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;
// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#close()
//
// Returns Exception::IO on error, Exception::NONE otherwise.
virtual Exception::Value 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;
};
// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html.
class BluetoothServerSocket {
public:
virtual ~BluetoothServerSocket() {}
// 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;
// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#close()
//
// Returns Exception::IO on error, Exception::NONE otherwise.
virtual Exception::Value close() = 0;
};
// Container of operations that can be performed over the Bluetooth Classic
// medium.
class BluetoothClassicMedium {
public:
virtual ~BluetoothClassicMedium() {}
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;
};
// 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;
// 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;
// A combination of
// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createInsecureRfcommSocketToServiceRecord
// followed by
// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#connect().
//
// service_uuid is the canonical textual representation
// (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
// type 3 name-based
// (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;
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#listenUsingInsecureRfcommWithServiceRecord
//
// service_uuid is the canonical textual representation
// (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
// type 3 name-based
// (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;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_BLUETOOTH_CLASSIC_H_
+26
View File
@@ -0,0 +1,26 @@
#ifndef PLATFORM_API_CONDITION_VARIABLE_H_
#define PLATFORM_API_CONDITION_VARIABLE_H_
#include "platform/exception.h"
namespace location {
namespace nearby {
// 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
// both modifies a shared variable (the condition), and notifies the
// ConditionVariable.
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
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_CONDITION_VARIABLE_H_
+28
View File
@@ -0,0 +1,28 @@
#ifndef PLATFORM_API_COUNT_DOWN_LATCH_H_
#define PLATFORM_API_COUNT_DOWN_LATCH_H_
#include <cstdint>
#include "platform/exception.h"
namespace location {
namespace nearby {
// A synchronization aid that allows one or more threads to wait until a set of
// operations being performed in other threads completes.
//
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html
class CountDownLatch {
public:
virtual ~CountDownLatch() {}
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;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_COUNT_DOWN_LATCH_H_
+20
View File
@@ -0,0 +1,20 @@
#ifndef PLATFORM_API_EXECUTOR_H_
#define PLATFORM_API_EXECUTOR_H_
namespace location {
namespace nearby {
// This abstract class is the superclass of all classes representing an
// Executor.
class Executor {
public:
virtual ~Executor() {}
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown--
virtual void shutdown() = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_EXECUTOR_H_
+24
View File
@@ -0,0 +1,24 @@
#ifndef PLATFORM_API_FUTURE_H_
#define PLATFORM_API_FUTURE_H_
#include "platform/exception.h"
namespace location {
namespace nearby {
// A Future represents the result of an asynchronous computation.
//
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html
template <typename T>
class Future {
public:
virtual ~Future() {}
virtual ExceptionOr<T>
get() = 0; // throws Exception::INTERRUPTED, Exception::EXECUTION
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_FUTURE_H_
+23
View File
@@ -0,0 +1,23 @@
#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_
+30
View File
@@ -0,0 +1,30 @@
#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"
namespace location {
namespace nearby {
// An InputFile represents a readable file on the system.
class InputFile {
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;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_INPUT_FILE_H_
+31
View File
@@ -0,0 +1,31 @@
#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_
+22
View File
@@ -0,0 +1,22 @@
#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_
+23
View File
@@ -0,0 +1,23 @@
#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-
template <typename ConcreteSubmittableExecutor>
class MultiThreadExecutor :
public SubmittableExecutor<ConcreteSubmittableExecutor> {
public:
~MultiThreadExecutor() override {}
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_MULTI_THREAD_EXECUTOR_H_
+26
View File
@@ -0,0 +1,26 @@
#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"
namespace location {
namespace nearby {
// An OutputFile represents a writable file on the system.
class OutputFile {
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;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_OUTPUT_FILE_H_
+29
View File
@@ -0,0 +1,29 @@
#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_
+29
View File
@@ -0,0 +1,29 @@
#ifndef PLATFORM_API_SCHEDULED_EXECUTOR_H_
#define PLATFORM_API_SCHEDULED_EXECUTOR_H_
#include <cstdint>
#include "platform/api/executor.h"
#include "platform/cancelable.h"
#include "platform/ptr.h"
#include "platform/runnable.h"
namespace location {
namespace nearby {
// 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 Executor {
public:
virtual ~ScheduledExecutor() {}
virtual Ptr<Cancelable> schedule(Ptr<Runnable> runnable,
std::int64_t delay_millis) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_SCHEDULED_EXECUTOR_H_
+23
View File
@@ -0,0 +1,23 @@
#ifndef PLATFORM_API_SETTABLE_FUTURE_H_
#define PLATFORM_API_SETTABLE_FUTURE_H_
#include "platform/api/future.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
template <typename T>
class SettableFuture : public Future<T> {
public:
~SettableFuture() override {}
virtual bool set(T value) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_SETTABLE_FUTURE_H_
+23
View File
@@ -0,0 +1,23 @@
#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--
template <typename ConcreteSubmittableExecutor>
class SingleThreadExecutor :
public SubmittableExecutor<ConcreteSubmittableExecutor> {
public:
~SingleThreadExecutor() override {}
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_SINGLE_THREAD_EXECUTOR_H_
+26
View File
@@ -0,0 +1,26 @@
#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_
+43
View File
@@ -0,0 +1,43 @@
#ifndef PLATFORM_API_SUBMITTABLE_EXECUTOR_H_
#define PLATFORM_API_SUBMITTABLE_EXECUTOR_H_
#include "platform/api/executor.h"
#include "platform/api/future.h"
#include "platform/callable.h"
#include "platform/port/down_cast.h"
#include "platform/ptr.h"
#include "platform/runnable.h"
namespace location {
namespace nearby {
// Each per-platform concrete implementation is expected to extend from
// SubmittableExecutor and provide an override of its submit() method.
//
// e.g.
// class IOSSubmittableExecutor
// : public SubmittableExecutor<IOSSubmittableExecutor> {
// public:
// template <typename T>
// Ptr<Future<T> > submit(Ptr<Callable<T> > callable) {
// ...
// }
// }
template <typename ConcreteSubmittableExecutor>
class SubmittableExecutor : public Executor {
public:
~SubmittableExecutor() override {}
template <typename T>
Ptr<Future<T> > submit(Ptr<Callable<T> > callable) {
return DOWN_CAST<ConcreteSubmittableExecutor*>(this)->submit(callable);
}
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-
virtual void execute(Ptr<Runnable> runnable) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_SUBMITTABLE_EXECUTOR_H_
+22
View File
@@ -0,0 +1,22 @@
#ifndef PLATFORM_API_SYSTEM_CLOCK_H_
#define PLATFORM_API_SYSTEM_CLOCK_H_
#include <cstdint>
namespace location {
namespace nearby {
class SystemClock {
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;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_SYSTEM_CLOCK_H_
+23
View File
@@ -0,0 +1,23 @@
#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_
+90
View File
@@ -0,0 +1,90 @@
#ifndef PLATFORM_API_WIFI_H_
#define PLATFORM_API_WIFI_H_
#include <cstdint>
#include <vector>
#include "platform/port/string.h"
#include "platform/ptr.h"
namespace location {
namespace nearby {
// Possible authentication types for a WiFi network.
struct WifiAuthType {
enum Value {
UNKNOWN = 0,
OPEN = 1,
WPA_PSK = 2,
WEP = 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,
};
};
// Represents a WiFi network found during a call to WifiMedium#scan().
class WifiScanResult {
public:
virtual ~WifiScanResult() {}
// Gets the SSID of this WiFi network.
virtual std::string getSSID() const = 0;
// Gets the signal strength of this WiFi network in dBm.
virtual std::int32_t getSignalStrengthDbm() const = 0;
// Gets the frequency band of this WiFi network in MHz.
virtual std::int32_t getFrequencyMhz() const = 0;
// Gets the authentication type of this WiFi network.
virtual WifiAuthType::Value getAuthType() const = 0;
};
// Container of operations that can be performed over the WiFi medium.
class WifiMedium {
public:
virtual ~WifiMedium() {}
class ScanResultCallback {
public:
virtual ~ScanResultCallback() {}
// 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;
};
// 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;
// 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;
// Blocks until it's certain of there being a connection to the internet, or
// returns false if it fails to do so.
//
// 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;
// Returns the local device's IP address in the IPv4 dotted-quad format.
virtual std::string getIPAddress() = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_WIFI_H_