upstream changes applied to linux impl

This commit is contained in:
kidfromjupiter
2026-02-04 22:04:03 +00:00
parent 5ec5b2b10f
commit 4d2f34ccfb
50 changed files with 505 additions and 10803 deletions
+53 -10466
View File
File diff suppressed because it is too large Load Diff
+1 -5
View File
@@ -396,7 +396,7 @@ class FileShareApp {
LOG(ERROR) << "Invalid file name: " << path;
return std::nullopt;
}
nearby::InputFile input_file(path, static_cast<std::int64_t>(size));
nearby::InputFile input_file(path);
return nearby::connections::Payload("", file_name, std::move(input_file));
}
@@ -470,10 +470,6 @@ int main(int argc, char** argv) {
::nearby::connections::config_package_nearby::
nearby_connections_feature::kEnableBleL2cap,
true);
nearby::NearbyFlags::GetInstance().OverrideBoolFlagValue(
::nearby::connections::config_package_nearby::
nearby_connections_feature::kEnableBleV2,
true);
Options options;
bool mediums_override = false;
+10 -10
View File
@@ -49,7 +49,7 @@
#include "internal/platform/cancellation_flag.h"
#include "internal/platform/expected.h"
#include "internal/platform/feature_flags.h"
#include "internal/platform/implementation/ble_v2.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/platform.h"
#include "internal/platform/logging.h"
#include "internal/platform/mutex.h"
@@ -63,9 +63,9 @@ namespace connections {
namespace {
using ::location::nearby::proto::connections::OperationResultCode;
using ::nearby::api::ble_v2::BleAdvertisementData;
using ::nearby::api::ble_v2::GattCharacteristic;
using ::nearby::api::ble_v2::TxPowerLevel;
using ::nearby::api::ble::BleAdvertisementData;
using ::nearby::api::ble::GattCharacteristic;
using ::nearby::api::ble::TxPowerLevel;
constexpr int kMaxAdvertisementLength = 512;
constexpr int kDummyServiceIdLength = 128;
@@ -329,11 +329,11 @@ ErrorOr<bool> BleV2::StartLegacyAdvertising(
return {Error(OperationResultCode::CLIENT_BLE_DUPLICATE_ADVERTISING)};
}
std::unique_ptr<api::ble_v2::BleMedium::AdvertisingSession>
std::unique_ptr<api::ble::BleMedium::AdvertisingSession>
legacy_device_advertizing_session = medium_.StartAdvertising(
CreateAdvertisingDataForLegacyDevice(),
{.tx_power_level = TxPowerLevel::kMedium, .is_connectable = true},
api::ble_v2::BleMedium::AdvertisingCallback{
api::ble::BleMedium::AdvertisingCallback{
.start_advertising_result =
[this, &service_id](absl::Status status) mutable {
AssumeHeld(mutex_);
@@ -1154,7 +1154,7 @@ ByteArray BleV2::CreateAdvertisementHeader(
advertisement_hash, psm));
}
api::ble_v2::BleAdvertisementData
api::ble::BleAdvertisementData
BleV2::CreateAdvertisingDataForLegacyDevice() {
BleAdvertisementData advertising_data;
advertising_data.is_extended_advertisement = false;
@@ -1381,7 +1381,7 @@ bool BleV2::StartAsyncScanningLocked(absl::string_view service_id,
auto scanning_session = medium_.StartScanning(
mediums::bleutils::kCopresenceServiceUuid,
PowerLevelToTxPowerLevel(power_level),
api::ble_v2::BleMedium::ScanningCallback{
api::ble::BleMedium::ScanningCallback{
.start_scanning_result =
[this, &service_id](absl::Status status) mutable {
// The `mutex_` is already held here. Use
@@ -1404,7 +1404,7 @@ bool BleV2::StartAsyncScanningLocked(absl::string_view service_id,
}
},
.advertisement_found_cb =
[this](api::ble_v2::BlePeripheral::UniqueId peripheral_id,
[this](api::ble::BlePeripheral::UniqueId peripheral_id,
BleAdvertisementData advertisement_data) {
AssumeHeld(mutex_);
BleV2Peripheral proxy(medium_, peripheral_id);
@@ -1431,7 +1431,7 @@ bool BleV2::StartAsyncScanningLocked(absl::string_view service_id,
});
},
.advertisement_lost_cb =
[](api::ble_v2::BlePeripheral::UniqueId peripheral_id) {
[](api::ble::BlePeripheral::UniqueId peripheral_id) {
// TODO(b/345514862): Implement.
},
});
@@ -22,7 +22,7 @@
#include "absl/strings/substitute.h"
#include "absl/synchronization/mutex.h"
#include "internal/platform/cancellation_flag_listener.h"
#include "internal/platform/implementation/ble_v2.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/linux/ble_gatt_client.h"
#include "internal/platform/implementation/linux/bluez_gatt_characteristic_client.h"
#include "internal/platform/implementation/linux/bluez_gatt_service_client.h"
@@ -41,17 +41,17 @@ bool GattClient::DiscoverServiceAndCharacteristics(
discovery_cancel_);
}
absl::optional<api::ble_v2::GattCharacteristic> GattClient::GetCharacteristic(
absl::optional<api::ble::GattCharacteristic> GattClient::GetCharacteristic(
const Uuid &service_uuid, const Uuid &characteristic_uuid) {
auto chr_proxy = gatt_discovery_->GetCharacteristic(
peripheral_object_path_, service_uuid, characteristic_uuid);
if (chr_proxy == nullptr) return std::nullopt;
api::ble_v2::GattCharacteristic chr;
api::ble::GattCharacteristic chr;
chr.service_uuid = service_uuid;
chr.uuid = characteristic_uuid;
chr.property = api::ble_v2::GattCharacteristic::Property::kNone;
chr.permission = api::ble_v2::GattCharacteristic::Permission::kNone;
chr.property = api::ble::GattCharacteristic::Property::kNone;
chr.permission = api::ble::GattCharacteristic::Permission::kNone;
std::vector<std::string> flags;
try {
@@ -63,15 +63,15 @@ absl::optional<api::ble_v2::GattCharacteristic> GattClient::GetCharacteristic(
for (const auto &flag : flags) {
if (flag == "read") {
chr.property |= api::ble_v2::GattCharacteristic::Property::kRead;
chr.permission |= api::ble_v2::GattCharacteristic::Permission::kRead;
chr.property |= api::ble::GattCharacteristic::Property::kRead;
chr.permission |= api::ble::GattCharacteristic::Permission::kRead;
} else if (flag == "write") {
chr.property |= api::ble_v2::GattCharacteristic::Property::kWrite;
chr.permission |= api::ble_v2::GattCharacteristic::Permission::kWrite;
chr.property |= api::ble::GattCharacteristic::Property::kWrite;
chr.permission |= api::ble::GattCharacteristic::Permission::kWrite;
} else if (flag == "notify") {
chr.property |= api::ble_v2::GattCharacteristic::Property::kNotify;
chr.property |= api::ble::GattCharacteristic::Property::kNotify;
} else if (flag == "indicate") {
chr.property |= api::ble_v2::GattCharacteristic::Property::kIndicate;
chr.property |= api::ble::GattCharacteristic::Property::kIndicate;
}
}
@@ -82,7 +82,7 @@ absl::optional<api::ble_v2::GattCharacteristic> GattClient::GetCharacteristic(
}
absl::optional<std::string> GattClient::ReadCharacteristic(
const api::ble_v2::GattCharacteristic &characteristic) {
const api::ble::GattCharacteristic &characteristic) {
absl::ReaderMutexLock lock(&characteristics_mutex_);
if (characteristics_.count(characteristic) == 0) {
LOG(ERROR) << __func__ << ": Unknown characteristic '"
@@ -105,7 +105,7 @@ absl::optional<std::string> GattClient::ReadCharacteristic(
}
bool GattClient::WriteCharacteristic(
const api::ble_v2::GattCharacteristic &characteristic,
const api::ble::GattCharacteristic &characteristic,
absl::string_view value, WriteType type) {
absl::ReaderMutexLock lock(&characteristics_mutex_);
if (characteristics_.count(characteristic) == 0) {
@@ -121,7 +121,7 @@ bool GattClient::WriteCharacteristic(
chr->WriteValue(
value_bytes,
{{"type",
type == api::ble_v2::GattClient::WriteType::kWithResponse
type == api::ble::GattClient::WriteType::kWithResponse
? "request"
: "command"}});
return true;
@@ -134,7 +134,7 @@ bool GattClient::WriteCharacteristic(
}
bool GattClient::SetCharacteristicSubscription(
const api::ble_v2::GattCharacteristic &characteristic, bool enable,
const api::ble::GattCharacteristic &characteristic, bool enable,
absl::AnyInvocable<void(absl::string_view value)>
on_characteristic_changed_cb) {
absl::MutexLock lock(&characteristics_mutex_);
@@ -23,7 +23,7 @@
#include "absl/container/flat_hash_map.h"
#include "absl/synchronization/mutex.h"
#include "internal/platform/cancellation_flag.h"
#include "internal/platform/implementation/ble_v2.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/linux/bluez.h"
#include "internal/platform/implementation/linux/bluez_gatt_characteristic_client.h"
#include "internal/platform/implementation/linux/bluez_gatt_service_client.h"
@@ -106,7 +106,7 @@ class BluezGattDiscovery final : public bluez::BluezObjectManager {
// https://developer.android.com/reference/android/bluetooth/BluetoothGatt
//
// Representation of a client GATT connection to a remote GATT server.
class GattClient : public api::ble_v2::GattClient {
class GattClient : public api::ble::GattClient {
public:
GattClient(const GattClient &) = delete;
GattClient(GattClient &&) = delete;
@@ -153,7 +153,7 @@ class GattClient : public api::ble_v2::GattClient {
// It is okay for duplicate services to exist, as long as the specified
// characteristic UUID is unique among all services of the same UUID.
// NOLINTNEXTLINE(google3-legacy-absl-backports)
absl::optional<api::ble_v2::GattCharacteristic> GetCharacteristic(
absl::optional<api::ble::GattCharacteristic> GetCharacteristic(
const Uuid &service_uuid, const Uuid &characteristic_uuid) override
ABSL_LOCKS_EXCLUDED(characteristics_mutex_);
@@ -161,7 +161,7 @@ class GattClient : public api::ble_v2::GattClient {
// https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html#getValue()
// NOLINTNEXTLINE(google3-legacy-absl-backports)
absl::optional<std::string> ReadCharacteristic(
const api::ble_v2::GattCharacteristic &characteristic) override
const api::ble::GattCharacteristic &characteristic) override
ABSL_LOCKS_EXCLUDED(characteristics_mutex_);
// https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html#setValue(byte[])
@@ -170,7 +170,7 @@ class GattClient : public api::ble_v2::GattClient {
// Sends a remote characteristic write request to the server and returns
// whether or not it was successful.
bool WriteCharacteristic(
const api::ble_v2::GattCharacteristic &characteristic,
const api::ble::GattCharacteristic &characteristic,
absl::string_view value, WriteType type) override
ABSL_LOCKS_EXCLUDED(characteristics_mutex_);
@@ -178,7 +178,7 @@ class GattClient : public api::ble_v2::GattClient {
//
// Enable or disable notifications/indications for a given characteristic.
bool SetCharacteristicSubscription(
const api::ble_v2::GattCharacteristic &characteristic, bool enable,
const api::ble::GattCharacteristic &characteristic, bool enable,
absl::AnyInvocable<void(absl::string_view value)>
on_characteristic_changed_cb) override
ABSL_LOCKS_EXCLUDED(characteristics_mutex_);
@@ -200,7 +200,7 @@ class GattClient : public api::ble_v2::GattClient {
std::variant<std::unique_ptr<bluez::GattCharacteristicClient>,
std::unique_ptr<bluez::SubscribedGattCharacteristicClient>>;
absl::Mutex characteristics_mutex_;
absl::flat_hash_map<api::ble_v2::GattCharacteristic, CharacteristicProxy>
absl::flat_hash_map<api::ble::GattCharacteristic, CharacteristicProxy>
characteristics_ ABSL_GUARDED_BY(characteristics_mutex_);
};
@@ -14,7 +14,7 @@
#include "internal/platform/implementation/linux/ble_gatt_server.h"
#include "absl/strings/substitute.h"
#include "internal/platform/implementation/ble_v2.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/linux/bluez_gatt_characteristic_server.h"
#include "internal/platform/implementation/linux/bluez_gatt_manager.h"
#include "internal/platform/implementation/linux/bluez_gatt_service_server.h"
@@ -24,16 +24,16 @@
namespace nearby {
namespace linux {
absl::optional<api::ble_v2::GattCharacteristic>
absl::optional<api::ble::GattCharacteristic>
GattServer::CreateCharacteristic(
const Uuid& service_uuid, const Uuid& characteristic_uuid,
api::ble_v2::GattCharacteristic::Permission permission,
api::ble_v2::GattCharacteristic::Property property) {
api::ble::GattCharacteristic::Permission permission,
api::ble::GattCharacteristic::Property property) {
absl::MutexLock lock(&services_mutex_);
if (services_.count(service_uuid) == 1) {
if (services_[service_uuid]->AddCharacteristic(
service_uuid, characteristic_uuid, permission, property)) {
api::ble_v2::GattCharacteristic characteristic{
api::ble::GattCharacteristic characteristic{
characteristic_uuid, service_uuid, permission, property};
return characteristic;
}
@@ -78,7 +78,7 @@ GattServer::CreateCharacteristic(
services_.insert({service_uuid, std::move(service)});
api::ble_v2::GattCharacteristic characteristic{
api::ble::GattCharacteristic characteristic{
characteristic_uuid, service_uuid, permission, property};
return characteristic;
}
@@ -87,7 +87,7 @@ GattServer::CreateCharacteristic(
}
bool GattServer::UpdateCharacteristic(
const api::ble_v2::GattCharacteristic& characteristic,
const api::ble::GattCharacteristic& characteristic,
const nearby::ByteArray& value) {
std::shared_ptr<bluez::GattCharacteristicServer> chr = nullptr;
{
@@ -114,7 +114,7 @@ bool GattServer::UpdateCharacteristic(
}
absl::Status GattServer::NotifyCharacteristicChanged(
const api::ble_v2::GattCharacteristic& characteristic, bool confirm,
const api::ble::GattCharacteristic& characteristic, bool confirm,
const ByteArray& new_value) {
std::shared_ptr<bluez::GattCharacteristicServer> chr = nullptr;
{
@@ -27,7 +27,7 @@
#include "absl/types/optional.h"
#include "internal/platform/bluetooth_utils.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/implementation/ble_v2.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/linux/bluetooth_adapter.h"
#include "internal/platform/implementation/linux/bluetooth_devices.h"
#include "internal/platform/implementation/linux/bluez_gatt_service_server.h"
@@ -35,15 +35,15 @@
namespace nearby {
namespace linux {
class LocalBlePeripheral : public api::ble_v2::BlePeripheral {
class LocalBlePeripheral : public api::ble::BlePeripheral {
public:
explicit LocalBlePeripheral(BluetoothAdapter& adapter) : adapter_(adapter) {
// temp fix till everything transitions to GGetAddress()
unique_id_ = std::stoull(std::regex_replace(adapter_.GetMacAddress(),
unique_id_ = std::stoull(std::regex_replace(adapter_.GetMacAddress().ToString(),
std::regex("[:\\-]"), ""), nullptr, 16);
}
std::string GetAddress() const override { return adapter_.GetMacAddress(); }
std::string GetAddress() const override { return adapter_.GetMacAddress().ToString(); }
UniqueId GetUniqueId() const override { return unique_id_; }
private:
@@ -51,7 +51,7 @@ class LocalBlePeripheral : public api::ble_v2::BlePeripheral {
UniqueId unique_id_;
};
class GattServer : public api::ble_v2::GattServer {
class GattServer : public api::ble::GattServer {
public:
GattServer(const GattServer&) = delete;
GattServer(GattServer&&) = delete;
@@ -60,26 +60,26 @@ class GattServer : public api::ble_v2::GattServer {
explicit GattServer(sdbus::IConnection& system_bus, BluetoothAdapter& adapter,
std::shared_ptr<BluetoothDevices> devices,
api::ble_v2::ServerGattConnectionCallback server_cb)
api::ble::ServerGattConnectionCallback server_cb)
: system_bus_(system_bus),
devices_(std::move(devices)),
adapter_(adapter),
local_peripheral_(adapter_),
gatt_service_root_object_manager(std::make_unique<RootObjectManager>(system_bus_, "/com/google/nearby/medium/ble/gatt")),
gatt_manager_(std::make_unique<bluez::GattManager>(system_bus_, adapter_.GetObjectPath())),
server_cb_(std::make_shared<api::ble_v2::ServerGattConnectionCallback>(
server_cb_(std::make_shared<api::ble::ServerGattConnectionCallback>(
std::move(server_cb))) {}
~GattServer() override = default;
absl::optional<api::ble_v2::GattCharacteristic> CreateCharacteristic(
absl::optional<api::ble::GattCharacteristic> CreateCharacteristic(
const Uuid& service_uuid, const Uuid& characteristic_uuid,
api::ble_v2::GattCharacteristic::Permission permission,
api::ble_v2::GattCharacteristic::Property property) override;
api::ble::GattCharacteristic::Permission permission,
api::ble::GattCharacteristic::Property property) override;
bool UpdateCharacteristic(
const api::ble_v2::GattCharacteristic& characteristic,
const api::ble::GattCharacteristic& characteristic,
const nearby::ByteArray& value) override;
absl::Status NotifyCharacteristicChanged(
const api::ble_v2::GattCharacteristic& characteristic, bool confirm,
const api::ble::GattCharacteristic& characteristic, bool confirm,
const ByteArray& new_value) override;
void Stop() override;
@@ -94,7 +94,7 @@ class GattServer : public api::ble_v2::GattServer {
absl::flat_hash_map<Uuid, std::unique_ptr<bluez::GattProfile>> gatt_profiles_;
ABSL_GUARDED_BY(profiles_mutex_)
std::unique_ptr<bluez::GattManager> gatt_manager_;
std::shared_ptr<api::ble_v2::ServerGattConnectionCallback> server_cb_;
std::shared_ptr<api::ble::ServerGattConnectionCallback> server_cb_;
absl::Mutex services_mutex_;
absl::flat_hash_map<Uuid, std::unique_ptr<bluez::GattServiceServer>> services_
ABSL_GUARDED_BY(services_mutex_);
@@ -37,7 +37,7 @@ BleL2capServerSocket::~BleL2capServerSocket() { Close(); }
void BleL2capServerSocket::SetPSM(int psm) { psm_ = psm; }
std::unique_ptr<api::ble_v2::BleL2capSocket> BleL2capServerSocket::Accept() {
std::unique_ptr<api::ble::BleL2capSocket> BleL2capServerSocket::Accept() {
if (stopped_.Cancelled()) {
LOG(ERROR) << __func__ << ": server socket has been stopped";
return nullptr;
@@ -144,7 +144,7 @@ std::unique_ptr<api::ble_v2::BleL2capSocket> BleL2capServerSocket::Accept() {
LOG(INFO) << __func__ << ": Connected to client_fd: " << client_fd;
// Create a unique ID from the MAC address
api::ble_v2::BlePeripheral::UniqueId peripheral_id = 0;
api::ble::BlePeripheral::UniqueId peripheral_id = 0;
for (int i = 0; i < 6; i++) {
peripheral_id = (peripheral_id << 8) | client_addr.l2_bdaddr.b[i];
}
@@ -22,13 +22,13 @@
#include "absl/synchronization/mutex.h"
#include "internal/platform/exception.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/ble_v2.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/linux/ble_l2cap_socket.h"
#include "absl/container/flat_hash_map.h"
namespace nearby {
namespace linux {
class BleL2capServerSocket final : public api::ble_v2::BleL2capServerSocket {
class BleL2capServerSocket final : public api::ble::BleL2capServerSocket {
public:
BleL2capServerSocket();
explicit BleL2capServerSocket(int psm);
@@ -37,7 +37,7 @@ class BleL2capServerSocket final : public api::ble_v2::BleL2capServerSocket {
int GetPSM() const override { return psm_; }
void SetPSM(int psm);
std::unique_ptr<api::ble_v2::BleL2capSocket> Accept() override
std::unique_ptr<api::ble::BleL2capSocket> Accept() override
ABSL_LOCKS_EXCLUDED(mutex_);
Exception Close() override ABSL_LOCKS_EXCLUDED(mutex_);
@@ -56,7 +56,7 @@ class BleL2capServerSocket final : public api::ble_v2::BleL2capServerSocket {
CancellationFlag stopped_;
// <server_fd, <client_fd, peripheral_id>>
absl::flat_hash_map<int, std::pair<int,api::ble_v2::BlePeripheral::UniqueId>> accepted_fds_ ABSL_GUARDED_BY(mutex_);
absl::flat_hash_map<int, std::pair<int,api::ble::BlePeripheral::UniqueId>> accepted_fds_ ABSL_GUARDED_BY(mutex_);
};
} // namespace linux
@@ -190,13 +190,13 @@ BleL2capOutputStream::BleL2capOutputStream(int fd) : fd_(fd) {}
BleL2capOutputStream::~BleL2capOutputStream() { Close(); }
Exception BleL2capOutputStream::Write(const ByteArray& data) {
Exception BleL2capOutputStream::Write(absl::string_view data) {
int fd = fd_.load();
if (fd < 0) return Exception{Exception::kIo};
auto poller = Poller::CreateOutputPoller(fd);
if (data.Empty()) {
if (data.empty()) {
return {Exception::kSuccess};
}
@@ -45,7 +45,7 @@ class BleL2capOutputStream final : public OutputStream {
explicit BleL2capOutputStream(int fd);
~BleL2capOutputStream() override;
Exception Write(const ByteArray& data) override;
Exception Write(absl::string_view data) override;
Exception Flush() override { return {Exception::kSuccess}; }
Exception Close() override;
@@ -54,9 +54,9 @@ class BleL2capOutputStream final : public OutputStream {
std::atomic<int> fd_{-1};
};
class BleL2capSocket final : public api::ble_v2::BleL2capSocket {
class BleL2capSocket final : public api::ble::BleL2capSocket {
public:
BleL2capSocket(int fd, api::ble_v2::BlePeripheral::UniqueId peripheral_id);
BleL2capSocket(int fd, api::ble::BlePeripheral::UniqueId peripheral_id);
~BleL2capSocket() override;
InputStream& GetInputStream() override { return *input_stream_; }
@@ -64,7 +64,7 @@ class BleL2capSocket final : public api::ble_v2::BleL2capSocket {
Exception Close() override ABSL_LOCKS_EXCLUDED(mutex_);
void SetCloseNotifier(absl::AnyInvocable<void()> notifier) override
ABSL_LOCKS_EXCLUDED(mutex_);
api::ble_v2::BlePeripheral::UniqueId GetRemotePeripheralId() override {
api::ble::BlePeripheral::UniqueId GetRemotePeripheralId() override {
return peripheral_id_;
}
@@ -77,7 +77,7 @@ class BleL2capSocket final : public api::ble_v2::BleL2capSocket {
bool closed_ ABSL_GUARDED_BY(mutex_) = false;
std::unique_ptr<BleL2capInputStream> input_stream_;
std::unique_ptr<BleL2capOutputStream> output_stream_;
api::ble_v2::BlePeripheral::UniqueId peripheral_id_;
api::ble::BlePeripheral::UniqueId peripheral_id_;
absl::AnyInvocable<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
};
@@ -541,7 +541,7 @@ std::unique_ptr<api::ble::BleL2capSocket> BleV2Medium::ConnectOverL2cap(
}
LOG(INFO) << __func__ << ": Connecting to L2CAP PSM " << psm
<< " on device " << device->GetMacAddress();
<< " on device " << device->GetMacAddress().ToString();
int fd = socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP);
@@ -575,7 +575,7 @@ std::unique_ptr<api::ble::BleL2capSocket> BleV2Medium::ConnectOverL2cap(
LOG(WARNING) << __func__ << ": Failed to set BT_RCVMTU: "
<< std::strerror(errno);
}
std::string mac_addr = device->GetMacAddress();
std::string mac_addr = device->GetMacAddress().ToString();
if (str2ba(mac_addr.c_str(), &addr.l2_bdaddr) < 0) {
LOG(ERROR) << __func__ << ": Invalid Bluetooth address: " << mac_addr;
close(fd);
@@ -184,7 +184,7 @@ void BleV2Socket::SetGattServer(
// Notify remote device via TX characteristic
absl::Status status = gatt_server_->NotifyCharacteristicChanged(
tx_char_, /*confirm=*/false, data);
tx_char_, /*confirm=*/false, ByteArray::FromStringView(data));
if (!status.ok()) {
LOG(WARNING) << "Failed to notify TX characteristic: "
@@ -61,7 +61,7 @@ class BleV2Socket : public api::ble::BleSocket {
// GATT integration: Set callback for output stream writes
// Callback should write to TX characteristic (notify remote)
void SetWriteCallback(
absl::AnyInvocable<bool(const ByteArray& data)> callback) {
absl::AnyInvocable<bool(absl::string_view data)> callback) {
output_stream_.SetWriteCallback(std::move(callback));
}
@@ -17,7 +17,7 @@
#include "absl/status/status.h"
#include "absl/synchronization/mutex.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/implementation/ble_v2.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/linux/ble_v2_socket.h"
#include "internal/platform/logging.h"
#include "internal/platform/uuid.h"
@@ -43,42 +43,42 @@ Uuid BleV2SocketAdapter::GetTxCharacteristicUuid() {
}
void BleV2SocketAdapter::RegisterSocket(
api::ble_v2::BlePeripheral::UniqueId device_id, BleV2Socket* socket) {
api::ble::BlePeripheral::UniqueId device_id, BleV2Socket* socket) {
absl::MutexLock lock(&mutex_);
device_sockets_[device_id] = socket;
LOG(INFO) << "Registered socket for device " << device_id;
}
void BleV2SocketAdapter::UnregisterSocket(
api::ble_v2::BlePeripheral::UniqueId device_id) {
api::ble::BlePeripheral::UniqueId device_id) {
absl::MutexLock lock(&mutex_);
device_sockets_.erase(device_id);
LOG(INFO) << "Unregistered socket for device " << device_id;
}
api::ble_v2::ServerGattConnectionCallback
api::ble::ServerGattConnectionCallback
BleV2SocketAdapter::CreateServerCallbacks() {
api::ble_v2::ServerGattConnectionCallback callbacks;
api::ble::ServerGattConnectionCallback callbacks;
// Handle subscription to TX characteristic (remote wants to receive data)
callbacks.characteristic_subscription_cb =
[](const api::ble_v2::GattCharacteristic& characteristic) {
[](const api::ble::GattCharacteristic& characteristic) {
LOG(INFO) << "Remote subscribed to characteristic: "
<< std::string(characteristic.uuid);
};
// Handle unsubscription
callbacks.characteristic_unsubscription_cb =
[](const api::ble_v2::GattCharacteristic& characteristic) {
[](const api::ble::GattCharacteristic& characteristic) {
LOG(INFO) << "Remote unsubscribed from characteristic: "
<< std::string(characteristic.uuid);
};
// Handle read requests (not typically used for socket data transfer)
callbacks.on_characteristic_read_cb =
[](api::ble_v2::BlePeripheral::UniqueId remote_device_id,
const api::ble_v2::GattCharacteristic& characteristic, int offset,
api::ble_v2::ServerGattConnectionCallback::ReadValueCallback
[](api::ble::BlePeripheral::UniqueId remote_device_id,
const api::ble::GattCharacteristic& characteristic, int offset,
api::ble::ServerGattConnectionCallback::ReadValueCallback
callback) {
LOG(INFO) << "Read request from device " << remote_device_id
<< " on characteristic "
@@ -89,10 +89,10 @@ BleV2SocketAdapter::CreateServerCallbacks() {
// Handle write requests - THIS IS WHERE DATA COMES IN
callbacks.on_characteristic_write_cb =
[this](api::ble_v2::BlePeripheral::UniqueId remote_device_id,
const api::ble_v2::GattCharacteristic& characteristic, int offset,
[this](api::ble::BlePeripheral::UniqueId remote_device_id,
const api::ble::GattCharacteristic& characteristic, int offset,
absl::string_view data,
api::ble_v2::ServerGattConnectionCallback::WriteValueCallback
api::ble::ServerGattConnectionCallback::WriteValueCallback
callback) {
LOG(INFO) << "Write request from device " << remote_device_id
<< " on characteristic "
@@ -21,7 +21,7 @@
#include "absl/container/flat_hash_map.h"
#include "absl/synchronization/mutex.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/implementation/ble_v2.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/linux/ble_v2_socket.h"
#include "internal/platform/uuid.h"
@@ -36,15 +36,15 @@ class BleV2SocketAdapter {
~BleV2SocketAdapter() = default;
// Create GATT server callbacks that will route data to/from sockets
api::ble_v2::ServerGattConnectionCallback CreateServerCallbacks();
api::ble::ServerGattConnectionCallback CreateServerCallbacks();
// Register a socket for a specific remote device
// When GATT writes come from this device, data is routed to this socket
void RegisterSocket(api::ble_v2::BlePeripheral::UniqueId device_id,
void RegisterSocket(api::ble::BlePeripheral::UniqueId device_id,
BleV2Socket* socket) ABSL_LOCKS_EXCLUDED(mutex_);
// Unregister a socket
void UnregisterSocket(api::ble_v2::BlePeripheral::UniqueId device_id)
void UnregisterSocket(api::ble::BlePeripheral::UniqueId device_id)
ABSL_LOCKS_EXCLUDED(mutex_);
// Get the RX characteristic UUID (for receiving data from remote)
@@ -56,7 +56,7 @@ class BleV2SocketAdapter {
private:
absl::Mutex mutex_;
// Map of device ID to socket for routing incoming GATT writes
absl::flat_hash_map<api::ble_v2::BlePeripheral::UniqueId, BleV2Socket*>
absl::flat_hash_map<api::ble::BlePeripheral::UniqueId, BleV2Socket*>
device_sockets_ ABSL_GUARDED_BY(mutex_);
};
@@ -108,9 +108,11 @@ bool BluetoothAdapter::SetName(absl::string_view name) {
}
}
std::string BluetoothAdapter::GetMacAddress() const {
MacAddress BluetoothAdapter::GetMacAddress() const {
try {
return bluez_adapter_->Address();
MacAddress addr;
MacAddress::FromString(bluez_adapter_ -> Address(), addr);
return addr;
} catch (const sdbus::Error &e) {
DBUS_LOG_PROPERTY_GET_ERROR(bluez_adapter_, "Address", e);
return {};
@@ -55,7 +55,7 @@ class BluetoothAdapter : public api::BluetoothAdapter {
bool SetName(absl::string_view name) override;
bool SetName(absl::string_view name, bool persist) override;
std::string GetMacAddress() const override;
MacAddress GetMacAddress() const override;
bool RemoveDeviceByObjectPath(const sdbus::ObjectPath &device_object_path) {
try {
@@ -83,7 +83,7 @@ void Profile::NewConnection(
<< " path=" << device_object_path;
{
absl::MutexLock l(&connections_lock_);
connections_[mac_addr.ToString()].push_back(std::pair(fd, props));
connections_[mac_addr].push_back(std::pair(fd, props));
}
}
@@ -98,7 +98,7 @@ void Profile::RequestDisconnection(
throw sdbus::Error("org.bluez.Error.Rejected", "Unknown object");
}
auto mac_addr = device->GetMacAddress();
auto mac_addr = device -> GetMacAddress();
LOG(INFO) << __func__ << ": Disconnection requested for device "
<< device_object_path;
@@ -202,21 +202,21 @@ std::optional<sdbus::UnixFd> ProfileManager::GetServiceRecordFD(
LOG(INFO) << __func__ << ": " << profile->getObjectPath()
<< ": Attempting to get a FD for service "
<< service_uuid << " on device " << mac_addr;
<< service_uuid << " on device " << mac_addr.ToString();
LOG(INFO) << "WAIT profile=" << profile.get()
<< " mutex=" << &profile->connections_lock_
<< " obj=" << profile->getObjectPath()
<< " key=" << mac_addr;
<< " key=" << mac_addr.ToString();
auto cond = [mac_addr, profile, cancellation_flag]() {
profile->connections_lock_.AssertHeld();
LOG(INFO) << "connections_lock_ is held by: " << mac_addr << " with ptr: " << &profile -> connections_lock_;
LOG(INFO) << "connections_lock_ is held by: " << mac_addr.ToString() << " with ptr: " << &profile -> connections_lock_;
return profile->connections_.count(mac_addr) != 0 ||
(cancellation_flag != nullptr && cancellation_flag->Cancelled());
};
// BUG: Race condition. Hangs here
LOG(INFO) << "WAIT key(GetMacAddress)=" << mac_addr;
LOG(INFO) << "WAIT key(GetMacAddress)=" << mac_addr.ToString();
LOG(INFO) << "connections_ size" << profile -> connections_.size();
absl::MutexLock connections_lock(&profile->connections_lock_,
absl::Condition(&cond));
@@ -229,7 +229,7 @@ std::optional<sdbus::UnixFd> ProfileManager::GetServiceRecordFD(
if (cancellation_flag != nullptr && cancellation_flag->Cancelled()) {
LOG(INFO)
<< __func__ << ": " << profile->getObjectPath() << ": "
<< remote_device.GetMacAddress()
<< remote_device.GetMacAddress().ToString()
<< ": Cancelled waiting for a new connection on profile "
<< service_uuid;
return std::nullopt;
@@ -297,7 +297,7 @@ ProfileManager::GetServiceRecordFD(absl::string_view service_uuid,
}
// Find first connection without pending outgoing
std::string mac_addr;
MacAddress mac_addr;
sdbus::UnixFd fd;
bool found = false;
@@ -327,7 +327,7 @@ ProfileManager::GetServiceRecordFD(absl::string_view service_uuid,
auto device = devices_.get_device_by_address(mac_addr);
if (device == nullptr) {
LOG(ERROR) << __func__ << ": Device " << mac_addr
LOG(ERROR) << __func__ << ": Device " << mac_addr.ToString()
<< " is no longer available";
return std::nullopt;
}
@@ -335,7 +335,7 @@ ProfileManager::GetServiceRecordFD(absl::string_view service_uuid,
return std::pair(device, std::move(fd));
}
void ProfileManager::MarkPendingOutgoing(absl::string_view service_uuid,
const std::string& mac_address) {
const MacAddress& mac_address) {
absl::ReaderMutexLock lock(&registered_service_uuids_mutex_);
if (registered_services_.count(std::string(service_uuid)) == 0) {
return;
@@ -343,12 +343,12 @@ ProfileManager::GetServiceRecordFD(absl::string_view service_uuid,
auto profile = registered_services_[std::string(service_uuid)];
absl::MutexLock l(&profile->connections_lock_);
profile->pending_outgoing_.insert(mac_address);
LOG(INFO) << __func__ << ": Marked " << mac_address
LOG(INFO) << __func__ << ": Marked " << mac_address.ToString()
<< " as pending outgoing for " << service_uuid;
}
void ProfileManager::ClearPendingOutgoing(absl::string_view service_uuid,
const std::string& mac_address) {
const MacAddress& mac_address) {
absl::ReaderMutexLock lock(&registered_service_uuids_mutex_);
if (registered_services_.count(std::string(service_uuid)) == 0) {
return;
@@ -356,7 +356,7 @@ ProfileManager::GetServiceRecordFD(absl::string_view service_uuid,
auto profile = registered_services_[std::string(service_uuid)];
absl::MutexLock l(&profile->connections_lock_);
profile->pending_outgoing_.erase(mac_address);
LOG(INFO) << __func__ << ": Cleared " << mac_address
LOG(INFO) << __func__ << ": Cleared " << mac_address.ToString()
<< " as pending outgoing for " << service_uuid;
}
} // namespace linux
@@ -93,11 +93,11 @@ class Profile final
std::atomic_bool released_;
absl::Mutex connections_lock_;
std::map<std::string, std::vector<std::pair<sdbus::UnixFd, FDProperties>>>
std::map<MacAddress, std::vector<std::pair<sdbus::UnixFd, FDProperties>>>
connections_ ABSL_GUARDED_BY(connections_lock_);
// Track pending outgoing connection attempts to avoid race with incoming
std::set<std::string> pending_outgoing_ ABSL_GUARDED_BY(connections_lock_);
std::set<MacAddress> pending_outgoing_ ABSL_GUARDED_BY(connections_lock_);
BluetoothDevices &devices_;
};
@@ -137,10 +137,10 @@ class ProfileManager final
CancellationFlag *cancellation_flag)
ABSL_LOCKS_EXCLUDED(registered_service_uuids_mutex_);
void MarkPendingOutgoing(absl::string_view service_uuid,
const std::string& mac_address)
const MacAddress& mac_address)
ABSL_LOCKS_EXCLUDED(registered_service_uuids_mutex_);
void ClearPendingOutgoing(absl::string_view service_uuid,
const std::string& mac_address)
const MacAddress& mac_address)
ABSL_LOCKS_EXCLUDED(registered_service_uuids_mutex_);
private:
BluetoothDevices &devices_;
@@ -63,11 +63,13 @@ std::string BluetoothDevice::GetName() const {
}
}
std::string BluetoothDevice::GetMacAddress() const {
MacAddress BluetoothDevice::GetMacAddress() const {
auto device = device_;
if (device == nullptr) {
absl::ReaderMutexLock l(&properties_mutex_);
return last_known_name_;
MacAddress addr;
MacAddress::FromString("00:00:00:00:00:00", addr);
return addr;
}
try {
@@ -76,10 +78,12 @@ std::string BluetoothDevice::GetMacAddress() const {
absl::MutexLock l(&properties_mutex_);
MacAddress::FromString(addr, last_known_address_);
}
return addr;
return last_known_address_;
} catch (const sdbus::Error &e) {
DBUS_LOG_PROPERTY_GET_ERROR(device, "Address", e);
return std::string();
MacAddress addr;
MacAddress::FromString("00:00:00:00:00:00", addr);
return addr;
}
}
@@ -29,7 +29,7 @@
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "internal/base/observer_list.h"
// #include "internal/platform/implementation/ble_v2.h"
// #include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/bluetooth_classic.h"
#include "internal/platform/implementation/linux/bluez_device.h"
#include "internal/platform/implementation/linux/dbus.h"
@@ -51,10 +51,10 @@ class BluetoothDevice : public api::BluetoothDevice {
explicit BluetoothDevice(std::shared_ptr<bluez::Device> device);
std::string GetName() const override;
std::string GetMacAddress() const override;
MacAddress GetMacAddress() const override;
std::string GetAddressType() const;
MacAddress GetAddress() const override { return last_known_address_; }
MacAddress GetAddress() const { return last_known_address_; }
std::optional<std::map<std::string, sdbus::Variant>> ServiceData() {
auto device = device_;
@@ -34,21 +34,21 @@
namespace nearby {
namespace linux {
BluetoothClassicMedium::BluetoothClassicMedium(BluetoothAdapter &adapter)
: system_bus_(adapter.GetConnection()),
adapter_(adapter),
observers_(nullptr),
devices_(nullptr),
device_watcher_(nullptr),
// agent_manager_(std::make_unique<AgentManager>(*system_bus_)),
profile_manager_(nullptr) {
auto shared =
GetSharedBluetoothDevices(system_bus_, adapter_.GetObjectPath());
observers_ = shared->observers;
devices_ = shared->devices;
profile_manager_ =
std::make_unique<ProfileManager>(*system_bus_, *devices_);
}
BluetoothClassicMedium::BluetoothClassicMedium(BluetoothAdapter &adapter)
: system_bus_(adapter.GetConnection()),
adapter_(adapter),
observers_(nullptr),
devices_(nullptr),
device_watcher_(nullptr),
// agent_manager_(std::make_unique<AgentManager>(*system_bus_)),
profile_manager_(nullptr) {
auto shared =
GetSharedBluetoothDevices(system_bus_, adapter_.GetObjectPath());
observers_ = shared->observers;
devices_ = shared->devices;
profile_manager_ =
std::make_unique<ProfileManager>(*system_bus_, *devices_);
}
bool BluetoothClassicMedium::StartDiscovery(
DiscoveryCallback discovery_callback) {
@@ -114,14 +114,14 @@ std::unique_ptr<api::BluetoothSocket> BluetoothClassicMedium::ConnectToService(
auto address = remote_device.GetMacAddress();
auto device = devices_->get_device_by_address(address);
if (device == nullptr) {
LOG(ERROR) << __func__ << ": Device " << address
LOG(ERROR) << __func__ << ": Device " << address.ToString()
<< " is no longer known";
return nullptr;
}
if (!device -> Bonded())
{
LOG(ERROR) << __func__ << ": Device " << address
LOG(ERROR) << __func__ << ": Device " << address.ToString()
<< " is not Bonded";
}
// Mark as pending BEFORE calling ConnectToProfile to win the race
@@ -137,7 +137,7 @@ std::unique_ptr<api::BluetoothSocket> BluetoothClassicMedium::ConnectToService(
if (!fd.has_value()) {
LOG(WARNING) << __func__
<< ": Failed to get a new connection for profile "
<< service_uuid << " for device " << address;
<< service_uuid << " for device " << address.ToString();
return nullptr;
}
@@ -166,7 +166,7 @@ BluetoothClassicMedium::ListenForService(const std::string &service_name,
api::BluetoothDevice *BluetoothClassicMedium::GetRemoteDevice(
MacAddress mac_address) {
// When BLE is discovering, it looks for remote devices to connect to using BT classic. If only
auto device = devices_->get_device_by_address(mac_address.ToString());
auto device = devices_->get_device_by_address(mac_address);
if (device == nullptr) return nullptr;
return device.get();
@@ -216,7 +216,7 @@ Exception BluetoothInputStream::Close() {
return {Exception::kSuccess};
}
Exception BluetoothOutputStream::Write(const ByteArray &data) {
Exception BluetoothOutputStream::Write(absl::string_view data) {
int fd = fd_raw_.load();
if (fd < 0) return Exception{Exception::kIo};
@@ -83,7 +83,7 @@ class BluetoothOutputStream : public nearby::OutputStream {
explicit BluetoothOutputStream(sdbus::UnixFd fd)
: fd_(std::move(fd)), fd_raw_(fd_.get()) {}
Exception Write(const ByteArray &data) override;
Exception Write(absl::string_view data) override;
Exception Flush() override { return {Exception::kSuccess}; }
Exception Close() override;
@@ -69,7 +69,7 @@ std::shared_ptr<BluetoothDevice> BluetoothDevices::get_device_by_path(
return devices_by_path_[device_object_path];
}
std::shared_ptr<BluetoothDevice> BluetoothDevices::get_device_by_unique_id(
api::ble_v2::BlePeripheral::UniqueId id)
api::ble::BlePeripheral::UniqueId id)
{
// converting from stoull to mac again
id &= 0x0000FFFFFFFFFFFFULL; // keep 48 bits
@@ -77,17 +77,22 @@ std::shared_ptr<BluetoothDevice> BluetoothDevices::get_device_by_unique_id(
oss << std::hex << std::setfill('0') << std::setw(12) << id;
std::string hex = oss.str(); // e.g. "aabbccddeeff"
std::string mac;
for (int i = 0; i < 6; ++i) {
if (i) mac.push_back(':');
mac.append(hex.substr(i * 2, 2));
MacAddress addr;
{
std::string mac;
for (int i = 0; i < 6; ++i) {
if (i) mac.push_back(':');
mac.append(hex.substr(i * 2, 2));
}
MacAddress::FromString(mac, addr);
}
return get_device_by_address(mac);
return get_device_by_address(addr);
}
std::shared_ptr<BluetoothDevice> BluetoothDevices::get_device_by_address(
const std::string &addr) {
const MacAddress &addr) {
auto device_object_path =
bluez::device_object_path(adapter_object_path_, addr);
bluez::device_object_path(adapter_object_path_, addr.ToString());
return get_device_by_path(device_object_path);
}
@@ -49,9 +49,9 @@ class BluetoothDevices final {
std::shared_ptr<BluetoothDevice> get_device_by_path(const sdbus::ObjectPath &)
ABSL_LOCKS_EXCLUDED(devices_by_path_lock_);
std::shared_ptr<BluetoothDevice> get_device_by_address(const std::string &);
std::shared_ptr<BluetoothDevice> get_device_by_address(const MacAddress &);
std::shared_ptr<BluetoothDevice> get_device_by_unique_id(
api::ble_v2::BlePeripheral::UniqueId id);
api::ble::BlePeripheral::UniqueId id);
std::shared_ptr<MonitoredBluetoothDevice> add_new_device(sdbus::ObjectPath)
ABSL_LOCKS_EXCLUDED(devices_by_path_lock_);
@@ -36,7 +36,7 @@ void BluetoothPairing::pairing_reply_handler(const sdbus::Error *error) {
<< "Got error '" << error->getName()
<< "' with message '" << error->getMessage()
<< "' while pairing with device "
<< device_->GetMacAddress();
<< device_->GetMacAddress().ToString();
if (name == "org.bluez.Error.AuthenticationCanceled") {
err = api::BluetoothPairingCallback::PairingError::kAuthCanceled;
@@ -65,17 +65,17 @@ sdbus::ObjectPath advertisement_monitor_path(absl::string_view uuid) {
absl::StrReplaceAll(uuid, {{"-", "_"}}));
}
int16_t TxPowerLevelDbm(api::ble_v2::TxPowerLevel level) {
int16_t TxPowerLevelDbm(api::ble::TxPowerLevel level) {
switch (level) {
case api::ble_v2::TxPowerLevel::kUnknown:
case api::ble::TxPowerLevel::kUnknown:
return 0;
case api::ble_v2::TxPowerLevel::kUltraLow:
case api::ble::TxPowerLevel::kUltraLow:
return -3;
case api::ble_v2::TxPowerLevel::kLow:
case api::ble::TxPowerLevel::kLow:
return 0;
case api::ble_v2::TxPowerLevel::kMedium:
case api::ble::TxPowerLevel::kMedium:
return 5;
case api::ble_v2::TxPowerLevel::kHigh:
case api::ble::TxPowerLevel::kHigh:
return 10; // Increased from 6 to 10 dBm (maximum for most adapters)
}
}
@@ -20,7 +20,7 @@
#include <sdbus-c++/Types.h>
#include "absl/strings/string_view.h"
#include "internal/platform/implementation/ble_v2.h"
#include "internal/platform/implementation/ble.h"
#include <string>
@@ -61,7 +61,7 @@ sdbus::ObjectPath gatt_characteristic_path(
const sdbus::ObjectPath &service_path, size_t num);
sdbus::ObjectPath ble_advertisement_path(size_t num);
sdbus::ObjectPath advertisement_monitor_path(absl::string_view uuid);
int16_t TxPowerLevelDbm(api::ble_v2::TxPowerLevel level);
int16_t TxPowerLevelDbm(api::ble::TxPowerLevel level);
class BluezObjectManager
: public sdbus::ProxyInterfaces<sdbus::ObjectManager_proxy> {
@@ -3,7 +3,7 @@
#include <regex>
#include "internal/platform/byte_array.h"
#include "internal/platform/implementation/ble_v2.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/linux/dbus.h"
#include "internal/platform/implementation/linux/utils.h"
#include "internal/platform/uuid.h"
@@ -12,21 +12,21 @@ namespace linux {
namespace bluez {
AdvertisementMonitor::AdvertisementMonitor(
sdbus::IConnection &system_bus, Uuid service_uuid,
api::ble_v2::TxPowerLevel tx_power_level, absl::string_view type,
api::ble::TxPowerLevel tx_power_level, absl::string_view type,
std::shared_ptr<BluetoothDevices> devices,
api::ble_v2::BleMedium::ScanCallback scan_callback)
api::ble::BleMedium::ScanCallback scan_callback)
: AdvertisementMonitor(
system_bus, service_uuid, tx_power_level, type, std::move(devices),
api::ble_v2::BleMedium::ScanningCallback{
api::ble::BleMedium::ScanningCallback{
.start_scanning_result = nullptr,
.advertisement_found_cb =
std::move(scan_callback.advertisement_found_cb)}) {}
AdvertisementMonitor::AdvertisementMonitor(
sdbus::IConnection &system_bus, Uuid service_uuid,
api::ble_v2::TxPowerLevel tx_power_level, absl::string_view type,
api::ble::TxPowerLevel tx_power_level, absl::string_view type,
std::shared_ptr<BluetoothDevices> devices,
api::ble_v2::BleMedium::ScanningCallback scan_callback)
api::ble::BleMedium::ScanningCallback scan_callback)
: AdaptorInterfaces(system_bus, bluez::advertisement_monitor_path(
std::string{service_uuid})),
devices_(std::move(devices)),
@@ -45,7 +45,7 @@ void AdvertisementMonitor::DeviceFound(const sdbus::ObjectPath &device) {
auto service_data = peripheral->ServiceData();
if (!service_data.has_value()) return;
struct api::ble_v2::BleAdvertisementData adv_data;
struct api::ble::BleAdvertisementData adv_data;
for (const auto &[uuid_str, data] : *service_data) {
auto uuid = UuidFromString(uuid_str);
if (!uuid.has_value()) {
@@ -60,7 +60,7 @@ void AdvertisementMonitor::DeviceFound(const sdbus::ObjectPath &device) {
adv_data.service_data.emplace(*uuid,
std::string(bytes.begin(), bytes.end()));
}
auto id = std::stoull(std::regex_replace(peripheral->GetMacAddress(),
auto id = std::stoull(std::regex_replace(peripheral->GetMacAddress().ToString(),
std::regex("[:\\-]"), ""), nullptr, 16);
scan_callback_.advertisement_found_cb(id, adv_data);
}
@@ -19,7 +19,7 @@
#include <sdbus-c++/StandardInterfaces.h>
#include "absl/strings/string_view.h"
#include "internal/platform/implementation/ble_v2.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/linux/bluetooth_devices.h"
#include "internal/platform/implementation/linux/bluez.h"
#include "internal/platform/implementation/linux/generated/dbus/bluez/advertisement_monitor_server.h"
@@ -38,15 +38,15 @@ class AdvertisementMonitor final
AdvertisementMonitor& operator=(AdvertisementMonitor&&) = delete;
AdvertisementMonitor(sdbus::IConnection& system_bus, Uuid service_uuid,
api::ble_v2::TxPowerLevel tx_power_level,
api::ble::TxPowerLevel tx_power_level,
absl::string_view type,
std::shared_ptr<BluetoothDevices> devices,
api::ble_v2::BleMedium::ScanCallback scan_callback);
api::ble::BleMedium::ScanCallback scan_callback);
AdvertisementMonitor(sdbus::IConnection& system_bus, Uuid service_uuid,
api::ble_v2::TxPowerLevel tx_power_level,
api::ble::TxPowerLevel tx_power_level,
absl::string_view type,
std::shared_ptr<BluetoothDevices> devices,
api::ble_v2::BleMedium::ScanningCallback scan_callback);
api::ble::BleMedium::ScanningCallback scan_callback);
~AdvertisementMonitor() { unregisterAdaptor(); }
private:
@@ -83,12 +83,12 @@ class AdvertisementMonitor final
};
std::shared_ptr<BluetoothDevices> devices_;
api::ble_v2::BleMedium::ScanCallback scan_callback_;
api::ble::BleMedium::ScanCallback scan_callback_;
absl::AnyInvocable<void(absl::Status)> start_scanning_result_callback_;
std::string type_;
Uuid service_uuid_;
api::ble_v2::TxPowerLevel tx_power_level_;
api::ble::TxPowerLevel tx_power_level_;
};
} // namespace bluez
} // namespace linux
@@ -17,7 +17,7 @@
#include <sdbus-c++/Types.h>
#include "internal/platform/byte_array.h"
#include "internal/platform/implementation/ble_v2.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/linux/bluez_gatt_characteristic_server.h"
#include "internal/platform/logging.h"
@@ -173,8 +173,8 @@ void GattCharacteristicServer::WriteValue(
void GattCharacteristicServer::StartNotify() {
if ((characteristic_.property |
api::ble_v2::GattCharacteristic::Property::kNotify) ==
api::ble_v2::GattCharacteristic::Property::kNotify) {
api::ble::GattCharacteristic::Property::kNotify) ==
api::ble::GattCharacteristic::Property::kNotify) {
if (notify_sessions_.fetch_add(1) == 0) {
if (server_cb_->characteristic_subscription_cb != nullptr) {
server_cb_->characteristic_subscription_cb(characteristic_);
@@ -188,8 +188,8 @@ void GattCharacteristicServer::StartNotify() {
void GattCharacteristicServer::StopNotify() {
if ((characteristic_.property |
api::ble_v2::GattCharacteristic::Property::kNotify) ==
api::ble_v2::GattCharacteristic::Property::kNotify) {
api::ble::GattCharacteristic::Property::kNotify) ==
api::ble::GattCharacteristic::Property::kNotify) {
if (notify_sessions_.fetch_sub(0) == 1) {
if (server_cb_->characteristic_unsubscription_cb != nullptr) {
server_cb_->characteristic_unsubscription_cb(characteristic_);
@@ -206,31 +206,31 @@ std::vector<std::string> GattCharacteristicServer::Flags() {
std::vector<std::string> flags;
if ((characteristic.permission &
api::ble_v2::GattCharacteristic::Permission::kRead) ==
api::ble_v2::GattCharacteristic::Permission::kRead ||
api::ble::GattCharacteristic::Permission::kRead) ==
api::ble::GattCharacteristic::Permission::kRead ||
(characteristic.property &
api::ble_v2::GattCharacteristic::Property::kRead) ==
api::ble_v2::GattCharacteristic::Property::kRead)
api::ble::GattCharacteristic::Property::kRead) ==
api::ble::GattCharacteristic::Property::kRead)
flags.push_back("read");
if ((characteristic.permission &
api::ble_v2::GattCharacteristic::Permission::kWrite) ==
api::ble_v2::GattCharacteristic::Permission::kWrite ||
api::ble::GattCharacteristic::Permission::kWrite) ==
api::ble::GattCharacteristic::Permission::kWrite ||
(characteristic.property &
api::ble_v2::GattCharacteristic::Property::kWrite) ==
api::ble_v2::GattCharacteristic::Property::kWrite) {
api::ble::GattCharacteristic::Property::kWrite) ==
api::ble::GattCharacteristic::Property::kWrite) {
flags.push_back("write");
flags.push_back("write-without-response");
}
if ((characteristic.property &
api::ble_v2::GattCharacteristic::Property::kIndicate) ==
api::ble_v2::GattCharacteristic::Property::kIndicate)
api::ble::GattCharacteristic::Property::kIndicate) ==
api::ble::GattCharacteristic::Property::kIndicate)
flags.push_back("indicate");
if ((characteristic.property &
api::ble_v2::GattCharacteristic::Property::kNotify) ==
api::ble_v2::GattCharacteristic::Property::kNotify)
api::ble::GattCharacteristic::Property::kNotify) ==
api::ble::GattCharacteristic::Property::kNotify)
flags.push_back("notify");
return flags;
@@ -29,7 +29,7 @@
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "internal/platform/implementation/ble_v2.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/linux/bluetooth_devices.h"
#include "internal/platform/implementation/linux/bluez.h"
#include "internal/platform/implementation/linux/generated/dbus/bluez/gatt_characteristic_server.h"
@@ -52,8 +52,8 @@ class GattCharacteristicServer final
GattCharacteristicServer(
sdbus::IConnection &system_bus,
const sdbus::ObjectPath &service_object_path, size_t num,
const api::ble_v2::GattCharacteristic &characteristic,
std::shared_ptr<api::ble_v2::ServerGattConnectionCallback> server_cb,
const api::ble::GattCharacteristic &characteristic,
std::shared_ptr<api::ble::ServerGattConnectionCallback> server_cb,
std::shared_ptr<BluetoothDevices> devices)
: AdaptorInterfaces(system_bus, bluez::gatt_characteristic_path(
service_object_path, num)),
@@ -103,8 +103,8 @@ class GattCharacteristicServer final
}
std::shared_ptr<BluetoothDevices> devices_;
std::shared_ptr<api::ble_v2::ServerGattConnectionCallback> server_cb_;
api::ble_v2::GattCharacteristic characteristic_;
std::shared_ptr<api::ble::ServerGattConnectionCallback> server_cb_;
api::ble::GattCharacteristic characteristic_;
// Set by `GattServer::UpdateCharacteristic()`
absl::Mutex static_value_mutex_;
@@ -14,7 +14,7 @@
#include "internal/platform/implementation/linux/bluez_gatt_service_server.h"
#include "absl/synchronization/mutex.h"
#include "internal/platform/implementation/ble_v2.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/linux/bluez_gatt_characteristic_server.h"
#include "internal/platform/implementation/linux/generated/dbus/bluez/gatt_characteristic_server.h"
#include "internal/platform/uuid.h"
@@ -24,10 +24,10 @@ namespace linux {
namespace bluez {
bool GattServiceServer::AddCharacteristic(
const Uuid &service_uuid, const Uuid &characteristic_uuid,
api::ble_v2::GattCharacteristic::Permission permission,
api::ble_v2::GattCharacteristic::Property property) {
api::ble::GattCharacteristic::Permission permission,
api::ble::GattCharacteristic::Property property) {
absl::MutexLock lock(&characterstics_mutex_);
api::ble_v2::GattCharacteristic characteristic{
api::ble::GattCharacteristic characteristic{
characteristic_uuid, service_uuid, permission, property};
auto count = characteristics_.size();
std::shared_ptr<GattCharacteristicServer> chr =
@@ -23,7 +23,7 @@
#include "absl/container/flat_hash_map.h"
#include "absl/strings/string_view.h"
#include "internal/platform/implementation/ble_v2.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/linux/bluez.h"
#include "internal/platform/implementation/linux/bluez_gatt_characteristic_server.h"
#include "internal/platform/implementation/linux/generated/dbus/bluez/gatt_characteristic_server.h"
@@ -46,7 +46,7 @@ class GattServiceServer final
GattServiceServer(
sdbus::IConnection &system_bus, size_t num, const Uuid &service_uuid,
std::shared_ptr<api::ble_v2::ServerGattConnectionCallback> server_cb,
std::shared_ptr<api::ble::ServerGattConnectionCallback> server_cb,
std::shared_ptr<BluetoothDevices> devices)
: AdaptorInterfaces(system_bus, bluez::gatt_service_path(num)),
devices_(std::move(devices)),
@@ -80,8 +80,8 @@ class GattServiceServer final
bool AddCharacteristic(const Uuid &service_uuid,
const Uuid &characteristic_uuid,
api::ble_v2::GattCharacteristic::Permission permission,
api::ble_v2::GattCharacteristic::Property property)
api::ble::GattCharacteristic::Permission permission,
api::ble::GattCharacteristic::Property property)
ABSL_LOCKS_EXCLUDED(characterstics_mutex_);
std::shared_ptr<GattCharacteristicServer> GetCharacteristic(const Uuid &uuid)
ABSL_LOCKS_EXCLUDED(characterstics_mutex_);
@@ -98,7 +98,7 @@ class GattServiceServer final
characteristics_ ABSL_GUARDED_BY(characterstics_mutex_);
std::shared_ptr<BluetoothDevices> devices_;
std::shared_ptr<api::ble_v2::ServerGattConnectionCallback> server_cb_;
std::shared_ptr<api::ble::ServerGattConnectionCallback> server_cb_;
const std::string uuid_;
const bool primary_;
@@ -14,7 +14,7 @@
#include <vector>
#include "internal/platform/implementation/ble_v2.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/linux/bluez.h"
#include "internal/platform/implementation/linux/bluez_le_advertisement.h"
#include "internal/platform/logging.h"
@@ -33,8 +33,8 @@ namespace bluez {
}
LEAdvertisement::LEAdvertisement(
sdbus::IConnection& system_bus, sdbus::ObjectPath path,
const api::ble_v2::BleAdvertisementData& advertising_data,
api::ble_v2::AdvertiseParameters advertise_set_parameters)
const api::ble::BleAdvertisementData& advertising_data,
api::ble::AdvertiseParameters advertise_set_parameters)
: AdaptorInterfaces(system_bus, std::move(path)),
is_extended_advertisement_(advertising_data.is_extended_advertisement),
advertise_set_parameters_(advertise_set_parameters) {
@@ -21,7 +21,7 @@
#include <sdbus-c++/StandardInterfaces.h>
#include <sdbus-c++/Types.h>
#include "internal/platform/implementation/ble_v2.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/implementation/linux/bluetooth_adapter.h"
#include "internal/platform/implementation/linux/bluez.h"
#include "internal/platform/implementation/linux/generated/dbus/bluez/le_advertisement_manager_client.h"
@@ -41,13 +41,13 @@ class LEAdvertisement final
LEAdvertisement& operator=(LEAdvertisement&&) = delete;
LEAdvertisement(sdbus::IConnection& system_bus, sdbus::ObjectPath path,
const api::ble_v2::BleAdvertisementData& advertising_data,
api::ble_v2::AdvertiseParameters advertise_set_parameters);
const api::ble::BleAdvertisementData& advertising_data,
api::ble::AdvertiseParameters advertise_set_parameters);
static std::unique_ptr<LEAdvertisement> CreateLEAdvertisement(
sdbus::IConnection& system_bus,
const api::ble_v2::BleAdvertisementData& advertising_data,
api::ble_v2::AdvertiseParameters advertising_parameters) {
const api::ble::BleAdvertisementData& advertising_data,
api::ble::AdvertiseParameters advertising_parameters) {
static std::atomic<size_t> adv_count = 0;
auto object_path = bluez::ble_advertisement_path(adv_count++);
return std::make_unique<LEAdvertisement>(
@@ -92,7 +92,7 @@ class LEAdvertisement final
bool is_extended_advertisement_;
std::vector<std::string> service_uuids_;
std::map<std::string, sdbus::Variant> service_data_;
api::ble_v2::AdvertiseParameters advertise_set_parameters_;
api::ble::AdvertiseParameters advertise_set_parameters_;
};
class LEAdvertisementManager final
@@ -56,7 +56,7 @@
#include "internal/platform/implementation/wifi_lan.h"
#include "internal/platform/payload_id.h"
#include "scheduled_executor.h"
#include "wifi_direct.h"
// #include "wifi_direct.h"
#include "wifi_hotspot.h"
namespace nearby {
@@ -158,15 +158,21 @@ ImplementationPlatform::CreateConditionVariable(api::Mutex *mutex) {
return std::make_unique<linux::ConditionVariable>(mutex);
}
std::unique_ptr<AppLifecycleMonitor>
ImplementationPlatform::CreateAppLifecycleMonitor(
std::function<void(AppLifecycleMonitor::AppLifecycleState)>
state_updated_callback) {
return nullptr;
}
std::unique_ptr<api::InputFile> ImplementationPlatform::CreateInputFile(
PayloadId id, std::int64_t total_size) {
PayloadId id) {
auto path = GetDownloadPath(std::to_string(id));
return nearby::shared::IOFile::CreateInputFile(path, total_size);
return nearby::shared::IOFile::CreateInputFile(path);
}
std::unique_ptr<InputFile> ImplementationPlatform::CreateInputFile(
const std::string &file_path, size_t size) {
return nearby::shared::IOFile::CreateInputFile(file_path, size);
const std::string &file_path) {
return nearby::shared::IOFile::CreateInputFile(file_path);
}
std::unique_ptr<OutputFile> ImplementationPlatform::CreateOutputFile(
@@ -240,15 +246,8 @@ ImplementationPlatform::CreateBluetoothClassicMedium(
dynamic_cast<linux::BluetoothAdapter &>(adapter));
}
std::unique_ptr<BleMedium> ImplementationPlatform::CreateBleMedium(
std::unique_ptr<api::ble::BleMedium> ImplementationPlatform::CreateBleMedium(
BluetoothAdapter &adapter) {
return nullptr;
}
std::unique_ptr<api::ble_v2::BleMedium>
ImplementationPlatform::CreateBleV2Medium(api::BluetoothAdapter &adapter) {
// return nullptr;
// TODO: Enable BLEv2 once BlueZ support is added.
return std::make_unique<linux::BleV2Medium>(
dynamic_cast<linux::BluetoothAdapter &>(adapter));
}
@@ -329,17 +328,17 @@ ImplementationPlatform::CreateWifiHotspotMedium() {
std::unique_ptr<api::WifiDirectMedium>
ImplementationPlatform::CreateWifiDirectMedium() {
return nullptr;
auto nm =
std::make_shared<linux::networkmanager::NetworkManager>(linux::getSystemBusConnection());
auto wifiMedium = createWifiMedium(nm);
if (wifiMedium == nullptr) {
LOG(ERROR) << __func__ << ": Could not create a WiFi medium";
return nullptr;
}
return std::make_unique<linux::NetworkManagerWifiDirectMedium>(
nm, std::move(wifiMedium));
// auto nm =
// std::make_shared<linux::networkmanager::NetworkManager>(linux::getSystemBusConnection());
// auto wifiMedium = createWifiMedium(nm);
//
// if (wifiMedium == nullptr) {
// LOG(ERROR) << __func__ << ": Could not create a WiFi medium";
// return nullptr;
// }
//
// return std::make_unique<linux::NetworkManagerWifiDirectMedium>(
// nm, std::move(wifiMedium));
}
std::unique_ptr<api::Timer> ImplementationPlatform::CreateTimer() {
@@ -51,7 +51,7 @@ Exception InputStream::Close() {
return {};
}
Exception OutputStream::Write(const ByteArray &data) {
Exception OutputStream::Write(absl::string_view data) {
if (!fd_.isValid()) return Exception{Exception::kIo};
size_t written = 0;
@@ -40,7 +40,7 @@ class OutputStream : public nearby::OutputStream {
public:
explicit OutputStream(sdbus::UnixFd fd) : fd_(std::move(fd)){};
Exception Write(const ByteArray &data) override;
Exception Write(absl::string_view data) override;
Exception Flush() override;
Exception Close() override;
@@ -17,6 +17,8 @@
#include "internal/platform/implementation/system_clock.h"
#include "absl/time/clock.h"
namespace nearby {
// Initialize global system state.
@@ -270,18 +270,14 @@ bool NetworkManagerWifiHotspotMedium::StopWifiHotspot() {
}
bool NetworkManagerWifiHotspotMedium::ConnectWifiHotspot(
HotspotCredentials *hotspot_credentials) {
if (hotspot_credentials == nullptr) {
LOG(ERROR) << __func__ << ": hotspot_credentials cannot be null";
return false;
}
const HotspotCredentials& hotspot_credentials) {
auto ssid = hotspot_credentials->GetSSID();
auto password = hotspot_credentials->GetPassword();
auto ssid = hotspot_credentials.GetSSID();
auto password = hotspot_credentials.GetPassword();
return wireless_device_->ConnectToNetwork(ssid, password,
api::WifiAuthType::kWpaPsk) ==
api::WifiConnectionStatus::kConnected;
NetworkManagerWifiMedium::WifiAuthType::kWpaPsk) ==
NetworkManagerWifiMedium::WifiConnectionStatus::kConnected;
}
bool NetworkManagerWifiHotspotMedium::DisconnectWifiHotspot() {
@@ -40,16 +40,23 @@ class NetworkManagerWifiHotspotMedium : public api::WifiHotspotMedium {
network_manager_(std::move(network_manager)) {}
bool IsInterfaceValid() const override { return true; }
std::unique_ptr<api::WifiHotspotSocket> ConnectToService(
virtual std::unique_ptr<api::WifiHotspotSocket> ConnectToService(
const ServiceAddress& service_address,
CancellationFlag* cancellation_flag) {
return ConnectToService(
std::string(service_address.address.begin(), service_address.address.end())
, service_address.port, cancellation_flag) ;
};
std::unique_ptr<api::WifiHotspotSocket> ConnectToService(
absl::string_view ip_address, int port,
CancellationFlag *cancellation_flag) override;
CancellationFlag *cancellation_flag);
std::unique_ptr<api::WifiHotspotServerSocket> ListenForService(
int port) override;
bool StartWifiHotspot(HotspotCredentials *hotspot_credentials) override;
bool StopWifiHotspot() override;
bool ConnectWifiHotspot(HotspotCredentials *hotspot_credentials) override;
bool ConnectWifiHotspot(const HotspotCredentials& hotspot_credentials) override;
bool DisconnectWifiHotspot() override;
absl::optional<std::pair<std::int32_t, std::int32_t>> GetDynamicPortRange()
@@ -12,13 +12,17 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include <arpa/inet.h>
#include <netinet/in.h>
#include <poll.h>
#include <sys/socket.h>
#include <cstring>
#include "internal/platform/implementation/linux/wifi_hotspot_server_socket.h"
#include "internal/platform/implementation/linux/wifi_hotspot_socket.h"
#include "internal/platform/implementation/linux/wifi_medium.h"
#include "internal/platform/service_address.h"
#include "internal/platform/wifi_credential.h"
namespace nearby {
namespace linux {
@@ -110,5 +114,50 @@ Exception NetworkManagerWifiHotspotServerSocket::Close() {
return {Exception::kSuccess};
}
void NetworkManagerWifiHotspotServerSocket::PopulateHotspotCredentials(
HotspotCredentials& hotspot_credentials) {
// Get IPv4 addresses from the active hotspot connection
auto ip4addresses = active_conn_->GetIP4Addresses();
if (ip4addresses.empty()) {
LOG(ERROR) << __func__
<< ": Could not find any IPv4 addresses for active connection "
<< active_conn_->getObjectPath();
return;
}
// Get the server socket port
uint16_t port = GetPort();
if (port == 0) {
LOG(ERROR) << __func__ << ": Invalid port number";
return;
}
std::vector<ServiceAddress> service_addresses;
// Convert each IP address to binary format and create ServiceAddress
for (const auto& ip_str : ip4addresses) {
struct in_addr addr;
if (inet_pton(AF_INET, ip_str.c_str(), &addr) != 1) {
LOG(ERROR) << __func__ << ": Invalid IPv4 address: " << ip_str;
continue;
}
// Convert to vector of chars in network byte order
std::vector<char> addr_bytes(4);
std::memcpy(addr_bytes.data(), &addr.s_addr, 4);
service_addresses.push_back(
ServiceAddress{.address = std::move(addr_bytes), .port = port});
}
if (service_addresses.empty()) {
LOG(ERROR) << __func__ << ": No valid IPv4 addresses found";
return;
}
// Set the address candidates in the credentials
hotspot_credentials.SetAddressCandidates(std::move(service_addresses));
}
} // namespace linux
} // namespace nearby
@@ -36,11 +36,14 @@ class NetworkManagerWifiHotspotServerSocket
network_manager_(std::move(network_manager)),
closed_(false) {}
std::string GetIPAddress() const override;
std::string GetIPAddress() const;
int GetPort() const override;
std::unique_ptr<api::WifiHotspotSocket> Accept() override;
Exception Close() override;
void PopulateHotspotCredentials(
HotspotCredentials& hotspot_credentials) override;
private:
sdbus::UnixFd fd_;
std::unique_ptr<networkmanager::ActiveConnection> active_conn_;
@@ -264,9 +264,87 @@ std::unique_ptr<api::WifiLanServerSocket> WifiLanMedium::ListenForService(
network_manager_);
}
absl::optional<std::pair<std::int32_t, std::int32_t>> GetDynamicPortRange() {
return absl::nullopt;
namespace {
bool IsIPv4LinkLocal(const std::string& ip_address) {
struct in_addr addr;
if (inet_pton(AF_INET, ip_address.c_str(), &addr) != 1) {
return false;
}
// Link-local range: 169.254.0.0/16
uint32_t ip = ntohl(addr.s_addr);
return (ip & 0xFFFF0000) == 0xA9FE0000;
}
} // namespace
api::UpgradeAddressInfo WifiLanMedium::GetUpgradeAddressCandidates(
const api::WifiLanServerSocket& server_socket) {
api::UpgradeAddressInfo result;
uint16_t port = server_socket.GetPort();
std::vector<ServiceAddress> ipv4_addresses;
std::vector<sdbus::ObjectPath> connection_paths;
try {
connection_paths = network_manager_->ActiveConnections();
} catch (const sdbus::Error& e) {
DBUS_LOG_PROPERTY_GET_ERROR(network_manager_, "ActiveConnections", e);
return result;
}
for (auto& path : connection_paths) {
auto active_connection =
std::make_unique<networkmanager::ActiveConnection>(system_bus_, path);
std::string conn_type;
try {
conn_type = active_connection->Type();
} catch (const sdbus::Error& e) {
DBUS_LOG_PROPERTY_GET_ERROR(active_connection, "Type", e);
continue;
}
// Only use WiFi and Ethernet interfaces for upgrade
if (conn_type != "802-11-wireless" && conn_type != "802-3-ethernet") {
continue;
}
bool has_ipv4_address = false;
// TODO: Add IPv6 support when IP6Config interface is available
// Get IPv4 addresses
auto ip4addresses = active_connection->GetIP4Addresses();
for (const auto& ip_str : ip4addresses) {
// Filter out link-local addresses
if (IsIPv4LinkLocal(ip_str)) {
continue;
}
struct in_addr addr;
if (inet_pton(AF_INET, ip_str.c_str(), &addr) != 1) {
LOG(ERROR) << __func__ << ": Invalid IPv4 address: " << ip_str;
continue;
}
// Convert to vector of chars in network byte order
std::vector<char> addr_bytes(4);
std::memcpy(addr_bytes.data(), &addr.s_addr, 4);
ipv4_addresses.push_back(
ServiceAddress{.address = std::move(addr_bytes), .port = port});
has_ipv4_address = true;
}
if (has_ipv4_address) {
result.num_interfaces++;
}
}
// Append IPv4 addresses to the result
result.address_candidates.insert(result.address_candidates.end(),
ipv4_addresses.begin(),
ipv4_addresses.end());
return result;
};
} // namespace linux
} // namespace nearby
@@ -49,9 +49,16 @@ class WifiLanMedium : public api::WifiLanMedium {
return ConnectToService(remote_service_info.GetIPAddress(),
remote_service_info.GetPort(), cancellation_flag);
};
std::unique_ptr<api::WifiLanSocket> ConnectToService(
std::unique_ptr<api::WifiLanSocket> ConnectToService(
const ServiceAddress &sa,
CancellationFlag *cancellation_flag) override {
return ConnectToService(std::string(sa.address.begin(), sa.address.end()),
sa.port, cancellation_flag);
};
std::unique_ptr<api::WifiLanSocket> ConnectToService(
const std::string &ip_address, int port,
CancellationFlag *cancellation_flag) override;
CancellationFlag *cancellation_flag);
std::unique_ptr<api::WifiLanServerSocket> ListenForService(
int port = 0) override;
absl::optional<std::pair<std::int32_t, std::int32_t>> GetDynamicPortRange()
@@ -59,7 +66,13 @@ class WifiLanMedium : public api::WifiLanMedium {
return std::nullopt;
}
private:
// Returns the list of ip address candidates that can be used to connect to
// this device for bandwidth upgrade.
// `server_socket` is the socket that is currently listening for service
// requests.
api::UpgradeAddressInfo GetUpgradeAddressCandidates(
const api::WifiLanServerSocket& server_socket) override;
private:
std::shared_ptr<sdbus::IConnection> system_bus_;
std::shared_ptr<networkmanager::NetworkManager> network_manager_;
@@ -73,6 +86,7 @@ class WifiLanMedium : public api::WifiLanMedium {
absl::Mutex service_browsers_mutex_;
absl::flat_hash_map<std::string, std::unique_ptr<avahi::ServiceBrowser>>
service_browsers_ ABSL_GUARDED_BY(service_browsers_mutex_);
};
} // namespace linux
} // namespace nearby
@@ -80,24 +80,6 @@ api::WifiInformation &NetworkManagerWifiMedium::GetInformation() {
networkmanager::ObjectManager manager(system_bus_);
auto ip4config = manager.GetIp4Config(active_access_point->getObjectPath());
if (ip4config != nullptr) {
auto address_data = ip4config->AddressData();
if (!address_data.empty()) {
std::string address = address_data[0]["address"];
information_.ip_address_dot_decimal = address;
struct in_addr addr {};
inet_aton(address.c_str(), &addr);
char addr_bytes[4];
memcpy(addr_bytes, &addr.s_addr, sizeof(addr_bytes));
information_.ip_address_4_bytes = std::string(addr_bytes, 4);
}
} else {
LOG(ERROR) << __func__ << ": " << getObjectPath()
<< ": Could not find the Ip4Config object for "
<< active_access_point->getObjectPath();
}
} catch (const sdbus::Error &e) {
LOG(ERROR)
<< __func__ << ": " << getObjectPath() << ": Got error '" << e.getName()
@@ -124,20 +106,6 @@ void NetworkManagerWifiMedium::onPropertiesChanged(
}
}
bool NetworkManagerWifiMedium::Scan(
const api::WifiMedium::ScanResultCallback &scan_result_callback) {
// absl::MutexLock l(&scan_result_callback_lock_);
// scan_result_callback_ = scan_result_callback;
try {
RequestScan({});
} catch (const sdbus::Error &e) {
scan_result_callback_ = std::nullopt;
DBUS_LOG_METHOD_CALL_ERROR(&getProxy(), "RequestScan", e);
return false;
}
return false;
}
std::shared_ptr<NetworkManagerAccessPoint>
NetworkManagerWifiMedium::SearchBySSIDNoScan(
@@ -208,32 +176,32 @@ NetworkManagerWifiMedium::SearchBySSID(absl::string_view ssid,
}
static inline std::pair<std::optional<std::string>, std::string>
AuthAlgAndKeyMgmt(api::WifiAuthType auth_type) {
AuthAlgAndKeyMgmt(NetworkManagerWifiMedium::WifiAuthType auth_type) {
switch (auth_type) {
case api::WifiAuthType::kUnknown:
case api::WifiAuthType::kOpen:
case NetworkManagerWifiMedium::WifiAuthType::kUnknown:
case NetworkManagerWifiMedium::WifiAuthType::kOpen:
return {"open", "none"};
case api::WifiAuthType::kWpaPsk:
case NetworkManagerWifiMedium::WifiAuthType::kWpaPsk:
return {std::nullopt, "wpa-psk"};
case api::WifiAuthType::kWep:
case NetworkManagerWifiMedium::WifiAuthType::kWep:
return {"none", "wep"};
}
}
api::WifiConnectionStatus NetworkManagerWifiMedium::ConnectToNetwork(
NetworkManagerWifiMedium::WifiConnectionStatus NetworkManagerWifiMedium::ConnectToNetwork(
absl::string_view ssid, absl::string_view password,
api::WifiAuthType auth_type) {
NetworkManagerWifiMedium::WifiAuthType auth_type) {
auto ap = SearchBySSID(ssid);
if (ap == nullptr) {
LOG(ERROR) << __func__ << ": " << getObjectPath()
<< ": Couldn't find SSID " << ssid;
return api::WifiConnectionStatus::kConnectionFailure;
return NetworkManagerWifiMedium::WifiConnectionStatus::kConnectionFailure;
}
auto connection_id = NewUuidStr();
if (!connection_id.has_value()) {
LOG(ERROR) << __func__ << ": could not generate a connection UUID";
return api::WifiConnectionStatus::kUnknown;
return NetworkManagerWifiMedium::WifiConnectionStatus::kUnknown;
}
auto [auth_alg, key_mgmt] = AuthAlgAndKeyMgmt(auth_type);
@@ -273,7 +241,7 @@ api::WifiConnectionStatus NetworkManagerWifiMedium::ConnectToNetwork(
active_conn_path = std::move(acp);
} catch (const sdbus::Error &e) {
DBUS_LOG_METHOD_CALL_ERROR(this, "AddAndActivateConnection2", e);
return api::WifiConnectionStatus::kUnknown;
return NetworkManagerWifiMedium::WifiConnectionStatus::kUnknown;
}
LOG(INFO) << __func__ << ": " << getObjectPath()
@@ -287,7 +255,7 @@ api::WifiConnectionStatus NetworkManagerWifiMedium::ConnectToNetwork(
<< ": timed out while waiting for connection " << active_conn_path
<< " to be activated, last NMActiveConnectionStateReason: "
<< reason->ToString();
return api::WifiConnectionStatus::kUnknown;
return NetworkManagerWifiMedium::WifiConnectionStatus::kUnknown;
}
if (reason.has_value()) {
@@ -301,27 +269,13 @@ api::WifiConnectionStatus NetworkManagerWifiMedium::ConnectToNetwork(
reason->value ==
networkmanager::ActiveConnection::ActiveConnectionStateReason::
kStateReasonLoginFailed)
return api::WifiConnectionStatus::kAuthFailure;
return NetworkManagerWifiMedium::WifiConnectionStatus::kAuthFailure;
}
LOG(INFO) << __func__ << ": Activated connection " << connection_path;
return api::WifiConnectionStatus::kConnected;
return NetworkManagerWifiMedium::WifiConnectionStatus::kConnected;
}
bool NetworkManagerWifiMedium::VerifyInternetConnectivity() {
try {
std::uint32_t connectivity = network_manager_->CheckConnectivity();
return connectivity == 4; // NM_CONNECTIVITY_FULL
} catch (const sdbus::Error &e) {
DBUS_LOG_METHOD_CALL_ERROR(network_manager_, "CheckConnectivity", e);
return false;
}
}
std::string NetworkManagerWifiMedium::GetIpAddress() {
GetInformation();
return information_.ip_address_dot_decimal;
}
std::unique_ptr<networkmanager::ActiveConnection>
NetworkManagerWifiMedium::GetActiveConnection() {
@@ -42,8 +42,30 @@ class NetworkManagerWifiMedium
public sdbus::ProxyInterfaces<
org::freedesktop::NetworkManager::Device::Wireless_proxy,
sdbus::Properties_proxy> {
public:
NetworkManagerWifiMedium(const NetworkManagerWifiMedium &) = delete;
// Possible authentication types for a WiFi network.
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.
enum class WifiConnectionStatus {
kUnknown = 0,
kConnected = 1,
kConnectionFailure = 2,
kAuthFailure = 3,
};
NetworkManagerWifiMedium(const NetworkManagerWifiMedium &) = delete;
NetworkManagerWifiMedium(NetworkManagerWifiMedium &&) = delete;
NetworkManagerWifiMedium &operator=(const NetworkManagerWifiMedium &) =
delete;
@@ -62,30 +84,18 @@ class NetworkManagerWifiMedium
~NetworkManagerWifiMedium() override { unregisterProxy(); }
class ScanResultCallback : public api::WifiMedium::ScanResultCallback {
public:
void OnScanResults(
const std::vector<api::WifiScanResult> &scan_results) override {
// TODO: Add implementation at some point
}
};
bool IsInterfaceValid() const override { return true; };
api::WifiCapability &GetCapability() override;
api::WifiInformation &GetInformation() override;
bool Scan(
const api::WifiMedium::ScanResultCallback &scan_result_callback) override;
std::shared_ptr<NetworkManagerAccessPoint> SearchBySSID(
absl::string_view ssid, absl::Duration scan_timeout = absl::Seconds(15))
ABSL_LOCKS_EXCLUDED(known_access_points_lock_);
api::WifiConnectionStatus ConnectToNetwork(
WifiConnectionStatus ConnectToNetwork(
absl::string_view ssid, absl::string_view password,
api::WifiAuthType auth_type) override;
bool VerifyInternetConnectivity() override;
std::string GetIpAddress() override;
WifiAuthType auth_type);
std::unique_ptr<networkmanager::ActiveConnection> GetActiveConnection();
@@ -125,10 +135,6 @@ class NetworkManagerWifiMedium
std::shared_ptr<NetworkManagerAccessPoint>>
known_access_points_ ABSL_GUARDED_BY(known_access_points_lock_);
absl::Mutex scan_result_callback_lock_;
std::optional<
std::reference_wrapper<const api::WifiMedium::ScanResultCallback>>
scan_result_callback_ ABSL_GUARDED_BY(scan_result_callback_lock_);
absl::Mutex last_scan_lock_;
std::int64_t last_scan_ ABSL_GUARDED_BY(last_scan_lock_);