Removed platform types dependency from windows platform codes

PiperOrigin-RevId: 676447748
This commit is contained in:
Guogang Li
2024-09-19 09:37:29 -07:00
committed by Copybara-Service
parent a9e753e1e1
commit 47f2dfec28
48 changed files with 1972 additions and 2133 deletions
@@ -48,7 +48,6 @@ cc_library(
"//internal/base:files",
"//internal/flags:nearby_flags",
"//internal/platform:base",
"//internal/platform:types",
"//internal/platform:uuid",
"//internal/platform/implementation:types",
"//internal/platform/implementation/windows/generated:types",
@@ -109,11 +108,11 @@ cc_library(
"//internal/flags:nearby_flags",
"//internal/platform:base",
"//internal/platform:comm",
"//internal/platform:types",
"//internal/platform:uuid",
"//internal/platform/flags:platform_flags",
"//internal/platform/implementation:account_manager",
"//internal/platform/implementation:comm",
"//internal/platform/implementation/shared:count_down_latch",
"//internal/platform/implementation/windows/generated:types",
"@com_google_absl//absl/base:core_headers",
"@com_google_absl//absl/container:flat_hash_map",
@@ -216,8 +215,7 @@ cc_library(
"//internal/flags:nearby_flags",
"//internal/platform:base",
"//internal/platform:cancellation_flag",
"//internal/platform:comm",
"//internal/platform:types",
"//internal/platform:logging",
"//internal/platform:uuid",
"//internal/platform/flags:platform_flags",
"//internal/platform/implementation:comm",
@@ -297,7 +295,7 @@ cc_test(
":types",
":windows",
"//internal/platform:base",
"//internal/platform:types",
"//internal/platform:logging",
"//internal/platform/implementation:comm",
"//internal/platform/implementation:platform",
"//internal/platform/implementation:types",
@@ -103,16 +103,15 @@ std::string GattCommunicationStatusToString(GattCommunicationStatus status) {
BleGattClient::BleGattClient(BluetoothLEDevice ble_device)
: ble_device_(ble_device) {
if (ble_device_ == nullptr) {
NEARBY_LOGS(WARNING) << __func__ << ": ble_device is null.";
LOG(WARNING) << __func__ << ": ble_device is null.";
} else {
NEARBY_LOGS(INFO) << __func__ << ": GATT client is created, address: "
<< uint64_to_mac_address_string(
ble_device_.BluetoothAddress());
LOG(INFO) << __func__ << ": GATT client is created, address: "
<< uint64_to_mac_address_string(ble_device_.BluetoothAddress());
}
}
BleGattClient::~BleGattClient() {
NEARBY_LOGS(INFO) << __func__ << ": GATT client is released.";
LOG(INFO) << __func__ << ": GATT client is released.";
Disconnect();
}
@@ -124,21 +123,21 @@ bool BleGattClient::DiscoverServiceAndCharacteristics(
kEnableBleV2Gatt)) {
BluetoothAdapter bluetooth_adapter;
if (bluetooth_adapter.IsExtendedAdvertisingSupported()) {
NEARBY_LOGS(WARNING) << __func__ << ": GATT is disabled.";
LOG(WARNING) << __func__ << ": GATT is disabled.";
return false;
}
if (!bluetooth_adapter.IsCentralRoleSupported()) {
NEARBY_LOGS(ERROR) << __func__
<< ": Bluetooth Hardware does not support Central "
"Role, which is required to start GATT client.";
LOG(ERROR) << __func__
<< ": Bluetooth Hardware does not support Central "
"Role, which is required to start GATT client.";
return false;
}
if (!NearbyFlags::GetInstance().GetBoolFlag(
platform::config_package_nearby::nearby_platform_feature::
kEnableBleV2GattOnNonExtendedDevice)) {
NEARBY_LOGS(WARNING) << __func__ << ": GATT is disabled.";
LOG(WARNING) << __func__ << ": GATT is disabled.";
return false;
}
}
@@ -148,13 +147,12 @@ bool BleGattClient::DiscoverServiceAndCharacteristics(
absl::StrAppend(out, std::string(uuid));
});
NEARBY_VLOG(1) << __func__
<< ": Discover service_uuid=" << std::string(service_uuid)
<< " with characteristic_uuids=" << flat_characteristics;
VLOG(1) << __func__ << ": Discover service_uuid=" << std::string(service_uuid)
<< " with characteristic_uuids=" << flat_characteristics;
try {
if (ble_device_ == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": BLE device is disconnected.";
LOG(ERROR) << __func__ << ": BLE device is disconnected.";
return false;
}
@@ -168,23 +166,21 @@ bool BleGattClient::DiscoverServiceAndCharacteristics(
gatt_devices_services_result_ = get_gatt_services_async.GetResults();
break;
case winrt::Windows::Foundation::AsyncStatus::Started:
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to get GATT services due to timeout.";
LOG(ERROR) << __func__
<< ": Failed to get GATT services due to timeout.";
get_gatt_services_async.Cancel();
return false;
default:
NEARBY_LOGS(ERROR)
<< __func__
<< ": Failed to get GATT services due to unknown reasons.";
LOG(ERROR) << __func__
<< ": Failed to get GATT services due to unknown reasons.";
return false;
}
if (gatt_devices_services_result_.Status() !=
GattCommunicationStatus::Success) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to get gatt service with error: "
<< GattCommunicationStatusToString(
gatt_devices_services_result_.Status());
LOG(ERROR) << __func__ << ": Failed to get gatt service with error: "
<< GattCommunicationStatusToString(
gatt_devices_services_result_.Status());
gatt_devices_services_result_ = nullptr;
return false;
}
@@ -198,8 +194,8 @@ bool BleGattClient::DiscoverServiceAndCharacteristics(
winrt::to_string(winrt::to_hstring(service.Uuid())));
});
NEARBY_LOGS(INFO) << __func__ << ": Found GATT services=" << flat_services
<< " from BLE device.";
LOG(INFO) << __func__ << ": Found GATT services=" << flat_services
<< " from BLE device.";
// Needs to check each service to make sure it includes all characteristic
// uuids. Services may include duplicate service UUID, but each of them may
@@ -208,26 +204,25 @@ bool BleGattClient::DiscoverServiceAndCharacteristics(
winrt::guid uuid = service.Uuid();
std::string uuid_string = winrt::to_string(winrt::to_hstring(uuid));
NEARBY_VLOG(1) << __func__ << ": Found service UUID=" << uuid_string;
VLOG(1) << __func__ << ": Found service UUID=" << uuid_string;
if (!is_nearby_uuid_equal_to_winrt_guid(service_uuid, uuid)) {
NEARBY_LOGS(WARNING)
LOG(WARNING)
<< __func__
<< ": Service uuid not match, continue check other services.";
continue;
}
NEARBY_LOGS(INFO) << __func__
<< ": Found the discovery service UUID=" << uuid_string;
LOG(INFO) << __func__
<< ": Found the discovery service UUID=" << uuid_string;
// Try to check the characteristic uuids.
GattCharacteristicsResult gatt_characteristics_result =
service.GetCharacteristicsAsync(BluetoothCacheMode::Uncached).get();
if (gatt_characteristics_result.Status() !=
GattCommunicationStatus::Success) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to get characteristics with error: "
<< GattCommunicationStatusToString(
gatt_characteristics_result.Status());
LOG(ERROR) << __func__ << ": Failed to get characteristics with error: "
<< GattCommunicationStatusToString(
gatt_characteristics_result.Status());
continue;
}
@@ -238,8 +233,8 @@ bool BleGattClient::DiscoverServiceAndCharacteristics(
gatt_characteristic.Uuid())));
});
NEARBY_VLOG(1) << __func__
<< ": Found GATT characteristics=" << flat_characteristics;
VLOG(1) << __func__
<< ": Found GATT characteristics=" << flat_characteristics;
bool found_all = true;
@@ -257,8 +252,8 @@ bool BleGattClient::DiscoverServiceAndCharacteristics(
}
}
if (found == false) {
NEARBY_LOGS(WARNING) << __func__ << ": Cannot find characteristic: "
<< std::string(characteristic_uuid);
LOG(WARNING) << __func__ << ": Cannot find characteristic: "
<< std::string(characteristic_uuid);
found_all = false;
break;
}
@@ -269,21 +264,18 @@ bool BleGattClient::DiscoverServiceAndCharacteristics(
}
// found all characteristics.
NEARBY_VLOG(1) << __func__ << ": Found all characteristics.";
VLOG(1) << __func__ << ": Found all characteristics.";
return true;
}
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to find service and all characteristics.";
LOG(ERROR) << __func__
<< ": Failed to find service and all characteristics.";
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to get GATT services. exception: "
<< exception.what();
LOG(ERROR) << __func__ << ": Failed to get GATT services. exception: "
<< exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to get GATT services. WinRT exception: "
<< error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": Failed to get GATT services. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
}
return false;
@@ -293,16 +285,15 @@ absl::optional<api::ble_v2::GattCharacteristic>
BleGattClient::GetCharacteristic(const Uuid& service_uuid,
const Uuid& characteristic_uuid) {
absl::MutexLock lock(&mutex_);
NEARBY_VLOG(1) << __func__ << ": Stared to get characteristic UUID="
<< std::string(characteristic_uuid)
<< " in service UUID=" << std::string(service_uuid);
VLOG(1) << __func__ << ": Stared to get characteristic UUID="
<< std::string(characteristic_uuid)
<< " in service UUID=" << std::string(service_uuid);
try {
std::optional<GattCharacteristic> gatt_characteristic =
GetNativeCharacteristic(service_uuid, characteristic_uuid);
if (!gatt_characteristic.has_value()) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to get native GATT characteristic.";
LOG(ERROR) << __func__ << ": Failed to get native GATT characteristic.";
return absl::nullopt;
}
@@ -340,18 +331,17 @@ BleGattClient::GetCharacteristic(const Uuid& service_uuid,
native_characteristic_map_[result].native_characteristic =
gatt_characteristic;
NEARBY_VLOG(1) << __func__ << ": Return Characteristic. uuid="
<< std::string(characteristic_uuid);
VLOG(1) << __func__ << ": Return Characteristic. uuid="
<< std::string(characteristic_uuid);
return result;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to get GATT characteristic. exception: "
<< exception.what();
LOG(ERROR) << __func__ << ": Failed to get GATT characteristic. exception: "
<< exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR)
<< __func__ << ": Failed to get GATT characteristic. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__
<< ": Failed to get GATT characteristic. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
}
return absl::nullopt;
@@ -360,32 +350,31 @@ BleGattClient::GetCharacteristic(const Uuid& service_uuid,
absl::optional<std::string> BleGattClient::ReadCharacteristic(
const api::ble_v2::GattCharacteristic& characteristic) {
absl::MutexLock lock(&mutex_);
NEARBY_VLOG(1) << __func__ << ": Read characteristic="
<< std::string(characteristic.uuid);
VLOG(1) << __func__
<< ": Read characteristic=" << std::string(characteristic.uuid);
try {
std::optional<GattCharacteristic> gatt_characteristic =
GetNativeCharacteristic(characteristic.service_uuid,
characteristic.uuid);
if (!gatt_characteristic.has_value()) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to get native GATT characteristic.";
LOG(ERROR) << __func__ << ": Failed to get native GATT characteristic.";
return absl::nullopt;
}
GattReadResult result =
gatt_characteristic->ReadValueAsync(BluetoothCacheMode::Uncached).get();
if (result.Status() != GattCommunicationStatus::Success) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to read GATT characteristic with error: "
<< GattCommunicationStatusToString(result.Status());
LOG(ERROR) << __func__
<< ": Failed to read GATT characteristic with error: "
<< GattCommunicationStatusToString(result.Status());
return absl::nullopt;
}
IBuffer buffer = result.Value();
int size = buffer.Length();
if (size == 0) {
NEARBY_LOGS(WARNING) << __func__ << ": No characteristic value.";
LOG(WARNING) << __func__ << ": No characteristic value.";
return absl::nullopt;
}
@@ -396,18 +385,17 @@ absl::optional<std::string> BleGattClient::ReadCharacteristic(
data.push_back(static_cast<char>(data_reader.ReadByte()));
}
NEARBY_VLOG(1) << __func__
<< ": Got characteristic value length=" << data.size();
VLOG(1) << __func__ << ": Got characteristic value length=" << data.size();
return data;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to read GATT characteristic. exception: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Failed to read GATT characteristic. exception: "
<< exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR)
<< __func__ << ": Failed to read GATT characteristic. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__
<< ": Failed to read GATT characteristic. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
}
return absl::nullopt;
@@ -417,15 +405,14 @@ bool BleGattClient::WriteCharacteristic(
const api::ble_v2::GattCharacteristic& characteristic,
absl::string_view value, api::ble_v2::GattClient::WriteType write_type) {
absl::MutexLock lock(&mutex_);
NEARBY_VLOG(1) << __func__ << ": write characteristic: "
<< std::string(characteristic.uuid);
VLOG(1) << __func__
<< ": write characteristic: " << std::string(characteristic.uuid);
try {
std::optional<GattCharacteristic> gatt_characteristic =
native_characteristic_map_[characteristic].native_characteristic;
if (!gatt_characteristic.has_value()) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to get native GATT characteristic.";
LOG(ERROR) << __func__ << ": Failed to get native GATT characteristic.";
return false;
}
@@ -442,26 +429,25 @@ bool BleGattClient::WriteCharacteristic(
gatt_characteristic->WriteValueAsync(buffer, write_option).get();
if (status != GattCommunicationStatus::Success) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to write data to GATT characteristic: "
<< std::string(characteristic.uuid) << "with error: "
<< GattCommunicationStatusToString(status);
LOG(ERROR) << __func__
<< ": Failed to write data to GATT characteristic: "
<< std::string(characteristic.uuid)
<< "with error: " << GattCommunicationStatusToString(status);
return false;
} else {
NEARBY_VLOG(1) << __func__ << ": Write data to GATT characteristic: "
<< std::string(characteristic.uuid)
<< ", bytes count: " << value.size();
VLOG(1) << __func__ << ": Write data to GATT characteristic: "
<< std::string(characteristic.uuid)
<< ", bytes count: " << value.size();
return true;
}
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to write GATT characteristic. exception: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Failed to write GATT characteristic. exception: "
<< exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR)
<< __func__
<< ": Failed to write GATT characteristic. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__
<< ": Failed to write GATT characteristic. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
}
return false;
}
@@ -471,7 +457,7 @@ bool BleGattClient::SetCharacteristicSubscription(
absl::AnyInvocable<void(absl::string_view value)>
on_characteristic_changed_cb) {
absl::MutexLock lock(&mutex_);
NEARBY_VLOG(1) << __func__ << ": Started to set Characteristic Subscription.";
VLOG(1) << __func__ << ": Started to set Characteristic Subscription.";
GattClientCharacteristicConfigurationDescriptorValue gcccd_value =
GattClientCharacteristicConfigurationDescriptorValue::None;
if ((characteristic.property & Property::kNotify) != Property::kNone) {
@@ -481,9 +467,8 @@ bool BleGattClient::SetCharacteristicSubscription(
gcccd_value =
GattClientCharacteristicConfigurationDescriptorValue::Indicate;
} else {
NEARBY_LOGS(WARNING) << "Characeristic: "
<< std::string(characteristic.uuid)
<< " supports neither notifications nor indications.";
LOG(WARNING) << "Characeristic: " << std::string(characteristic.uuid)
<< " supports neither notifications nor indications.";
return false;
}
@@ -493,8 +478,7 @@ bool BleGattClient::SetCharacteristicSubscription(
native_characteristic_map_[characteristic].native_characteristic;
if (!gatt_characteristic.has_value()) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to get native GATT characteristic.";
LOG(ERROR) << __func__ << ": Failed to get native GATT characteristic.";
return false;
}
@@ -521,27 +505,23 @@ bool BleGattClient::SetCharacteristicSubscription(
});
if (!native_characteristic_map_[characteristic].notification_token) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to add value change handler.";
LOG(ERROR) << __func__ << ": Failed to add value change handler.";
return false;
}
} else if (native_characteristic_map_[characteristic].notification_token) {
gatt_characteristic->ValueChanged(std::exchange(
native_characteristic_map_[characteristic].notification_token, {}));
}
NEARBY_LOGS(ERROR) << __func__
<< ": Successfully set Characteristic Subscription.";
LOG(ERROR) << __func__ << ": Successfully set Characteristic Subscription.";
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to set Characteristic Subscription."
<< exception.what();
LOG(ERROR) << __func__ << ": Failed to set Characteristic Subscription."
<< exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to set Characteristic Subscription."
" WinRT exception: "
<< error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << __func__
<< ": Failed to set Characteristic Subscription."
" WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
}
return false;
}
@@ -549,37 +529,36 @@ bool BleGattClient::SetCharacteristicSubscription(
void BleGattClient::Disconnect() {
absl::MutexLock lock(&mutex_);
try {
NEARBY_VLOG(1) << __func__ << ": Disconnect is called.";
VLOG(1) << __func__ << ": Disconnect is called.";
if (ble_device_ != nullptr) {
ble_device_.Close();
ble_device_ = nullptr;
}
native_characteristic_map_.clear();
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to disconnect GATT device. exception: "
<< exception.what();
LOG(ERROR) << __func__ << ": Failed to disconnect GATT device. exception: "
<< exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR)
<< __func__ << ": Failed to disconnect GATT device. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__
<< ": Failed to disconnect GATT device. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
}
}
std::optional<GattCharacteristic> BleGattClient::GetNativeCharacteristic(
const Uuid& service_uuid, const Uuid& characteristic_uuid) {
NEARBY_VLOG(1) << __func__ << ": Stared to get native characteristic UUID="
<< std::string(characteristic_uuid)
<< " in service UUID=" << std::string(service_uuid);
VLOG(1) << __func__ << ": Stared to get native characteristic UUID="
<< std::string(characteristic_uuid)
<< " in service UUID=" << std::string(service_uuid);
try {
if (ble_device_ == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": BLE device is disconnected.";
LOG(ERROR) << __func__ << ": BLE device is disconnected.";
return absl::nullopt;
}
if (gatt_devices_services_result_ == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": No available GATT services.";
LOG(ERROR) << __func__ << ": No available GATT services.";
return absl::nullopt;
}
@@ -589,10 +568,10 @@ std::optional<GattCharacteristic> BleGattClient::GetNativeCharacteristic(
service.GetCharacteristicsAsync(BluetoothCacheMode::Cached).get();
if (gatt_characteristics_result.Status() !=
GattCommunicationStatus::Success) {
NEARBY_LOGS(ERROR)
<< __func__ << ": Failed to get characteristics with error: "
<< GattCommunicationStatusToString(
gatt_characteristics_result.Status());
LOG(ERROR) << __func__
<< ": Failed to get characteristics with error: "
<< GattCommunicationStatusToString(
gatt_characteristics_result.Status());
continue;
}
@@ -600,9 +579,8 @@ std::optional<GattCharacteristic> BleGattClient::GetNativeCharacteristic(
gatt_characteristics_result.Characteristics()) {
if (is_nearby_uuid_equal_to_winrt_guid(characteristic_uuid,
characteristic.Uuid())) {
NEARBY_VLOG(1) << __func__
<< ": Return native Characteristic. uuid="
<< std::string(characteristic_uuid);
VLOG(1) << __func__ << ": Return native Characteristic. uuid="
<< std::string(characteristic_uuid);
return characteristic;
}
@@ -610,13 +588,13 @@ std::optional<GattCharacteristic> BleGattClient::GetNativeCharacteristic(
}
}
NEARBY_LOGS(ERROR) << __func__ << ": Failed to get native characteristic.";
LOG(ERROR) << __func__ << ": Failed to get native characteristic.";
} catch (std::exception exception) {
NEARBY_LOGS(ERROR)
<< __func__ << ": Failed to get native GATT characteristic. exception: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Failed to get native GATT characteristic. exception: "
<< exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR)
LOG(ERROR)
<< __func__
<< ": Failed to get native GATT characteristic. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
@@ -628,8 +606,8 @@ std::optional<GattCharacteristic> BleGattClient::GetNativeCharacteristic(
bool BleGattClient::WriteCharacteristicConfigurationDescriptor(
GattCharacteristic& characteristic,
GattClientCharacteristicConfigurationDescriptorValue value) {
NEARBY_VLOG(1) << __func__
<< ": Stared to write characteristic configuration descriptor";
VLOG(1) << __func__
<< ": Stared to write characteristic configuration descriptor";
try {
GattCommunicationStatus status =
@@ -637,23 +615,23 @@ bool BleGattClient::WriteCharacteristicConfigurationDescriptor(
.WriteClientCharacteristicConfigurationDescriptorAsync(value)
.get();
if (status == GattCommunicationStatus::Success) {
NEARBY_VLOG(1) << __func__
<< ": Successfully write client characteristic "
"configuration descriptor";
VLOG(1) << __func__
<< ": Successfully write client characteristic "
"configuration descriptor";
return true;
}
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to write client characteristic "
"configuration descriptor with error: "
<< GattCommunicationStatusToString(status);
LOG(ERROR) << __func__
<< ": Failed to write client characteristic "
"configuration descriptor with error: "
<< GattCommunicationStatusToString(status);
} catch (std::exception exception) {
// This usually happens when a device reports that it support notify, but
// it actually doesn't.
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to write client characteristic "
"configuration descriptor";
LOG(ERROR) << __func__
<< ": Failed to write client characteristic "
"configuration descriptor";
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR)
LOG(ERROR)
<< __func__
<< ": Failed to write client characteristic configuration descriptor."
" WinRT exception: "
@@ -665,7 +643,7 @@ bool BleGattClient::WriteCharacteristicConfigurationDescriptor(
void BleGattClient::OnCharacteristicValueChanged(
const api::ble_v2::GattCharacteristic& characteristic,
GattValueChangedEventArgs args) {
NEARBY_VLOG(1) << __func__ << ": Gatt Characteristic value changed.";
VLOG(1) << __func__ << ": Gatt Characteristic value changed.";
IBuffer buffer = args.CharacteristicValue();
int size = buffer.Length();
DataReader data_reader = DataReader::FromBuffer(buffer);
@@ -674,8 +652,7 @@ void BleGattClient::OnCharacteristicValueChanged(
for (int i = 0; i < size; ++i) {
data.push_back(static_cast<char>(data_reader.ReadByte()));
}
NEARBY_VLOG(1) << __func__
<< ": Got characteristic value length= " << data.size();
VLOG(1) << __func__ << ": Got characteristic value length= " << data.size();
absl::AnyInvocable<void(absl::string_view value)>
on_characteristic_changed_cb;
@@ -684,8 +661,7 @@ void BleGattClient::OnCharacteristicValueChanged(
if (!native_characteristic_map_.contains(characteristic) ||
!native_characteristic_map_[characteristic]
.on_characteristic_changed_cb) {
NEARBY_LOGS(INFO) << __func__
<< ": No registered callback for characteristic.";
LOG(INFO) << __func__ << ": No registered callback for characteristic.";
return;
}
on_characteristic_changed_cb =
@@ -126,13 +126,12 @@ BleGattServer::CreateCharacteristic(
api::ble_v2::GattCharacteristic::Permission permission,
api::ble_v2::GattCharacteristic::Property property) {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__ << ": create characteristic, service_uuid: "
<< std::string(service_uuid) << ", characteristic_uuid: "
<< std::string(characteristic_uuid);
LOG(INFO) << __func__ << ": create characteristic, service_uuid: "
<< std::string(service_uuid)
<< ", characteristic_uuid: " << std::string(characteristic_uuid);
if (!service_uuid_.IsEmpty() && service_uuid_ != service_uuid) {
NEARBY_LOGS(ERROR) << __func__
<< ": Only support one GATT service for now.";
LOG(ERROR) << __func__ << ": Only support one GATT service for now.";
return absl::nullopt;
}
@@ -156,17 +155,17 @@ bool BleGattServer::UpdateCharacteristic(
const api::ble_v2::GattCharacteristic& characteristic,
const nearby::ByteArray& value) {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__ << ": update characteristic: "
<< std::string(characteristic.uuid);
LOG(INFO) << __func__
<< ": update characteristic: " << std::string(characteristic.uuid);
if (characteristic.service_uuid != service_uuid_) {
NEARBY_LOGS(ERROR) << __func__ << ": Cannot found the GATT service.";
LOG(ERROR) << __func__ << ": Cannot found the GATT service.";
return false;
}
for (auto& it : gatt_characteristic_datas_) {
if (it.gatt_characteristic.uuid == characteristic.uuid) {
NEARBY_VLOG(1) << __func__ << ": Found the characteristic to update.";
VLOG(1) << __func__ << ": Found the characteristic to update.";
it.data = value;
// If it is in running, notify the value changed.
@@ -178,8 +177,7 @@ bool BleGattServer::UpdateCharacteristic(
is_indicate_characteristic = true;
}
NEARBY_LOGS(INFO) << __func__
<< ": Notify characteristic value updated.";
LOG(INFO) << __func__ << ": Notify characteristic value updated.";
if (is_indicate_characteristic) {
NotifyValueChanged(it.gatt_characteristic);
}
@@ -189,7 +187,7 @@ bool BleGattServer::UpdateCharacteristic(
}
}
NEARBY_LOGS(ERROR) << __func__ << ": Failed to update the characteristic.";
LOG(ERROR) << __func__ << ": Failed to update the characteristic.";
return false;
}
@@ -199,8 +197,9 @@ absl::Status BleGattServer::NotifyCharacteristicChanged(
const ByteArray& new_value) {
absl::MutexLock lock(&mutex_);
// Currently, the method is not hooked up at platform layer.
NEARBY_VLOG(1) << __func__ << ": Notify characteristic="
<< std::string(characteristic.uuid) << " changed.";
VLOG(1) << __func__
<< ": Notify characteristic=" << std::string(characteristic.uuid)
<< " changed.";
return absl::OkStatus();
}
@@ -208,7 +207,7 @@ void BleGattServer::Stop() {
absl::AnyInvocable<void()> close_notifier = nullptr;
{
absl::MutexLock lock(&mutex_);
NEARBY_VLOG(1) << __func__ << ": Start to stop GATT server.";
VLOG(1) << __func__ << ": Start to stop GATT server.";
if (gatt_service_provider_ != nullptr) {
try {
if (is_advertising_) {
@@ -219,15 +218,15 @@ void BleGattServer::Stop() {
service_uuid_ = Uuid();
gatt_service_provider_ = nullptr;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
}
} else {
NEARBY_LOGS(WARNING) << __func__ << ": no GATT server is running.";
LOG(WARNING) << __func__ << ": no GATT server is running.";
}
close_notifier = std::move(close_notifier_);
}
@@ -240,28 +239,28 @@ void BleGattServer::Stop() {
bool BleGattServer::InitializeGattServer() {
try {
// Create and advertise GATT service.
NEARBY_VLOG(1) << __func__ << ": Create GATT service service_uuid="
<< std::string(service_uuid_);
VLOG(1) << __func__ << ": Create GATT service service_uuid="
<< std::string(service_uuid_);
if (adapter_ == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": Bluetooth adapter is absent.";
LOG(ERROR) << __func__ << ": Bluetooth adapter is absent.";
return false;
}
if (!adapter_->IsEnabled()) {
NEARBY_LOGS(ERROR) << __func__ << ": Bluetooth adapter is disabled.";
LOG(ERROR) << __func__ << ": Bluetooth adapter is disabled.";
return false;
}
if (!adapter_->IsLowEnergySupported()) {
NEARBY_LOGS(ERROR) << __func__
<< ": Bluetooth adapter does not support BLE, which "
"is needed to start GATT server.";
LOG(ERROR) << __func__
<< ": Bluetooth adapter does not support BLE, which "
"is needed to start GATT server.";
return false;
}
if (!adapter_->IsPeripheralRoleSupported()) {
NEARBY_LOGS(ERROR)
LOG(ERROR)
<< __func__
<< ": Bluetooth Hardware does not support Peripheral Role, which is "
"required to start GATT server.";
@@ -273,9 +272,8 @@ bool BleGattServer::InitializeGattServer() {
GattServiceProvider::CreateAsync(service_uuid).get();
if (service_provider_result.Error() != BluetoothError::Success) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to create GATT service. Error: "
<< static_cast<int>(service_provider_result.Error());
LOG(ERROR) << __func__ << ": Failed to create GATT service. Error: "
<< static_cast<int>(service_provider_result.Error());
return false;
}
@@ -284,7 +282,7 @@ bool BleGattServer::InitializeGattServer() {
service_provider_advertisement_changed_token_ =
gatt_service_provider_.AdvertisementStatusChanged(
{this, &BleGattServer::ServiceProvider_AdvertisementStatusChanged});
NEARBY_LOGS(INFO) << __func__ << ": GATT service created.";
LOG(INFO) << __func__ << ": GATT service created.";
// Create GATT characteristics.
for (auto& characteristic_data : gatt_characteristic_datas_) {
@@ -318,10 +316,11 @@ bool BleGattServer::InitializeGattServer() {
is_notify_supported = true;
}
NEARBY_VLOG(1) << __func__ << ": GATT characteristic properties: read="
<< is_read_supported << ",write=" << is_write_supported
<< ",indicate=" << is_indicate_supported
<< ",notify=" << is_notify_supported;
VLOG(1) << __func__
<< ": GATT characteristic properties: read=" << is_read_supported
<< ",write=" << is_write_supported
<< ",indicate=" << is_indicate_supported
<< ",notify=" << is_notify_supported;
gatt_characteristic_parameters.CharacteristicProperties(properties);
gatt_characteristic_parameters.WriteProtectionLevel(
@@ -330,10 +329,8 @@ bool BleGattServer::InitializeGattServer() {
winrt::guid characteristic_uuid = nearby_uuid_to_winrt_guid(
characteristic_data.gatt_characteristic.uuid);
NEARBY_VLOG(1) << __func__
<< ": Create characteristic characteristic_uuid="
<< winrt::to_string(
winrt::to_hstring(characteristic_uuid));
VLOG(1) << __func__ << ": Create characteristic characteristic_uuid="
<< winrt::to_string(winrt::to_hstring(characteristic_uuid));
GattLocalCharacteristicResult result =
gatt_service_provider_.Service()
@@ -342,9 +339,9 @@ bool BleGattServer::InitializeGattServer() {
.get();
if (result.Error() != BluetoothError::Success) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to create GATT characteristic. Error: "
<< static_cast<int>(result.Error());
LOG(ERROR) << __func__
<< ": Failed to create GATT characteristic. Error: "
<< static_cast<int>(result.Error());
return false;
}
@@ -352,9 +349,8 @@ bool BleGattServer::InitializeGattServer() {
::winrt::guid local_characteristic_guid =
characteristic_data.local_characteristic.Uuid();
NEARBY_VLOG(1) << __func__ << ": Local GATT characteristic. uuid: "
<< winrt::to_string(
winrt::to_hstring(local_characteristic_guid));
VLOG(1) << __func__ << ": Local GATT characteristic. uuid: "
<< winrt::to_string(winrt::to_hstring(local_characteristic_guid));
// Setup gatt local characteristic events.
if (is_read_supported) {
@@ -379,15 +375,15 @@ bool BleGattServer::InitializeGattServer() {
is_gatt_server_inited_ = true;
NEARBY_LOGS(INFO) << __func__ << ": GATT service is initalized.";
LOG(INFO) << __func__ << ": GATT service is initalized.";
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
}
// Clean up.
@@ -404,29 +400,28 @@ bool BleGattServer::StartAdvertisement(const ByteArray& service_data,
absl::MutexLock lock(&mutex_);
try {
NEARBY_VLOG(1) << __func__ << ": service_data="
<< absl::BytesToHexString(service_data.AsStringView())
<< ", is_connectable=" << is_connectable;
VLOG(1) << __func__ << ": service_data="
<< absl::BytesToHexString(service_data.AsStringView())
<< ", is_connectable=" << is_connectable;
if (is_advertising_) {
NEARBY_LOGS(ERROR) << ": GATT server is already in advertising.";
LOG(ERROR) << ": GATT server is already in advertising.";
return false;
}
if (!is_gatt_server_inited_ && !InitializeGattServer()) {
NEARBY_LOGS(ERROR) << ":Failed to initalize GATT service.";
LOG(ERROR) << ":Failed to initalize GATT service.";
return false;
}
if (gatt_service_provider_ == nullptr) {
NEARBY_LOGS(WARNING) << __func__ << ": no GATT server is running.";
LOG(WARNING) << __func__ << ": no GATT server is running.";
return false;
}
if (gatt_service_provider_.AdvertisementStatus() ==
GattServiceProviderAdvertisementStatus::Started) {
NEARBY_LOGS(WARNING) << __func__
<< ": GATT server is already in advertising.";
LOG(WARNING) << __func__ << ": GATT server is already in advertising.";
return false;
}
@@ -451,27 +446,27 @@ bool BleGattServer::StartAdvertisement(const ByteArray& service_data,
absl::SleepFor(absl::Milliseconds(kGattServerCheckIntervalInMills));
wait_milliseconds += kGattServerCheckIntervalInMills;
if (absl::Milliseconds(wait_milliseconds) > kGattServerTimeout) {
NEARBY_LOGS(ERROR)
<< __func__ << ": Failed to start GATT advertising due to timeout.";
LOG(ERROR) << __func__
<< ": Failed to start GATT advertising due to timeout.";
return false;
}
}
is_advertising_ = true;
NEARBY_LOGS(INFO) << __func__ << ": GATT server started.";
LOG(INFO) << __func__ << ": GATT server started.";
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
}
is_advertising_ = false;
NEARBY_LOGS(ERROR) << __func__ << ": Failed to advertise GATT server.";
LOG(ERROR) << __func__ << ": Failed to advertise GATT server.";
return false;
}
@@ -479,22 +474,22 @@ bool BleGattServer::StopAdvertisement() {
absl::MutexLock lock(&mutex_);
try {
NEARBY_LOGS(INFO) << __func__ << ": stop advertisement.";
LOG(INFO) << __func__ << ": stop advertisement.";
if (!is_advertising_) {
NEARBY_LOGS(WARNING) << __func__ << ": no GATT advertisement.";
LOG(WARNING) << __func__ << ": no GATT advertisement.";
return true;
}
if (gatt_service_provider_ == nullptr) {
NEARBY_LOGS(WARNING) << __func__ << ": no GATT server is running.";
LOG(WARNING) << __func__ << ": no GATT server is running.";
is_advertising_ = false;
return true;
}
if (gatt_service_provider_.AdvertisementStatus() ==
GattServiceProviderAdvertisementStatus ::Stopped) {
NEARBY_LOGS(WARNING) << __func__ << ": no GATT advertisement is running.";
LOG(WARNING) << __func__ << ": no GATT advertisement is running.";
is_advertising_ = false;
return true;
}
@@ -506,15 +501,15 @@ bool BleGattServer::StopAdvertisement() {
// status is stopped after the stop advertising is called.
is_advertising_ = false;
NEARBY_LOGS(INFO) << __func__ << ": GATT server stopped.";
LOG(INFO) << __func__ << ": GATT server stopped.";
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
}
return false;
@@ -530,9 +525,9 @@ void BleGattServer::SetCloseNotifier(absl::AnyInvocable<void()> notifier) {
GattLocalCharacteristic const& gatt_local_characteristic,
::winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::
GattReadRequestedEventArgs args) {
NEARBY_LOGS(INFO) << __func__ << ": Read characteristic. uuid: "
<< winrt::to_string(
winrt::to_hstring(gatt_local_characteristic.Uuid()));
LOG(INFO) << __func__ << ": Read characteristic. uuid: "
<< winrt::to_string(
winrt::to_hstring(gatt_local_characteristic.Uuid()));
auto deferral = args.GetDeferral();
@@ -542,15 +537,15 @@ void BleGattServer::SetCloseNotifier(absl::AnyInvocable<void()> notifier) {
FindGattCharacteristicData(gatt_local_characteristic);
if (characteristic_data == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to find characteristic="
<< ::winrt::to_string(::winrt::to_hstring(
gatt_local_characteristic.Uuid()));
LOG(ERROR) << __func__ << ": Failed to find characteristic="
<< ::winrt::to_string(
::winrt::to_hstring(gatt_local_characteristic.Uuid()));
return {};
}
GattReadRequest request = args.GetRequestAsync().get();
if (request == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to get GATT read request.";
LOG(ERROR) << __func__ << ": Failed to get GATT read request.";
deferral.Complete();
return {};
}
@@ -563,20 +558,20 @@ void BleGattServer::SetCloseNotifier(absl::AnyInvocable<void()> notifier) {
request.RespondWithValue(buffer);
deferral.Complete();
NEARBY_VLOG(1) << __func__ << ": Sent data to remote device.";
VLOG(1) << __func__ << ": Sent data to remote device.";
return {};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
}
deferral.Complete();
NEARBY_LOGS(ERROR) << __func__ << ": Failed to send data to remote device.";
LOG(ERROR) << __func__ << ": Failed to send data to remote device.";
return {};
}
@@ -593,10 +588,9 @@ void BleGattServer::Characteristic_SubscribedClientsChanged(
::winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::
GattLocalCharacteristic const& gatt_local_characteristic,
::winrt::Windows::Foundation::IInspectable const& args) {
NEARBY_LOGS(INFO) << __func__
<< ": Subscribed clients changed. characteristic="
<< ::winrt::to_string(::winrt::to_hstring(
gatt_local_characteristic.Uuid()));
LOG(INFO) << __func__ << ": Subscribed clients changed. characteristic="
<< ::winrt::to_string(
::winrt::to_hstring(gatt_local_characteristic.Uuid()));
try {
std::vector<api::ble_v2::GattCharacteristic>
@@ -608,9 +602,9 @@ void BleGattServer::Characteristic_SubscribedClientsChanged(
FindGattCharacteristicData(gatt_local_characteristic);
if (characteristic_data == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to find characteristic="
<< ::winrt::to_string(::winrt::to_hstring(
gatt_local_characteristic.Uuid()));
LOG(ERROR) << __func__ << ": Failed to find characteristic="
<< ::winrt::to_string(
::winrt::to_hstring(gatt_local_characteristic.Uuid()));
return;
}
@@ -666,12 +660,12 @@ void BleGattServer::Characteristic_SubscribedClientsChanged(
subscribed_characteristic);
}
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
}
}
@@ -680,9 +674,9 @@ void BleGattServer::ServiceProvider_AdvertisementStatusChanged(
GattServiceProvider const& sender,
::winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::
GattServiceProviderAdvertisementStatusChangedEventArgs const& args) {
NEARBY_LOGS(INFO) << __func__ << ": Advertisement status changed. status="
<< ConvertGattStatusToString(args.Status())
<< ", error=" << static_cast<int>(args.Error());
LOG(INFO) << __func__ << ": Advertisement status changed. status="
<< ConvertGattStatusToString(args.Status())
<< ", error=" << static_cast<int>(args.Error());
}
void BleGattServer::NotifyValueChanged(
@@ -692,8 +686,8 @@ void BleGattServer::NotifyValueChanged(
FindGattCharacteristicData(gatt_characteristic);
if (characteristic_data == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to find characteristic="
<< std::string(gatt_characteristic.uuid);
LOG(ERROR) << __func__ << ": Failed to find characteristic="
<< std::string(gatt_characteristic.uuid);
return;
}
@@ -713,19 +707,19 @@ void BleGattServer::NotifyValueChanged(
for (const auto& result : results) {
if (result.Status() != GattCommunicationStatus::Success) {
NEARBY_LOGS(ERROR)
<< __func__ << ": Failed to notify value change. remote device id="
<< ::winrt::to_string(
result.SubscribedClient().Session().DeviceId().Id());
LOG(ERROR) << __func__
<< ": Failed to notify value change. remote device id="
<< ::winrt::to_string(
result.SubscribedClient().Session().DeviceId().Id());
}
}
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
}
}
@@ -15,6 +15,7 @@
#include "internal/platform/implementation/windows/ble_medium.h"
#include <chrono> // NOLINT
#include <cstdint>
#include <exception>
#include <future> // NOLINT
#include <list>
@@ -26,7 +27,9 @@
#include "absl/synchronization/mutex.h"
#include "absl/synchronization/notification.h"
#include "absl/time/time.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/feature_flags.h"
#include "internal/platform/implementation/bluetooth_adapter.h"
#include "internal/platform/implementation/windows/ble_peripheral.h"
#include "internal/platform/implementation/windows/bluetooth_adapter.h"
#include "internal/platform/implementation/windows/utils.h"
@@ -146,22 +149,20 @@ bool BleMedium::StartAdvertising(
const std::string& fast_advertisement_service_uuid) {
try {
if (!adapter_->IsEnabled()) {
NEARBY_LOGS(WARNING) << "BLE cannot start advertising because the "
"bluetooth adapter is not enabled.";
LOG(WARNING) << "BLE cannot start advertising because the "
"bluetooth adapter is not enabled.";
return false;
}
NEARBY_LOGS(INFO)
<< "Windows Ble StartAdvertising: service_id=" << service_id
<< ", advertisement bytes= 0x"
<< absl::BytesToHexString(advertisement_bytes.AsStringView()) << "("
<< advertisement_bytes.size() << "),"
<< " fast advertisement service uuid= 0x"
<< absl::BytesToHexString(fast_advertisement_service_uuid);
LOG(INFO) << "Windows Ble StartAdvertising: service_id=" << service_id
<< ", advertisement bytes= 0x"
<< absl::BytesToHexString(advertisement_bytes.AsStringView())
<< "(" << advertisement_bytes.size() << "),"
<< " fast advertisement service uuid= 0x"
<< absl::BytesToHexString(fast_advertisement_service_uuid);
if (is_publisher_started_) {
NEARBY_LOGS(WARNING)
<< "BLE cannot start to advertise again when it is running.";
LOG(WARNING) << "BLE cannot start to advertise again when it is running.";
return false;
}
@@ -205,8 +206,8 @@ bool BleMedium::StartAdvertising(
publisher_.UseExtendedAdvertisement(false);
} else {
// otherwise no-op
NEARBY_LOGS(INFO) << "Everyone Mode unavailable for hardware that does "
"not support Extended Advertising.";
LOG(INFO) << "Everyone Mode unavailable for hardware that does "
"not support Extended Advertising.";
publisher_ = nullptr;
return false;
}
@@ -217,21 +218,21 @@ bool BleMedium::StartAdvertising(
publisher_.Start();
is_publisher_started_ = true;
NEARBY_LOGS(INFO) << "Windows Ble StartAdvertising started.";
LOG(INFO) << "Windows Ble StartAdvertising started.";
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception to start BLE advertising: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Exception to start BLE advertising: " << exception.what();
return false;
} catch (const winrt::hresult_error& ex) {
NEARBY_LOGS(ERROR) << __func__
<< ": Exception to start BLE advertising: " << ex.code()
<< ": " << winrt::to_string(ex.message());
LOG(ERROR) << __func__
<< ": Exception to start BLE advertising: " << ex.code() << ": "
<< winrt::to_string(ex.message());
return false;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
return false;
}
}
@@ -239,16 +240,15 @@ bool BleMedium::StartAdvertising(
bool BleMedium::StopAdvertising(const std::string& service_id) {
try {
if (!adapter_->IsEnabled()) {
NEARBY_LOGS(WARNING) << "BLE cannot stop advertising because the "
"bluetooth adapter is not enabled.";
LOG(WARNING) << "BLE cannot stop advertising because the "
"bluetooth adapter is not enabled.";
return false;
}
NEARBY_LOGS(INFO) << "Windows Ble StopAdvertising: service_id="
<< service_id;
LOG(INFO) << "Windows Ble StopAdvertising: service_id=" << service_id;
if (!is_publisher_started_) {
NEARBY_LOGS(WARNING) << "BLE advertising is not running.";
LOG(WARNING) << "BLE advertising is not running.";
return false;
}
@@ -266,18 +266,18 @@ bool BleMedium::StopAdvertising(const std::string& service_id) {
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception to stop BLE advertising: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Exception to stop BLE advertising: " << exception.what();
return false;
} catch (const winrt::hresult_error& ex) {
NEARBY_LOGS(ERROR) << __func__
<< ": Exception to stop BLE advertising: " << ex.code()
<< ": " << winrt::to_string(ex.message());
LOG(ERROR) << __func__
<< ": Exception to stop BLE advertising: " << ex.code() << ": "
<< winrt::to_string(ex.message());
return false;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
return false;
}
}
@@ -288,16 +288,15 @@ bool BleMedium::StartScanning(
DiscoveredPeripheralCallback callback) {
try {
if (!adapter_->IsEnabled()) {
NEARBY_LOGS(WARNING) << "BLE cannot start scanning because the "
"bluetooth adapter is not enabled.";
LOG(WARNING) << "BLE cannot start scanning because the "
"bluetooth adapter is not enabled.";
return false;
}
NEARBY_LOGS(INFO) << "Windows Ble StartScanning: service_id=" << service_id;
LOG(INFO) << "Windows Ble StartScanning: service_id=" << service_id;
if (is_watcher_started_) {
NEARBY_LOGS(WARNING)
<< "BLE cannot start to scan again when it is running.";
LOG(WARNING) << "BLE cannot start to scan again when it is running.";
return false;
}
@@ -327,21 +326,20 @@ bool BleMedium::StartScanning(
is_watcher_started_ = true;
NEARBY_LOGS(INFO) << "Windows Ble StartScanning started.";
LOG(INFO) << "Windows Ble StartScanning started.";
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception to start BLE scanning: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Exception to start BLE scanning: " << exception.what();
return false;
} catch (const winrt::hresult_error& ex) {
NEARBY_LOGS(ERROR) << __func__
<< ": Exception to start BLE scanning: " << ex.code()
<< ": " << winrt::to_string(ex.message());
LOG(ERROR) << __func__ << ": Exception to start BLE scanning: " << ex.code()
<< ": " << winrt::to_string(ex.message());
return false;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
return false;
}
}
@@ -349,15 +347,15 @@ bool BleMedium::StartScanning(
bool BleMedium::StopScanning(const std::string& service_id) {
try {
if (!adapter_->IsEnabled()) {
NEARBY_LOGS(WARNING) << "BLE cannot stop scanning because the "
"bluetooth adapter is not enabled.";
LOG(WARNING) << "BLE cannot stop scanning because the "
"bluetooth adapter is not enabled.";
return false;
}
NEARBY_LOGS(INFO) << "Windows Ble StopScanning: service_id=" << service_id;
LOG(INFO) << "Windows Ble StopScanning: service_id=" << service_id;
if (!is_watcher_started_) {
NEARBY_LOGS(WARNING) << "BLE scanning is not running.";
LOG(WARNING) << "BLE scanning is not running.";
return false;
}
@@ -368,37 +366,35 @@ bool BleMedium::StopScanning(const std::string& service_id) {
// stopping to finish.
is_watcher_started_ = false;
NEARBY_LOGS(ERROR)
<< "Windows Ble stoped scanning successfully for service_id="
<< service_id;
LOG(ERROR) << "Windows Ble stoped scanning successfully for service_id="
<< service_id;
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception to stop BLE scanning: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Exception to stop BLE scanning: " << exception.what();
return false;
} catch (const winrt::hresult_error& ex) {
NEARBY_LOGS(ERROR) << __func__
<< ": Exception to stop BLE scanning: " << ex.code()
<< ": " << winrt::to_string(ex.message());
LOG(ERROR) << __func__ << ": Exception to stop BLE scanning: " << ex.code()
<< ": " << winrt::to_string(ex.message());
return false;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
return false;
}
}
bool BleMedium::StartAcceptingConnections(const std::string& service_id,
AcceptedConnectionCallback callback) {
NEARBY_LOGS(INFO) << "Windows Ble StartAcceptingConnections: service_id="
<< service_id;
LOG(INFO) << "Windows Ble StartAcceptingConnections: service_id="
<< service_id;
return true;
}
bool BleMedium::StopAcceptingConnections(const std::string& service_id) {
NEARBY_LOGS(INFO) << "Windows Ble StopAcceptingConnections: service_id="
<< service_id;
LOG(INFO) << "Windows Ble StopAcceptingConnections: service_id="
<< service_id;
return true;
}
@@ -406,15 +402,15 @@ std::unique_ptr<api::BleSocket> BleMedium::Connect(
api::BlePeripheral& remote_peripheral, const std::string& service_id,
CancellationFlag* cancellation_flag) {
if (cancellation_flag->Cancelled()) {
NEARBY_LOGS(ERROR) << "Windows BLE Connect: Has been cancelled: "
"service_id="
<< service_id;
LOG(ERROR) << "Windows BLE Connect: Has been cancelled: "
"service_id="
<< service_id;
return {};
}
NEARBY_LOGS(ERROR) << "Windows Ble Connect: Cannot connect over BLE socket. "
"service_id="
<< service_id;
LOG(ERROR) << "Windows Ble Connect: Cannot connect over BLE socket. "
"service_id="
<< service_id;
return {};
}
@@ -424,75 +420,73 @@ void BleMedium::PublisherHandler(
// This method is called when publisher's status is changed.
switch (args.Status()) {
case BluetoothLEAdvertisementPublisherStatus::Created:
NEARBY_LOGS(INFO) << "Nearby BLE Medium created to advertise.";
LOG(INFO) << "Nearby BLE Medium created to advertise.";
return;
case BluetoothLEAdvertisementPublisherStatus::Started:
NEARBY_LOGS(INFO) << "Nearby BLE Medium started to advertise.";
LOG(INFO) << "Nearby BLE Medium started to advertise.";
return;
case BluetoothLEAdvertisementPublisherStatus::Stopping:
NEARBY_LOGS(INFO) << "Nearby BLE Medium is stopping.";
LOG(INFO) << "Nearby BLE Medium is stopping.";
return;
case BluetoothLEAdvertisementPublisherStatus::Waiting:
NEARBY_LOGS(INFO) << "Nearby BLE Medium is waiting.";
LOG(INFO) << "Nearby BLE Medium is waiting.";
return;
case BluetoothLEAdvertisementPublisherStatus::Stopped:
NEARBY_LOGS(INFO) << "Nearby BLE Medium stopped to advertise.";
LOG(INFO) << "Nearby BLE Medium stopped to advertise.";
break;
case BluetoothLEAdvertisementPublisherStatus::Aborted:
switch (args.Error()) {
case BluetoothError::Success:
if (publisher_.Status() ==
BluetoothLEAdvertisementPublisherStatus::Started) {
NEARBY_LOGS(ERROR)
<< "Nearby BLE Medium start advertising operation was "
"successfully completed or serviced.";
LOG(ERROR) << "Nearby BLE Medium start advertising operation was "
"successfully completed or serviced.";
}
if (publisher_.Status() ==
BluetoothLEAdvertisementPublisherStatus::Stopped) {
NEARBY_LOGS(ERROR)
<< "Nearby BLE Medium stop advertising operation was "
"successfully completed or serviced.";
LOG(ERROR) << "Nearby BLE Medium stop advertising operation was "
"successfully completed or serviced.";
} else {
NEARBY_LOGS(ERROR) << "Nearby BLE Medium advertising failed due to "
"unknown errors.";
LOG(ERROR) << "Nearby BLE Medium advertising failed due to "
"unknown errors.";
}
break;
case BluetoothError::RadioNotAvailable:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium advertising failed due to "
"radio not available.";
LOG(ERROR) << "Nearby BLE Medium advertising failed due to "
"radio not available.";
break;
case BluetoothError::ResourceInUse:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium advertising failed due to "
"resource in use.";
LOG(ERROR) << "Nearby BLE Medium advertising failed due to "
"resource in use.";
break;
case BluetoothError::DeviceNotConnected:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium advertising failed due to "
"remote device is not connected.";
LOG(ERROR) << "Nearby BLE Medium advertising failed due to "
"remote device is not connected.";
break;
case BluetoothError::DisabledByPolicy:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium advertising failed due to "
"disabled by policy.";
LOG(ERROR) << "Nearby BLE Medium advertising failed due to "
"disabled by policy.";
break;
case BluetoothError::DisabledByUser:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium advertising failed due to "
"disabled by user.";
LOG(ERROR) << "Nearby BLE Medium advertising failed due to "
"disabled by user.";
break;
case BluetoothError::NotSupported:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium advertising failed due to "
"hardware not supported.";
LOG(ERROR) << "Nearby BLE Medium advertising failed due to "
"hardware not supported.";
break;
case BluetoothError::TransportNotSupported:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium advertising failed due to "
"transport not supported.";
LOG(ERROR) << "Nearby BLE Medium advertising failed due to "
"transport not supported.";
break;
case BluetoothError::ConsentRequired:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium advertising failed due to "
"consent required.";
LOG(ERROR) << "Nearby BLE Medium advertising failed due to "
"consent required.";
break;
case BluetoothError::OtherError:
default:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium advertising failed due to "
"unknown errors.";
LOG(ERROR) << "Nearby BLE Medium advertising failed due to "
"unknown errors.";
break;
}
break;
@@ -502,7 +496,7 @@ void BleMedium::PublisherHandler(
// The publisher is stopped. Clean up the running publisher
if (publisher_ != nullptr) {
NEARBY_LOGS(ERROR) << "Nearby BLE Medium cleaned the publisher.";
LOG(ERROR) << "Nearby BLE Medium cleaned the publisher.";
publisher_.StatusChanged(publisher_token_);
publisher_ = nullptr;
is_publisher_started_ = false;
@@ -516,47 +510,42 @@ void BleMedium::WatcherHandler(
// information on the reason.
switch (args.Error()) {
case BluetoothError::Success:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium stoped to scan successfully.";
LOG(ERROR) << "Nearby BLE Medium stoped to scan successfully.";
break;
case BluetoothError::RadioNotAvailable:
NEARBY_LOGS(ERROR)
LOG(ERROR)
<< "Nearby BLE Medium stoped to scan due to radio not available.";
break;
case BluetoothError::ResourceInUse:
NEARBY_LOGS(ERROR)
<< "Nearby BLE Medium stoped to scan due to resource in use.";
LOG(ERROR) << "Nearby BLE Medium stoped to scan due to resource in use.";
break;
case BluetoothError::DeviceNotConnected:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium stoped to scan due to "
"remote device is not connected.";
LOG(ERROR) << "Nearby BLE Medium stoped to scan due to "
"remote device is not connected.";
break;
case BluetoothError::DisabledByPolicy:
NEARBY_LOGS(ERROR)
LOG(ERROR)
<< "Nearby BLE Medium stoped to scan due to disabled by policy.";
break;
case BluetoothError::DisabledByUser:
NEARBY_LOGS(ERROR)
<< "Nearby BLE Medium stoped to scan due to disabled by user.";
LOG(ERROR) << "Nearby BLE Medium stoped to scan due to disabled by user.";
break;
case BluetoothError::NotSupported:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium stoped to scan due to "
"hardware not supported.";
LOG(ERROR) << "Nearby BLE Medium stoped to scan due to "
"hardware not supported.";
break;
case BluetoothError::TransportNotSupported:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium stoped to scan due to "
"transport not supported.";
LOG(ERROR) << "Nearby BLE Medium stoped to scan due to "
"transport not supported.";
break;
case BluetoothError::ConsentRequired:
NEARBY_LOGS(ERROR)
<< "Nearby BLE Medium stoped to scan due to consent required.";
LOG(ERROR) << "Nearby BLE Medium stoped to scan due to consent required.";
break;
case BluetoothError::OtherError:
NEARBY_LOGS(ERROR)
<< "Nearby BLE Medium stoped to scan due to unknown errors.";
LOG(ERROR) << "Nearby BLE Medium stoped to scan due to unknown errors.";
break;
default:
NEARBY_LOGS(ERROR)
<< "Nearby BLE Medium stoped to scan due to unknown errors.";
LOG(ERROR) << "Nearby BLE Medium stoped to scan due to unknown errors.";
break;
}
@@ -564,7 +553,7 @@ void BleMedium::WatcherHandler(
// The BLE V1 interface doesn't have an API to return the error to the upper
// layer.
if (watcher_ != nullptr) {
NEARBY_LOGS(ERROR) << "Nearby BLE Medium cleaned the watcher.";
LOG(ERROR) << "Nearby BLE Medium cleaned the watcher.";
watcher_.Stopped(watcher_token_);
watcher_.Received(advertisement_received_token_);
watcher_ = nullptr;
@@ -600,11 +589,10 @@ void BleMedium::AdvertisementReceivedHandler(
ByteArray advertisement_data(data);
NEARBY_VLOG(1) << "Nearby BLE Medium Advertisement discovered. "
"0x16 Service data: advertisement bytes= 0x"
<< absl::BytesToHexString(
advertisement_data.AsStringView())
<< "(" << advertisement_data.size() << ")";
VLOG(1) << "Nearby BLE Medium Advertisement discovered. "
"0x16 Service data: advertisement bytes= 0x"
<< absl::BytesToHexString(advertisement_data.AsStringView())
<< "(" << advertisement_data.size() << ")";
std::string peripheral_name =
uint64_to_mac_address_string(args.BluetoothAddress());
@@ -616,7 +604,7 @@ void BleMedium::AdvertisementReceivedHandler(
if (peripheral_map_.contains(peripheral_name)) {
if (peripheral_map_[peripheral_name]->GetAdvertisementBytes(
service_id_) != advertisement_data) {
NEARBY_LOGS(INFO) << "BLE reports lost device: " << peripheral_name;
LOG(INFO) << "BLE reports lost device: " << peripheral_name;
// Lost the device first and then the report discovered the
// device.
@@ -644,15 +632,13 @@ void BleMedium::AdvertisementReceivedHandler(
// Received Fast Advertisement packet
if (unconsumed_buffer_length <= 27) {
NEARBY_LOGS(INFO)
<< "Sending Fast Advertisement packet for processing.";
LOG(INFO) << "Sending Fast Advertisement packet for processing.";
advertisement_received_callback_.peripheral_discovered_cb(
/*ble_peripheral*/ *peripheral_ptr, /*service_id*/ service_id_,
/*is_fast_advertisement*/ true);
} else {
// Received Extended Advertising packet
NEARBY_LOGS(INFO)
<< "Sending Extended Advertising packet for processing.";
LOG(INFO) << "Sending Extended Advertising packet for processing.";
advertisement_received_callback_.peripheral_discovered_cb(
/*ble_peripheral*/ *peripheral_ptr, /*service_id*/ service_id_,
/*is_fast_advertisement*/ false);
@@ -15,7 +15,10 @@
#include "internal/platform/implementation/windows/ble_socket.h"
#include "absl/synchronization/mutex.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/exception.h"
#include "internal/platform/implementation/windows/ble_peripheral.h"
#include "internal/platform/input_stream.h"
#include "internal/platform/output_stream.h"
namespace nearby {
namespace windows {
+199 -224
View File
@@ -146,24 +146,22 @@ bool BleV2Medium::StartAdvertising(const BleAdvertisementData& advertising_data,
absl::BytesToHexString(it.second.AsStringView()) + "}";
}
NEARBY_LOGS(INFO) << __func__
<< ": advertising_data.service_data=" << service_data_info
<< ", tx_power_level="
<< TxPowerLevelToName(
advertising_parameters.tx_power_level);
LOG(INFO) << __func__
<< ": advertising_data.service_data=" << service_data_info
<< ", tx_power_level="
<< TxPowerLevelToName(advertising_parameters.tx_power_level);
if (advertising_data.is_extended_advertisement) {
// In BLE v2, the flag is set when the Bluetooth adapter supports extended
// advertising and GATT server is using.
NEARBY_LOGS(INFO) << __func__
<< ": BLE advertising using BLE extended feature.";
LOG(INFO) << __func__ << ": BLE advertising using BLE extended feature.";
return StartBleAdvertising(advertising_data, advertising_parameters);
} else {
if (ble_gatt_server_ != nullptr) {
NEARBY_LOGS(INFO) << __func__ << ": BLE advertising on GATT server.";
LOG(INFO) << __func__ << ": BLE advertising on GATT server.";
return StartGattAdvertising(advertising_data, advertising_parameters);
} else {
NEARBY_LOGS(INFO) << __func__ << ": BLE fast advertising.";
LOG(INFO) << __func__ << ": BLE fast advertising.";
return StartBleAdvertising(advertising_data, advertising_parameters);
}
}
@@ -171,12 +169,12 @@ bool BleV2Medium::StartAdvertising(const BleAdvertisementData& advertising_data,
bool BleV2Medium::StopAdvertising() {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__ << ": Stop advertising.";
LOG(INFO) << __func__ << ": Stop advertising.";
bool result = true;
if (is_gatt_publisher_started_) {
bool stop_gatt_result = StopGattAdvertising();
if (!stop_gatt_result) {
NEARBY_LOGS(WARNING) << "Failed to stop GATT advertising.";
LOG(WARNING) << "Failed to stop GATT advertising.";
}
ble_gatt_server_ = nullptr;
result = stop_gatt_result;
@@ -185,7 +183,7 @@ bool BleV2Medium::StopAdvertising() {
if (is_ble_publisher_started_) {
bool stop_ble_result = StopBleAdvertising();
if (!stop_ble_result) {
NEARBY_LOGS(WARNING) << "Failed to stop BLE advertising.";
LOG(WARNING) << "Failed to stop BLE advertising.";
}
result = result && stop_ble_result;
}
@@ -198,13 +196,12 @@ std::unique_ptr<BleV2Medium::AdvertisingSession> BleV2Medium::StartAdvertising(
const api::ble_v2::BleAdvertisementData& advertising_data,
api::ble_v2::AdvertiseParameters advertise_set_parameters,
BleV2Medium::AdvertisingCallback callback) {
NEARBY_LOGS(INFO)
<< __func__ << ": advertising_data.is_extended_advertisement="
<< advertising_data.is_extended_advertisement
<< ", advertising_data.service_data size="
<< advertising_data.service_data.size() << ", tx_power_level="
<< TxPowerLevelToName(advertise_set_parameters.tx_power_level)
<< ", is_connectable=" << advertise_set_parameters.is_connectable;
LOG(INFO) << __func__ << ": advertising_data.is_extended_advertisement="
<< advertising_data.is_extended_advertisement
<< ", advertising_data.service_data size="
<< advertising_data.service_data.size() << ", tx_power_level="
<< TxPowerLevelToName(advertise_set_parameters.tx_power_level)
<< ", is_connectable=" << advertise_set_parameters.is_connectable;
if (StartAdvertising(advertising_data, advertise_set_parameters)) {
if (callback.start_advertising_result) {
callback.start_advertising_result(absl::OkStatus());
@@ -234,20 +231,19 @@ bool BleV2Medium::StartScanning(const Uuid& service_uuid,
TxPowerLevel tx_power_level,
ScanCallback callback) {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__
<< ": service UUID: " << std::string(service_uuid)
<< ", TxPowerLevel: " << TxPowerLevelToName(tx_power_level);
LOG(INFO) << __func__ << ": service UUID: " << std::string(service_uuid)
<< ", TxPowerLevel: " << TxPowerLevelToName(tx_power_level);
try {
if (!adapter_->IsEnabled()) {
NEARBY_LOGS(WARNING) << __func__
<< "BLE cannot start scanning because the "
"Bluetooth adapter is not enabled.";
LOG(WARNING) << __func__
<< "BLE cannot start scanning because the "
"Bluetooth adapter is not enabled.";
return false;
}
if (is_watcher_started_) {
NEARBY_LOGS(WARNING)
<< __func__ << ": BLE cannot start to scan again when it is running.";
LOG(WARNING) << __func__
<< ": BLE cannot start to scan again when it is running.";
return false;
}
@@ -289,8 +285,7 @@ bool BleV2Medium::StartScanning(const Uuid& service_uuid,
absl::SleepFor(absl::Milliseconds(kMediumCheckIntervalInMills));
wait_milliseconds += kMediumCheckIntervalInMills;
if (absl::Milliseconds(wait_milliseconds) > kMediumTimeout) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to start BLE scan due to timeout..";
LOG(ERROR) << __func__ << ": Failed to start BLE scan due to timeout..";
watcher_.Stopped(watcher_token_);
watcher_.Received(advertisement_received_token_);
watcher_ = nullptr;
@@ -300,21 +295,20 @@ bool BleV2Medium::StartScanning(const Uuid& service_uuid,
is_watcher_started_ = true;
NEARBY_LOGS(INFO) << __func__ << ": BLE scanning started.";
LOG(INFO) << __func__ << ": BLE scanning started.";
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception to start BLE scanning: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Exception to start BLE scanning: " << exception.what();
return false;
} catch (const winrt::hresult_error& ex) {
NEARBY_LOGS(ERROR) << __func__
<< ": Exception to start BLE scanning: " << ex.code()
<< ": " << winrt::to_string(ex.message());
LOG(ERROR) << __func__ << ": Exception to start BLE scanning: " << ex.code()
<< ": " << winrt::to_string(ex.message());
return false;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
return false;
}
}
@@ -323,17 +317,16 @@ std::unique_ptr<BleV2Medium::ScanningSession> BleV2Medium::StartScanning(
const Uuid& service_uuid, TxPowerLevel tx_power_level,
BleV2Medium::ScanningCallback callback) {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__
<< ": service UUID: " << std::string(service_uuid)
<< ", TxPowerLevel: " << TxPowerLevelToName(tx_power_level);
LOG(INFO) << __func__ << ": service UUID: " << std::string(service_uuid)
<< ", TxPowerLevel: " << TxPowerLevelToName(tx_power_level);
if (!adapter_->IsEnabled()) {
NEARBY_LOGS(WARNING) << __func__
<< "BLE cannot start scanning because the "
"Bluetooth adapter is not enabled.";
LOG(WARNING) << __func__
<< "BLE cannot start scanning because the "
"Bluetooth adapter is not enabled.";
return nullptr;
}
if (!is_watcher_started_) {
NEARBY_LOGS(WARNING) << __func__ << ": Starting BLE Scanning.";
LOG(WARNING) << __func__ << ": Starting BLE Scanning.";
try {
watcher_ = BluetoothLEAdvertisementWatcher();
watcher_token_ = watcher_.Stopped({this, &BleV2Medium::WatcherHandler});
@@ -355,22 +348,22 @@ std::unique_ptr<BleV2Medium::ScanningSession> BleV2Medium::StartScanning(
watcher_.SignalStrengthFilter(filter);
watcher_.Start();
is_watcher_started_ = true;
NEARBY_LOGS(INFO) << __func__ << ": BLE scanning started.";
LOG(INFO) << __func__ << ": BLE scanning started.";
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception to start BLE scanning: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Exception to start BLE scanning: " << exception.what();
return nullptr;
} catch (const winrt::hresult_error& ex) {
NEARBY_LOGS(ERROR) << __func__
<< ": Exception to start BLE scanning: " << ex.code()
<< ": " << winrt::to_string(ex.message());
LOG(ERROR) << __func__
<< ": Exception to start BLE scanning: " << ex.code() << ": "
<< winrt::to_string(ex.message());
return nullptr;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
return nullptr;
}
} else {
NEARBY_LOGS(WARNING) << __func__ << ": BLE Scanning already started.";
LOG(WARNING) << __func__ << ": BLE Scanning already started.";
}
uint64_t session_id = GenerateSessionId();
@@ -406,27 +399,27 @@ std::unique_ptr<BleV2Medium::ScanningSession> BleV2Medium::StartScanning(
// Stop discovery if there's no more on-going scan sessions.
if (service_uuid_to_session_map_.empty()) {
try {
NEARBY_LOGS(INFO)
LOG(INFO)
<< "No more scan sessions, stopping Ble scanning.";
watcher_.Stop();
is_watcher_started_ = false;
NEARBY_LOGS(INFO) << "Ble stoped scanning successfully.";
LOG(INFO) << "Ble stoped scanning successfully.";
} catch (std::exception exception) {
NEARBY_LOGS(ERROR)
LOG(ERROR)
<< __func__ << ": Exception to stop BLE scanning: "
<< exception.what();
return absl::InternalError(
"Bad status stopping Ble scanning");
} catch (const winrt::hresult_error& ex) {
NEARBY_LOGS(ERROR)
LOG(ERROR)
<< __func__
<< ": Exception to stop BLE scanning: " << ex.code()
<< ": " << winrt::to_string(ex.message());
return absl::InternalError(
"Bad status stopping Ble scanning");
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
return absl::InternalError(
"Bad status stopping Ble scanning");
}
@@ -440,20 +433,20 @@ std::unique_ptr<BleV2Medium::ScanningSession> BleV2Medium::StartScanning(
std::unique_ptr<api::ble_v2::GattServer> BleV2Medium::StartGattServer(
api::ble_v2::ServerGattConnectionCallback callback) {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__ << ": Start GATT server.";
LOG(INFO) << __func__ << ": Start GATT server.";
if (!NearbyFlags::GetInstance().GetBoolFlag(
platform::config_package_nearby::nearby_platform_feature::
kEnableBleV2Gatt)) {
if (adapter_->IsExtendedAdvertisingSupported()) {
NEARBY_LOGS(WARNING) << __func__ << ": GATT is disabled.";
LOG(WARNING) << __func__ << ": GATT is disabled.";
return nullptr;
}
if (!NearbyFlags::GetInstance().GetBoolFlag(
platform::config_package_nearby::nearby_platform_feature::
kEnableBleV2GattOnNonExtendedDevice)) {
NEARBY_LOGS(WARNING) << __func__ << ": GATT is disabled.";
LOG(WARNING) << __func__ << ": GATT is disabled.";
return nullptr;
}
}
@@ -466,7 +459,7 @@ std::unique_ptr<api::ble_v2::GattServer> BleV2Medium::StartGattServer(
// acquire the mutex here. The calling flow may cause deadlock due to
// StartGattAdvertising may run into the codes. It is not ideal, but it is
// hard to run in thread issues.
NEARBY_LOGS(INFO) << __func__ << ": GATT server is closed.";
LOG(INFO) << __func__ << ": GATT server is closed.";
ble_gatt_server_ = nullptr;
});
@@ -477,22 +470,22 @@ std::unique_ptr<api::ble_v2::GattClient> BleV2Medium::ConnectToGattServer(
api::ble_v2::BlePeripheral& peripheral, TxPowerLevel tx_power_level,
api::ble_v2::ClientGattConnectionCallback callback) {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << "ConnectToGattServer is called, address: "
<< peripheral.GetAddress()
<< ", power:" << TxPowerLevelToName(tx_power_level);
LOG(INFO) << "ConnectToGattServer is called, address: "
<< peripheral.GetAddress()
<< ", power:" << TxPowerLevelToName(tx_power_level);
if (!NearbyFlags::GetInstance().GetBoolFlag(
platform::config_package_nearby::nearby_platform_feature::
kEnableBleV2Gatt)) {
if (adapter_->IsExtendedAdvertisingSupported()) {
NEARBY_LOGS(WARNING) << __func__ << ": GATT is disabled.";
LOG(WARNING) << __func__ << ": GATT is disabled.";
return nullptr;
}
if (!NearbyFlags::GetInstance().GetBoolFlag(
platform::config_package_nearby::nearby_platform_feature::
kEnableBleV2GattOnNonExtendedDevice)) {
NEARBY_LOGS(WARNING) << __func__ << ": GATT is disabled.";
LOG(WARNING) << __func__ << ": GATT is disabled.";
return nullptr;
}
}
@@ -505,12 +498,12 @@ std::unique_ptr<api::ble_v2::GattClient> BleV2Medium::ConnectToGattServer(
return std::make_unique<BleGattClient>(ble_device);
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
}
return nullptr;
@@ -519,17 +512,17 @@ std::unique_ptr<api::ble_v2::GattClient> BleV2Medium::ConnectToGattServer(
bool BleV2Medium::StopScanning() {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__ << ": BLE StopScanning: service_uuid: "
<< std::string(service_uuid_);
LOG(INFO) << __func__ << ": BLE StopScanning: service_uuid: "
<< std::string(service_uuid_);
try {
if (!adapter_->IsEnabled()) {
NEARBY_LOGS(WARNING) << "BLE cannot stop scanning because the "
"bluetooth adapter is not enabled.";
LOG(WARNING) << "BLE cannot stop scanning because the "
"bluetooth adapter is not enabled.";
return false;
}
if (!is_watcher_started_) {
NEARBY_LOGS(WARNING) << "BLE scanning is not running.";
LOG(WARNING) << "BLE scanning is not running.";
return false;
}
@@ -542,8 +535,7 @@ bool BleV2Medium::StopScanning() {
absl::SleepFor(absl::Milliseconds(kMediumCheckIntervalInMills));
wait_milliseconds += kMediumCheckIntervalInMills;
if (absl::Milliseconds(wait_milliseconds) > kMediumTimeout) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to stop BLE scan due to timeout.";
LOG(ERROR) << __func__ << ": Failed to stop BLE scan due to timeout.";
watcher_.Stopped(watcher_token_);
watcher_.Received(advertisement_received_token_);
watcher_ = nullptr;
@@ -557,35 +549,33 @@ bool BleV2Medium::StopScanning() {
watcher_ = nullptr;
is_watcher_started_ = false;
NEARBY_LOGS(ERROR)
<< "Windows Ble stoped scanning successfully for service UUID:"
<< std::string(service_uuid_);
LOG(ERROR) << "Windows Ble stoped scanning successfully for service UUID:"
<< std::string(service_uuid_);
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception to stop BLE scanning: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Exception to stop BLE scanning: " << exception.what();
return false;
} catch (const winrt::hresult_error& ex) {
NEARBY_LOGS(ERROR) << __func__
<< ": Exception to stop BLE scanning: " << ex.code()
<< ": " << winrt::to_string(ex.message());
LOG(ERROR) << __func__ << ": Exception to stop BLE scanning: " << ex.code()
<< ": " << winrt::to_string(ex.message());
return false;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
return false;
}
}
std::unique_ptr<api::ble_v2::BleServerSocket> BleV2Medium::OpenServerSocket(
const std::string& service_id) {
NEARBY_LOGS(INFO) << "OpenServerSocket is called";
LOG(INFO) << "OpenServerSocket is called";
auto server_socket = std::make_unique<BleV2ServerSocket>(adapter_);
if (!server_socket->Bind()) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to bing socket.";
LOG(ERROR) << __func__ << ": Failed to bing socket.";
return nullptr;
}
@@ -596,17 +586,16 @@ std::unique_ptr<api::ble_v2::BleSocket> BleV2Medium::Connect(
const std::string& service_id, TxPowerLevel tx_power_level,
api::ble_v2::BlePeripheral& remote_peripheral,
CancellationFlag* cancellation_flag) {
NEARBY_LOGS(INFO) << __func__ << ": Connect to service_id=" << service_id;
LOG(INFO) << __func__ << ": Connect to service_id=" << service_id;
if (cancellation_flag == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": cancellation_flag not specified.";
LOG(ERROR) << __func__ << ": cancellation_flag not specified.";
return nullptr;
}
if (cancellation_flag->Cancelled()) {
NEARBY_LOGS(INFO) << __func__
<< ": BLE socket connection cancelled for service: "
<< service_id;
LOG(INFO) << __func__ << ": BLE socket connection cancelled for service: "
<< service_id;
return nullptr;
}
@@ -616,9 +605,8 @@ std::unique_ptr<api::ble_v2::BleSocket> BleV2Medium::Connect(
cancellation_flag, [socket = ble_socket.get()]() { socket->Close(); });
if (!ble_socket->Connect(&remote_peripheral)) {
NEARBY_LOGS(INFO) << __func__
<< ": BLE socket connection failed. service_id="
<< service_id;
LOG(INFO) << __func__
<< ": BLE socket connection failed. service_id=" << service_id;
return nullptr;
}
@@ -632,23 +620,22 @@ bool BleV2Medium::IsExtendedAdvertisementsAvailable() {
bool BleV2Medium::StartBleAdvertising(
const api::ble_v2::BleAdvertisementData& advertising_data,
api::ble_v2::AdvertiseParameters advertising_parameters) {
NEARBY_LOGS(INFO) << __func__ << ": Start BLE advertising.";
LOG(INFO) << __func__ << ": Start BLE advertising.";
try {
if (!adapter_->IsEnabled()) {
NEARBY_LOGS(WARNING) << "BLE cannot start advertising because the "
"bluetooth adapter is not enabled.";
LOG(WARNING) << "BLE cannot start advertising because the "
"bluetooth adapter is not enabled.";
return false;
}
if (advertising_data.service_data.empty()) {
NEARBY_LOGS(WARNING)
LOG(WARNING)
<< "BLE cannot start to advertise due to invalid service data.";
return false;
}
if (is_ble_publisher_started_) {
NEARBY_LOGS(WARNING)
<< "BLE cannot start to advertise again when it is running.";
LOG(WARNING) << "BLE cannot start to advertise again when it is running.";
return false;
}
@@ -664,12 +651,11 @@ bool BleV2Medium::StartBleAdvertising(
std::string uuid_string = it.first.Get16BitAsString();
int uuid;
if (!absl::SimpleHexAtoi(uuid_string, &uuid)) {
NEARBY_LOGS(WARNING) << "BLE failed to get service UUID.";
LOG(WARNING) << "BLE failed to get service UUID.";
return false;
}
NEARBY_LOGS(WARNING) << "BLE service UUID: "
<< absl::StrFormat("%#x", uuid);
LOG(WARNING) << "BLE service UUID: " << absl::StrFormat("%#x", uuid);
data_writer.WriteUInt16(((uuid >> 8) & 0xff) | ((uuid & 0xff) << 8));
@@ -693,7 +679,7 @@ bool BleV2Medium::StartBleAdvertising(
// string because the long format advertisement will be used
if (advertising_data.is_extended_advertisement) {
if (!adapter_->IsExtendedAdvertisingSupported()) {
NEARBY_LOGS(WARNING)
LOG(WARNING)
<< "Cannot advertise extended advertisement on devie without BLE "
"advertisement extention feature.";
return false;
@@ -703,8 +689,8 @@ bool BleV2Medium::StartBleAdvertising(
publisher_.UseExtendedAdvertisement(true);
} else {
if (max_data_section_size > 27) {
NEARBY_LOGS(WARNING) << "Invalid advertisement data size for "
"non-extended advertisement.";
LOG(WARNING) << "Invalid advertisement data size for "
"non-extended advertisement.";
return false;
}
@@ -723,8 +709,8 @@ bool BleV2Medium::StartBleAdvertising(
absl::SleepFor(absl::Milliseconds(kMediumCheckIntervalInMills));
wait_milliseconds += kMediumCheckIntervalInMills;
if (absl::Milliseconds(wait_milliseconds) > kMediumTimeout) {
NEARBY_LOGS(ERROR)
<< __func__ << ": BLE advertising failed to start due to timeout.";
LOG(ERROR) << __func__
<< ": BLE advertising failed to start due to timeout.";
publisher_.StatusChanged(publisher_token_);
publisher_ = nullptr;
is_ble_publisher_started_ = false;
@@ -733,36 +719,36 @@ bool BleV2Medium::StartBleAdvertising(
}
is_ble_publisher_started_ = true;
NEARBY_LOGS(INFO) << "BLE advertising started.";
LOG(INFO) << "BLE advertising started.";
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception to start BLE advertising: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Exception to start BLE advertising: " << exception.what();
return false;
} catch (const winrt::hresult_error& ex) {
NEARBY_LOGS(ERROR) << __func__
<< ": Exception to start BLE advertising: " << ex.code()
<< ": " << winrt::to_string(ex.message());
LOG(ERROR) << __func__
<< ": Exception to start BLE advertising: " << ex.code() << ": "
<< winrt::to_string(ex.message());
return false;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
return false;
}
}
bool BleV2Medium::StopBleAdvertising() {
NEARBY_LOGS(INFO) << __func__ << ": Stop BLE advertising.";
LOG(INFO) << __func__ << ": Stop BLE advertising.";
try {
if (!adapter_->IsEnabled()) {
NEARBY_LOGS(WARNING) << "BLE cannot stop advertising because the "
"bluetooth adapter is not enabled.";
LOG(WARNING) << "BLE cannot stop advertising because the "
"bluetooth adapter is not enabled.";
return false;
}
if (!is_ble_publisher_started_) {
NEARBY_LOGS(WARNING) << "BLE advertising is not running.";
LOG(WARNING) << "BLE advertising is not running.";
return false;
}
@@ -770,7 +756,7 @@ bool BleV2Medium::StopBleAdvertising() {
if (publisher_ == nullptr ||
publisher_.Status() !=
BluetoothLEAdvertisementPublisherStatus::Started) {
NEARBY_LOGS(WARNING) << "No started publisher is running.";
LOG(WARNING) << "No started publisher is running.";
return false;
}
@@ -783,8 +769,8 @@ bool BleV2Medium::StopBleAdvertising() {
absl::SleepFor(absl::Milliseconds(kMediumCheckIntervalInMills));
wait_milliseconds += kMediumCheckIntervalInMills;
if (absl::Milliseconds(wait_milliseconds) > kMediumTimeout) {
NEARBY_LOGS(ERROR)
<< __func__ << ": BLE advertising failed to stop due to timeout.";
LOG(ERROR) << __func__
<< ": BLE advertising failed to stop due to timeout.";
publisher_.StatusChanged(publisher_token_);
publisher_ = nullptr;
is_ble_publisher_started_ = false;
@@ -799,18 +785,18 @@ bool BleV2Medium::StopBleAdvertising() {
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception to stop BLE advertising: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Exception to stop BLE advertising: " << exception.what();
return false;
} catch (const winrt::hresult_error& ex) {
NEARBY_LOGS(ERROR) << __func__
<< ": Exception to stop BLE advertising: " << ex.code()
<< ": " << winrt::to_string(ex.message());
LOG(ERROR) << __func__
<< ": Exception to stop BLE advertising: " << ex.code() << ": "
<< winrt::to_string(ex.message());
return false;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
return false;
}
}
@@ -818,28 +804,28 @@ bool BleV2Medium::StopBleAdvertising() {
bool BleV2Medium::StartGattAdvertising(
const api::ble_v2::BleAdvertisementData& advertising_data,
api::ble_v2::AdvertiseParameters advertising_parameters) {
NEARBY_LOGS(INFO) << __func__ << ": Start GATT advertising.";
LOG(INFO) << __func__ << ": Start GATT advertising.";
try {
if (!adapter_->IsEnabled()) {
NEARBY_LOGS(WARNING) << "BLE cannot start GATT advertising because the "
"bluetooth adapter is not enabled.";
LOG(WARNING) << "BLE cannot start GATT advertising because the "
"bluetooth adapter is not enabled.";
return false;
}
if (advertising_data.service_data.empty()) {
NEARBY_LOGS(WARNING)
LOG(WARNING)
<< "BLE cannot start GATT advertising due to invalid service data.";
return false;
}
if (is_gatt_publisher_started_) {
NEARBY_LOGS(WARNING)
LOG(WARNING)
<< "BLE cannot start GATT advertising again when it is running.";
return false;
}
if (ble_gatt_server_ == nullptr) {
NEARBY_LOGS(WARNING) << "No Gatt server is running.";
LOG(WARNING) << "No Gatt server is running.";
return false;
}
@@ -854,69 +840,68 @@ bool BleV2Medium::StartGattAdvertising(
bool is_started = ble_gatt_server_->StartAdvertisement(
service_data, advertising_parameters.is_connectable);
if (!is_started) {
NEARBY_LOGS(WARNING) << "BLE cannot start GATT advertising.";
LOG(WARNING) << "BLE cannot start GATT advertising.";
return false;
}
is_gatt_publisher_started_ = true;
NEARBY_LOGS(INFO) << "GATT advertising started.";
LOG(INFO) << "GATT advertising started.";
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception to start GATT advertising: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Exception to start GATT advertising: " << exception.what();
return false;
} catch (const winrt::hresult_error& ex) {
NEARBY_LOGS(ERROR) << __func__
<< ": Exception to start GATT advertising: " << ex.code()
<< ": " << winrt::to_string(ex.message());
LOG(ERROR) << __func__
<< ": Exception to start GATT advertising: " << ex.code() << ": "
<< winrt::to_string(ex.message());
return false;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
return false;
}
}
bool BleV2Medium::StopGattAdvertising() {
try {
NEARBY_LOGS(INFO) << __func__ << ": Stop GATT advertising.";
LOG(INFO) << __func__ << ": Stop GATT advertising.";
if (!adapter_->IsEnabled()) {
NEARBY_LOGS(WARNING) << "BLE cannot stop GATT advertising because the "
"bluetooth adapter is not enabled.";
LOG(WARNING) << "BLE cannot stop GATT advertising because the "
"bluetooth adapter is not enabled.";
return false;
}
if (!is_gatt_publisher_started_) {
NEARBY_LOGS(WARNING) << "BLE GATT advertising is not running.";
LOG(WARNING) << "BLE GATT advertising is not running.";
return false;
}
if (ble_gatt_server_ == nullptr) {
NEARBY_LOGS(WARNING) << "No Gatt server is running.";
LOG(WARNING) << "No Gatt server is running.";
return false;
}
bool stop_result = ble_gatt_server_->StopAdvertisement();
is_gatt_publisher_started_ = false;
NEARBY_LOGS(INFO) << "Stop GATT advertisement result=" << stop_result;
LOG(INFO) << "Stop GATT advertisement result=" << stop_result;
return stop_result;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__
<< ": Exception to stop BLE GATT advertising: "
<< exception.what();
LOG(ERROR) << __func__ << ": Exception to stop BLE GATT advertising: "
<< exception.what();
return false;
} catch (const winrt::hresult_error& ex) {
NEARBY_LOGS(ERROR) << __func__
<< ": Exception to stop BLE GATT advertising: "
<< ex.code() << ": " << winrt::to_string(ex.message());
LOG(ERROR) << __func__
<< ": Exception to stop BLE GATT advertising: " << ex.code()
<< ": " << winrt::to_string(ex.message());
return false;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
return false;
}
}
@@ -927,74 +912,72 @@ void BleV2Medium::PublisherHandler(
// This method is called when publisher's status is changed.
switch (args.Status()) {
case BluetoothLEAdvertisementPublisherStatus::Created:
NEARBY_LOGS(INFO) << "Nearby BLE Medium created to advertise.";
LOG(INFO) << "Nearby BLE Medium created to advertise.";
return;
case BluetoothLEAdvertisementPublisherStatus::Started:
NEARBY_LOGS(INFO) << "Nearby BLE Medium started to advertise.";
LOG(INFO) << "Nearby BLE Medium started to advertise.";
return;
case BluetoothLEAdvertisementPublisherStatus::Stopping:
NEARBY_LOGS(INFO) << "Nearby BLE Medium is stopping.";
LOG(INFO) << "Nearby BLE Medium is stopping.";
return;
case BluetoothLEAdvertisementPublisherStatus::Waiting:
NEARBY_LOGS(INFO) << "Nearby BLE Medium is waiting.";
LOG(INFO) << "Nearby BLE Medium is waiting.";
return;
case BluetoothLEAdvertisementPublisherStatus::Stopped:
NEARBY_LOGS(INFO) << "Nearby BLE Medium stopped to advertise.";
LOG(INFO) << "Nearby BLE Medium stopped to advertise.";
break;
case BluetoothLEAdvertisementPublisherStatus::Aborted:
switch (args.Error()) {
case BluetoothError::Success:
if (publisher.Status() ==
BluetoothLEAdvertisementPublisherStatus::Started) {
NEARBY_LOGS(ERROR)
<< "Nearby BLE Medium start advertising operation was "
"successfully completed or serviced.";
LOG(ERROR) << "Nearby BLE Medium start advertising operation was "
"successfully completed or serviced.";
}
if (publisher.Status() ==
BluetoothLEAdvertisementPublisherStatus::Stopped) {
NEARBY_LOGS(ERROR)
<< "Nearby BLE Medium stop advertising operation was "
"successfully completed or serviced.";
LOG(ERROR) << "Nearby BLE Medium stop advertising operation was "
"successfully completed or serviced.";
} else {
NEARBY_LOGS(ERROR) << "Nearby BLE Medium advertising failed due to "
"unknown errors.";
LOG(ERROR) << "Nearby BLE Medium advertising failed due to "
"unknown errors.";
}
break;
case BluetoothError::RadioNotAvailable:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium advertising failed due to "
"radio not available.";
LOG(ERROR) << "Nearby BLE Medium advertising failed due to "
"radio not available.";
break;
case BluetoothError::ResourceInUse:
NEARBY_LOGS(ERROR)
LOG(ERROR)
<< "Nearby BLE Medium advertising failed due to resource in use.";
break;
case BluetoothError::DeviceNotConnected:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium advertising failed due to "
"remote device is not connected.";
LOG(ERROR) << "Nearby BLE Medium advertising failed due to "
"remote device is not connected.";
break;
case BluetoothError::DisabledByPolicy:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium advertising failed due to "
"disabled by policy.";
LOG(ERROR) << "Nearby BLE Medium advertising failed due to "
"disabled by policy.";
break;
case BluetoothError::DisabledByUser:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium advertising failed due to "
"disabled by user.";
LOG(ERROR) << "Nearby BLE Medium advertising failed due to "
"disabled by user.";
break;
case BluetoothError::NotSupported:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium advertising failed due to "
"hardware not supported.";
LOG(ERROR) << "Nearby BLE Medium advertising failed due to "
"hardware not supported.";
break;
case BluetoothError::TransportNotSupported:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium advertising failed due to "
"transport not supported.";
LOG(ERROR) << "Nearby BLE Medium advertising failed due to "
"transport not supported.";
break;
case BluetoothError::ConsentRequired:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium advertising failed due to "
"consent required.";
LOG(ERROR) << "Nearby BLE Medium advertising failed due to "
"consent required.";
break;
case BluetoothError::OtherError:
default:
NEARBY_LOGS(ERROR)
LOG(ERROR)
<< "Nearby BLE Medium advertising failed due to unknown errors.";
break;
}
@@ -1011,47 +994,42 @@ void BleV2Medium::WatcherHandler(
// information on the reason.
switch (args.Error()) {
case BluetoothError::Success:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium stoped to scan successfully.";
LOG(ERROR) << "Nearby BLE Medium stoped to scan successfully.";
break;
case BluetoothError::RadioNotAvailable:
NEARBY_LOGS(ERROR)
LOG(ERROR)
<< "Nearby BLE Medium stoped to scan due to radio not available.";
break;
case BluetoothError::ResourceInUse:
NEARBY_LOGS(ERROR)
<< "Nearby BLE Medium stoped to scan due to resource in use.";
LOG(ERROR) << "Nearby BLE Medium stoped to scan due to resource in use.";
break;
case BluetoothError::DeviceNotConnected:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium stoped to scan due to "
"remote device is not connected.";
LOG(ERROR) << "Nearby BLE Medium stoped to scan due to "
"remote device is not connected.";
break;
case BluetoothError::DisabledByPolicy:
NEARBY_LOGS(ERROR)
LOG(ERROR)
<< "Nearby BLE Medium stoped to scan due to disabled by policy.";
break;
case BluetoothError::DisabledByUser:
NEARBY_LOGS(ERROR)
<< "Nearby BLE Medium stoped to scan due to disabled by user.";
LOG(ERROR) << "Nearby BLE Medium stoped to scan due to disabled by user.";
break;
case BluetoothError::NotSupported:
NEARBY_LOGS(ERROR)
LOG(ERROR)
<< "Nearby BLE Medium stoped to scan due to hardware not supported.";
break;
case BluetoothError::TransportNotSupported:
NEARBY_LOGS(ERROR) << "Nearby BLE Medium stoped to scan due to "
"transport not supported.";
LOG(ERROR) << "Nearby BLE Medium stoped to scan due to "
"transport not supported.";
break;
case BluetoothError::ConsentRequired:
NEARBY_LOGS(ERROR)
<< "Nearby BLE Medium stoped to scan due to consent required.";
LOG(ERROR) << "Nearby BLE Medium stoped to scan due to consent required.";
break;
case BluetoothError::OtherError:
NEARBY_LOGS(ERROR)
<< "Nearby BLE Medium stoped to scan due to unknown errors.";
LOG(ERROR) << "Nearby BLE Medium stoped to scan due to unknown errors.";
break;
default:
NEARBY_LOGS(ERROR)
<< "Nearby BLE Medium stoped to scan due to unknown errors.";
LOG(ERROR) << "Nearby BLE Medium stoped to scan due to unknown errors.";
break;
}
}
@@ -1085,12 +1063,11 @@ void BleV2Medium::AdvertisementReceivedHandler(
ByteArray advertisement_data(data);
NEARBY_VLOG(1) << "Nearby BLE Medium " << service_uuid_.Get16BitAsString()
<< " Advertisement discovered. "
"0x16 Service data: advertisement bytes= 0x"
<< absl::BytesToHexString(
advertisement_data.AsStringView())
<< "(" << advertisement_data.size() << ")";
VLOG(1) << "Nearby BLE Medium " << service_uuid_.Get16BitAsString()
<< " Advertisement discovered. "
"0x16 Service data: advertisement bytes= 0x"
<< absl::BytesToHexString(advertisement_data.AsStringView())
<< "(" << advertisement_data.size() << ")";
std::string bluetooth_address =
uint64_to_mac_address_string(args.BluetoothAddress());
@@ -1099,16 +1076,15 @@ void BleV2Medium::AdvertisementReceivedHandler(
absl::MutexLock lock(&mutex_);
peripheral_ptr = GetOrCreatePeripheral(bluetooth_address);
if (peripheral_ptr == nullptr) {
NEARBY_LOGS(ERROR)
<< "No BLE peripheral with address: " << bluetooth_address;
LOG(ERROR) << "No BLE peripheral with address: " << bluetooth_address;
return;
}
}
NEARBY_LOGS(INFO) << "BLE peripheral with address: " << bluetooth_address;
LOG(INFO) << "BLE peripheral with address: " << bluetooth_address;
// Received Advertisement packet
NEARBY_LOGS(INFO) << "unconsumed_buffer_length: "
<< static_cast<int>(unconsumed_buffer_length);
LOG(INFO) << "unconsumed_buffer_length: "
<< static_cast<int>(unconsumed_buffer_length);
api::ble_v2::BleAdvertisementData ble_advertisement_data;
if (unconsumed_buffer_length <= 27) {
@@ -1166,8 +1142,8 @@ void BleV2Medium::AdvertisementFoundHandler(
uint8_t unconsumed_buffer_length = data_reader.UnconsumedBufferLength();
if (unconsumed_buffer_length > 27) {
NEARBY_LOGS(INFO) << "Skipping extended advertisement with service "
<< service_uuid.Get16BitAsString();
LOG(INFO) << "Skipping extended advertisement with service "
<< service_uuid.Get16BitAsString();
return;
}
for (int i = 0; i < unconsumed_buffer_length; i++) {
@@ -1178,8 +1154,8 @@ void BleV2Medium::AdvertisementFoundHandler(
}
}
if (ble_advertisement_data.service_data.empty()) {
NEARBY_LOGS(ERROR) << "Got matching Service UUID but found no "
"corresponding data, skipping";
LOG(ERROR) << "Got matching Service UUID but found no "
"corresponding data, skipping";
return;
}
// Save the BleV2Peripheral.
@@ -1190,12 +1166,11 @@ void BleV2Medium::AdvertisementFoundHandler(
absl::MutexLock lock(&mutex_);
peripheral_ptr = GetOrCreatePeripheral(bluetooth_address);
if (peripheral_ptr == nullptr) {
NEARBY_LOGS(ERROR) << "No BLE peripheral with address: "
<< bluetooth_address;
LOG(ERROR) << "No BLE peripheral with address: " << bluetooth_address;
return;
}
}
NEARBY_LOGS(INFO) << "BLE peripheral with address: " << bluetooth_address;
LOG(INFO) << "BLE peripheral with address: " << bluetooth_address;
// Invokes callbacks that matches the UUID.
for (auto service_uuid : service_uuid_list) {
@@ -1237,7 +1212,7 @@ bool BleV2Medium::GetRemotePeripheral(api::ble_v2::BlePeripheral::UniqueId id,
}
if (peripheral == nullptr) {
NEARBY_LOGS(WARNING) << __func__ << ": No matched peripheral device.";
LOG(WARNING) << __func__ << ": No matched peripheral device.";
return false;
}
callback(*peripheral);
@@ -1272,10 +1247,10 @@ BleV2Peripheral* BleV2Medium::GetOrCreatePeripheral(absl::string_view address) {
};
BleV2Peripheral* peripheral = peripheral_info.peripheral.get();
if (!peripheral->Ok()) {
NEARBY_LOGS(WARNING) << __func__ << "Invalid MAC address: " << address;
LOG(WARNING) << __func__ << "Invalid MAC address: " << address;
return nullptr;
}
NEARBY_LOGS(INFO) << "New BLE peripheral with address: " << address;
LOG(INFO) << "New BLE peripheral with address: " << address;
peripheral_map_[peripheral->GetUniqueId()] = std::move(peripheral_info);
return peripheral;
@@ -35,7 +35,7 @@ BleV2Peripheral::BleV2Peripheral(absl::string_view address) {
bool BleV2Peripheral::SetAddress(absl::string_view address) {
// The address must be in format "00:B0:D0:63:C2:26".
if (address.size() != kMacAddressLength) {
NEARBY_LOGS(ERROR) << ": Invalid MAC address length.";
LOG(ERROR) << ": Invalid MAC address length.";
return false;
}
@@ -52,7 +52,7 @@ bool BleV2Peripheral::SetAddress(absl::string_view address) {
}
}
NEARBY_LOGS(ERROR) << ": Invalid MAC address format.";
LOG(ERROR) << ": Invalid MAC address format.";
return false;
}
@@ -21,6 +21,8 @@
#include "absl/synchronization/mutex.h"
#include "absl/synchronization/notification.h"
#include "internal/platform/exception.h"
#include "internal/platform/implementation/ble_v2.h"
#include "internal/platform/implementation/bluetooth_adapter.h"
#include "internal/platform/implementation/windows/ble_v2_socket.h"
#include "internal/platform/implementation/windows/bluetooth_adapter.h"
#include "internal/platform/implementation/windows/utils.h"
@@ -36,7 +38,7 @@ BleV2ServerSocket::BleV2ServerSocket(api::BluetoothAdapter* adapter)
std::unique_ptr<api::ble_v2::BleSocket> BleV2ServerSocket::Accept() {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__ << ": Accept is called.";
LOG(INFO) << __func__ << ": Accept is called.";
while (!closed_ && pending_sockets_.empty()) {
cond_.Wait(&mutex_);
@@ -46,14 +48,14 @@ std::unique_ptr<api::ble_v2::BleSocket> BleV2ServerSocket::Accept() {
BleV2Socket ble_socket = pending_sockets_.front();
pending_sockets_.pop_front();
NEARBY_LOGS(INFO) << __func__ << ": Accepted a remote connection.";
LOG(INFO) << __func__ << ": Accepted a remote connection.";
return std::make_unique<BleV2Socket>(ble_socket);
}
Exception BleV2ServerSocket::Close() {
// TODO(b/271031645): implement BLE socket using weave
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__ << ": Close is called.";
LOG(INFO) << __func__ << ": Close is called.";
if (closed_) {
return {Exception::kSuccess};
@@ -67,7 +69,7 @@ Exception BleV2ServerSocket::Close() {
bool BleV2ServerSocket::Bind() {
// TODO(b/271031645): implement BLE socket using weave
NEARBY_LOGS(ERROR) << __func__ << ": GATT socket started.";
LOG(ERROR) << __func__ << ": GATT socket started.";
return true;
}
@@ -15,6 +15,7 @@
#include "internal/platform/implementation/windows/ble_v2_socket.h"
#include <cstddef>
#include <cstdint>
#include <memory>
#include "absl/synchronization/mutex.h"
@@ -22,8 +23,11 @@
#include "absl/time/time.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/exception.h"
#include "internal/platform/implementation/ble_v2.h"
#include "internal/platform/implementation/windows/utils.h"
#include "internal/platform/input_stream.h"
#include "internal/platform/logging.h"
#include "internal/platform/output_stream.h"
namespace nearby {
namespace windows {
@@ -40,38 +44,38 @@ api::ble_v2::BlePeripheral* BleV2Socket::GetRemotePeripheral() {
bool BleV2Socket::Connect(api::ble_v2::BlePeripheral* ble_peripheral) {
// TODO(b/271031645): implement BLE socket using weave
NEARBY_VLOG(1) << __func__ << ": Connect to BLE peripheral="
<< ble_peripheral->GetAddress();
VLOG(1) << __func__
<< ": Connect to BLE peripheral=" << ble_peripheral->GetAddress();
return false;
}
ExceptionOr<ByteArray> BleV2Socket::BleInputStream::Read(std::int64_t size) {
// TODO(b/271031645): implement BLE socket using weave
NEARBY_VLOG(1) << __func__ << ": Read data size=" << size;
VLOG(1) << __func__ << ": Read data size=" << size;
return ExceptionOr<ByteArray>(Exception::kIo);
}
Exception BleV2Socket::BleInputStream::Close() {
// TODO(b/271031645): implement BLE socket using weave
NEARBY_VLOG(1) << __func__ << ": Close BLE input stream.";
VLOG(1) << __func__ << ": Close BLE input stream.";
return {Exception::kSuccess};
}
Exception BleV2Socket::BleOutputStream::Write(const ByteArray& data) {
// TODO(b/271031645): implement BLE socket using weave
NEARBY_VLOG(1) << __func__ << ": Write data size=" << data.size();
VLOG(1) << __func__ << ": Write data size=" << data.size();
return {Exception::kIo};
}
Exception BleV2Socket::BleOutputStream::Flush() {
// TODO(b/271031645): implement BLE socket using weave
NEARBY_LOGS(INFO) << __func__ << ": Flush is called.";
LOG(INFO) << __func__ << ": Flush is called.";
return {Exception::kSuccess};
}
Exception BleV2Socket::BleOutputStream::Close() {
// TODO(b/271031645): implement BLE socket using weave
NEARBY_LOGS(INFO) << __func__ << ": close is called.";
LOG(INFO) << __func__ << ": close is called.";
return {Exception::kSuccess};
}
@@ -32,12 +32,14 @@
#include <stdio.h>
#include <usbiodef.h>
#include <cstdint>
#include <cstring>
#include <exception>
#include <optional>
#include <string>
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "third_party/json/src/json.hpp"
#include "internal/platform/feature_flags.h"
#include "internal/platform/implementation/platform.h"
@@ -88,8 +90,7 @@ BluetoothAdapter::BluetoothAdapter() : windows_bluetooth_adapter_(nullptr) {
winrt::Windows::Devices::Bluetooth::BluetoothAdapter::GetDefaultAsync()
.get();
if (windows_bluetooth_adapter_ == nullptr) {
NEARBY_LOGS(ERROR) << __func__
<< ": No Bluetooth adapter on this device.";
LOG(ERROR) << __func__ << ": No Bluetooth adapter on this device.";
} else {
// Gets the radio represented by this Bluetooth adapter.
// https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothadapter.getradioasync?view=winrt-20348
@@ -97,20 +98,20 @@ BluetoothAdapter::BluetoothAdapter() : windows_bluetooth_adapter_(nullptr) {
windows_bluetooth_adapter_.GetRadioAsync().get();
}
} catch (const winrt::hresult_error &error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": unknown error.";
LOG(ERROR) << __func__ << ": unknown error.";
}
}
// Synchronously sets the status of the BluetoothAdapter to 'status', and
// returns true if the operation was a success.
bool BluetoothAdapter::SetStatus(Status status) {
NEARBY_LOGS(ERROR) << __func__ << ": Set Bluetooth radio status to "
<< (status == Status::kEnabled ? "On" : "Off");
LOG(ERROR) << __func__ << ": Set Bluetooth radio status to "
<< (status == Status::kEnabled ? "On" : "Off");
if (windows_bluetooth_radio_ == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": No Bluetooth radio on this device.";
LOG(ERROR) << __func__ << ": No Bluetooth radio on this device.";
return false;
}
@@ -119,25 +120,23 @@ bool BluetoothAdapter::SetStatus(Status status) {
if (status == Status::kDisabled &&
(radio_state == RadioState::Unknown || radio_state == RadioState::Off ||
radio_state == RadioState::Disabled)) {
NEARBY_LOGS(INFO)
<< __func__
<< ": Skip set radio status kDisabled due to requested state is "
"already kDisabled.";
LOG(INFO) << __func__
<< ": Skip set radio status kDisabled due to requested state is "
"already kDisabled.";
return true;
}
if (status == Status::kEnabled && radio_state == RadioState::On) {
NEARBY_LOGS(INFO)
<< __func__
<< ": Skip set radio status kEnabled due to requested state is "
"already kEnabled.";
LOG(INFO) << __func__
<< ": Skip set radio status kEnabled due to requested state is "
"already kEnabled.";
return true;
}
if (!FeatureFlags::GetInstance().GetFlags().enable_set_radio_state) {
NEARBY_LOGS(INFO) << __func__
<< ": Attempt to set the radio state while "
"FeatureFlags::enable_set_radio_state is false.";
LOG(INFO) << __func__
<< ": Attempt to set the radio state while "
"FeatureFlags::enable_set_radio_state is false.";
return false;
}
@@ -151,22 +150,19 @@ bool BluetoothAdapter::SetStatus(Status status) {
windows_bluetooth_radio_.SetStateAsync(RadioState::On).get();
}
} catch (const winrt::hresult_error &ex) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to set Bluetooth radio state to "
<< (status == Status::kDisabled ? "kDisabled."
: "kEnabled.")
<< "Exception: " << ex.code() << ": "
<< winrt::to_string(ex.message());
LOG(ERROR) << __func__ << ": Failed to set Bluetooth radio state to "
<< (status == Status::kDisabled ? "kDisabled." : "kEnabled.")
<< "Exception: " << ex.code() << ": "
<< winrt::to_string(ex.message());
return false;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": unknown error.";
LOG(ERROR) << __func__ << ": unknown error.";
return false;
}
NEARBY_LOGS(INFO) << __func__ << ": Successfully set the radio state to "
<< (status == Status::kDisabled ? "kDisabled."
: "kEnabled.");
LOG(INFO) << __func__ << ": Successfully set the radio state to "
<< (status == Status::kDisabled ? "kDisabled." : "kEnabled.");
return true;
}
@@ -174,7 +170,7 @@ bool BluetoothAdapter::SetStatus(Status status) {
// Status::Value::kEnabled.
bool BluetoothAdapter::IsEnabled() const {
if (windows_bluetooth_radio_ == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": No Bluetooth radio on this device.";
LOG(ERROR) << __func__ << ": No Bluetooth radio on this device.";
return false;
}
try {
@@ -182,14 +178,14 @@ bool BluetoothAdapter::IsEnabled() const {
// https://docs.microsoft.com/en-us/uwp/api/windows.devices.radios.radio.state?view=winrt-20348
return windows_bluetooth_radio_.State() == RadioState::On;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": exception:" << exception.what();
LOG(ERROR) << __func__ << ": exception:" << exception.what();
return false;
} catch (const winrt::hresult_error &ex) {
NEARBY_LOGS(ERROR) << __func__ << ": exception:" << ex.code() << ": "
<< winrt::to_string(ex.message());
LOG(ERROR) << __func__ << ": exception:" << ex.code() << ": "
<< winrt::to_string(ex.message());
return false;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": unknown error.";
LOG(ERROR) << __func__ << ": unknown error.";
return false;
}
}
@@ -198,7 +194,7 @@ bool BluetoothAdapter::IsEnabled() const {
// Advertising
bool BluetoothAdapter::IsExtendedAdvertisingSupported() const {
if (windows_bluetooth_adapter_ == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": No Bluetooth adapter on this device.";
LOG(ERROR) << __func__ << ": No Bluetooth adapter on this device.";
return false;
}
try {
@@ -207,14 +203,14 @@ bool BluetoothAdapter::IsExtendedAdvertisingSupported() const {
// https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothadapter.isextendedadvertisingsupported?view=winrt-22621
return windows_bluetooth_adapter_.IsExtendedAdvertisingSupported();
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": exception:" << exception.what();
LOG(ERROR) << __func__ << ": exception:" << exception.what();
return false;
} catch (const winrt::hresult_error &ex) {
NEARBY_LOGS(ERROR) << __func__ << ": exception:" << ex.code() << ": "
<< winrt::to_string(ex.message());
LOG(ERROR) << __func__ << ": exception:" << ex.code() << ": "
<< winrt::to_string(ex.message());
return false;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": unknown error.";
LOG(ERROR) << __func__ << ": unknown error.";
return false;
}
}
@@ -222,7 +218,7 @@ bool BluetoothAdapter::IsExtendedAdvertisingSupported() const {
// Returns true if the Bluetooth hardware supports BLE Central Role
bool BluetoothAdapter::IsCentralRoleSupported() const {
if (windows_bluetooth_adapter_ == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": No Bluetooth adapter on this device.";
LOG(ERROR) << __func__ << ": No Bluetooth adapter on this device.";
return false;
}
try {
@@ -230,14 +226,14 @@ bool BluetoothAdapter::IsCentralRoleSupported() const {
// https://learn.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothadapter.iscentralrolesupported?view=winrt-22621
return windows_bluetooth_adapter_.IsCentralRoleSupported();
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": exception:" << exception.what();
LOG(ERROR) << __func__ << ": exception:" << exception.what();
return false;
} catch (const winrt::hresult_error &ex) {
NEARBY_LOGS(ERROR) << __func__ << ": exception:" << ex.code() << ": "
<< winrt::to_string(ex.message());
LOG(ERROR) << __func__ << ": exception:" << ex.code() << ": "
<< winrt::to_string(ex.message());
return false;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": unknown error.";
LOG(ERROR) << __func__ << ": unknown error.";
return false;
}
}
@@ -245,7 +241,7 @@ bool BluetoothAdapter::IsCentralRoleSupported() const {
// Returns true if the Bluetooth hardware supports BLE Peripheral Role
bool BluetoothAdapter::IsPeripheralRoleSupported() const {
if (windows_bluetooth_adapter_ == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": No Bluetooth adapter on this device.";
LOG(ERROR) << __func__ << ": No Bluetooth adapter on this device.";
return false;
}
try {
@@ -253,14 +249,14 @@ bool BluetoothAdapter::IsPeripheralRoleSupported() const {
// https://learn.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothadapter.isperipheralrolesupported?view=winrt-22621
return windows_bluetooth_adapter_.IsPeripheralRoleSupported();
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": exception:" << exception.what();
LOG(ERROR) << __func__ << ": exception:" << exception.what();
return false;
} catch (const winrt::hresult_error &ex) {
NEARBY_LOGS(ERROR) << __func__ << ": exception:" << ex.code() << ": "
<< winrt::to_string(ex.message());
LOG(ERROR) << __func__ << ": exception:" << ex.code() << ": "
<< winrt::to_string(ex.message());
return false;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": unknown error.";
LOG(ERROR) << __func__ << ": unknown error.";
return false;
}
}
@@ -268,7 +264,7 @@ bool BluetoothAdapter::IsPeripheralRoleSupported() const {
// Returns true if the Bluetooth hardware supports BLE
bool BluetoothAdapter::IsLowEnergySupported() const {
if (windows_bluetooth_adapter_ == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": No Bluetooth adapter on this device.";
LOG(ERROR) << __func__ << ": No Bluetooth adapter on this device.";
return false;
}
try {
@@ -276,14 +272,14 @@ bool BluetoothAdapter::IsLowEnergySupported() const {
// https://learn.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothadapter.islowenergysupported?view=winrt-22621
return windows_bluetooth_adapter_.IsLowEnergySupported();
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": exception:" << exception.what();
LOG(ERROR) << __func__ << ": exception:" << exception.what();
return false;
} catch (const winrt::hresult_error &ex) {
NEARBY_LOGS(ERROR) << __func__ << ": exception:" << ex.code() << ": "
<< winrt::to_string(ex.message());
LOG(ERROR) << __func__ << ": exception:" << ex.code() << ": "
<< winrt::to_string(ex.message());
return false;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": unknown error.";
LOG(ERROR) << __func__ << ": unknown error.";
return false;
}
}
@@ -320,13 +316,13 @@ void BluetoothAdapter::RestoreRadioNameIfNecessary() {
auto settings_file =
nearby::api::ImplementationPlatform::CreateInputFile(full_path, 0);
if (settings_file == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to create input file.";
LOG(ERROR) << __func__ << ": Failed to create input file.";
return;
}
auto total_size = settings_file->GetTotalSize();
if (total_size == 0) {
NEARBY_LOGS(WARNING) << __func__ << ": No data for local settings.";
LOG(WARNING) << __func__ << ": No data for local settings.";
return;
}
@@ -336,7 +332,7 @@ void BluetoothAdapter::RestoreRadioNameIfNecessary() {
settings_file->Close();
if (!raw_local_settings.ok()) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to read data file.";
LOG(ERROR) << __func__ << ": Failed to read data file.";
return;
}
@@ -344,12 +340,11 @@ void BluetoothAdapter::RestoreRadioNameIfNecessary() {
json::parse(raw_local_settings.GetResult().data(), nullptr, false);
if (local_settings.is_discarded()) {
NEARBY_LOGS(ERROR) << __func__ << ": Invalid local settings data.";
LOG(ERROR) << __func__ << ": Invalid local settings data.";
return;
}
NEARBY_VLOG(1) << __func__
<< ": loaded settings: " << local_settings.dump();
VLOG(1) << __func__ << ": loaded settings: " << local_settings.dump();
LocalSettings settings = local_settings.get<LocalSettings>();
@@ -358,10 +353,10 @@ void BluetoothAdapter::RestoreRadioNameIfNecessary() {
/* persist= */ true);
}
} catch (const winrt::hresult_error &ex) {
NEARBY_LOGS(ERROR) << __func__ << ": exception:" << ex.code() << ": "
<< winrt::to_string(ex.message());
LOG(ERROR) << __func__ << ": exception:" << ex.code() << ": "
<< winrt::to_string(ex.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": unknown error.";
LOG(ERROR) << __func__ << ": unknown error.";
}
}
@@ -369,9 +364,8 @@ void BluetoothAdapter::StoreRadioNames(absl::string_view original_radio_name,
absl::string_view nearby_radio_name) {
try {
if (original_radio_name.empty() || nearby_radio_name.empty()) {
NEARBY_LOGS(ERROR)
<< __func__
<< ":Failed to save radio names due to invalid parameters.";
LOG(ERROR) << __func__
<< ":Failed to save radio names due to invalid parameters.";
return;
}
@@ -383,7 +377,7 @@ void BluetoothAdapter::StoreRadioNames(absl::string_view original_radio_name,
nearby::api::ImplementationPlatform::CreateOutputFile(full_path);
if (settings_file == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to create output file.";
LOG(ERROR) << __func__ << ": Failed to create output file.";
return;
}
@@ -392,18 +386,18 @@ void BluetoothAdapter::StoreRadioNames(absl::string_view original_radio_name,
json encoded_local_settings;
to_json(encoded_local_settings, local_settings);
NEARBY_VLOG(1) << __func__
<< ": saved settings: " << encoded_local_settings.dump();
VLOG(1) << __func__
<< ": saved settings: " << encoded_local_settings.dump();
ByteArray data(encoded_local_settings.dump());
settings_file->Write(data);
settings_file->Close();
} catch (const winrt::hresult_error &ex) {
NEARBY_LOGS(ERROR) << __func__ << ": exception:" << ex.code() << ": "
<< winrt::to_string(ex.message());
LOG(ERROR) << __func__ << ": exception:" << ex.code() << ": "
<< winrt::to_string(ex.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": unknown error.";
LOG(ERROR) << __func__ << ": unknown error.";
}
}
@@ -417,8 +411,8 @@ std::string BluetoothAdapter::GetName() const {
std::optional<std::string> adapter_instance_id =
GetGenericBluetoothAdapterInstanceID();
if (!adapter_instance_id.has_value()) {
NEARBY_LOGS(ERROR)
<< __func__ << ": Failed to get Generic Bluetooth Adapter InstanceID";
LOG(ERROR) << __func__
<< ": Failed to get Generic Bluetooth Adapter InstanceID";
return std::string();
}
@@ -484,18 +478,18 @@ bool BluetoothAdapter::SetName(absl::string_view name, bool persist) {
StoreRadioNames(GetName(), name);
}
if (name.size() > 248 * sizeof(char)) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to set name for bluetooth adapter because "
"the name exceeded the 248 bytes limit for Windows.";
LOG(ERROR) << __func__
<< ": Failed to set name for bluetooth adapter because "
"the name exceeded the 248 bytes limit for Windows.";
return false;
}
if (name.size() > kAndroidDiscoverableBluetoothNameMaxLength * sizeof(char)) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to set name for bluetooth adapter because "
"Android cannot discover Windows bluetooth device "
"name that exceeded the 37 bytes limit (11 "
"characters in EndpointInfo).";
LOG(ERROR) << __func__
<< ": Failed to set name for bluetooth adapter because "
"Android cannot discover Windows bluetooth device "
"name that exceeded the 37 bytes limit (11 "
"characters in EndpointInfo).";
device_name_ = std::string(name);
return true;
}
@@ -503,9 +497,9 @@ bool BluetoothAdapter::SetName(absl::string_view name, bool persist) {
device_name_ = std::nullopt;
if (registry_bluetooth_adapter_name_ == name) {
NEARBY_LOGS(INFO) << __func__
<< ": Tried to set name for bluetooth adapter to the "
"same name again.";
LOG(INFO) << __func__
<< ": Tried to set name for bluetooth adapter to the "
"same name again.";
return true;
}
@@ -513,8 +507,8 @@ bool BluetoothAdapter::SetName(absl::string_view name, bool persist) {
GetGenericBluetoothAdapterInstanceID();
if (!adapter_instance_id.has_value()) {
NEARBY_LOGS(ERROR)
<< __func__ << ": Failed to get Generic Bluetooth Adapter InstanceID";
LOG(ERROR) << __func__
<< ": Failed to get Generic Bluetooth Adapter InstanceID";
return false;
}
@@ -538,7 +532,7 @@ bool BluetoothAdapter::SetName(absl::string_view name, bool persist) {
StringFromGUID2(guid, guid_ole_str, guid_ole_str_size);
if (conversionResult == 0) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to convert guid to string";
LOG(ERROR) << __func__ << ": Failed to convert guid to string";
return false;
}
std::string guid_str;
@@ -601,9 +595,8 @@ bool BluetoothAdapter::SetName(absl::string_view name, bool persist) {
find_and_replace(instance_id_modified.data(), "\\", "#");
char empty[0];
size_t file_name_size =
absl::SNPrintF(empty, 0, "\\\\.\\%s#%s", instance_id_modified.c_str(),
guid_str.c_str());
size_t file_name_size = absl::SNPrintF(
empty, 0, "\\\\.\\%s#%s", instance_id_modified.c_str(), guid_str.c_str());
std::string file_name;
file_name.reserve(file_name_size + 1);
@@ -630,8 +623,8 @@ bool BluetoothAdapter::SetName(absl::string_view name, bool persist) {
// access right. This parameter can be NULL.
if (hDevice == INVALID_HANDLE_VALUE) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to open device. Error code: "
<< GetLastError();
LOG(ERROR) << __func__
<< ": Failed to open device. Error code: " << GetLastError();
return false;
}
@@ -660,9 +653,8 @@ bool BluetoothAdapter::SetName(absl::string_view name, bool persist) {
// key.
if (status != ERROR_SUCCESS) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to open registry key. Error code: "
<< status;
LOG(ERROR) << __func__
<< ": Failed to open registry key. Error code: " << status;
return false;
}
@@ -688,9 +680,8 @@ bool BluetoothAdapter::SetName(absl::string_view name, bool persist) {
}
if (status != ERROR_SUCCESS) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to set/delete registry key. Error code: "
<< status;
LOG(ERROR) << __func__
<< ": Failed to set/delete registry key. Error code: " << status;
return false;
}
@@ -720,10 +711,9 @@ bool BluetoothAdapter::SetName(absl::string_view name, bool persist) {
&bytes, // A pointer to a variable that receives the size of the
// data stored in the output buffer, in bytes.
NULL)) { // A pointer to an OVERLAPPED structure.
NEARBY_LOGS(ERROR)
<< __func__
<< ": Failed to update radio module local name. Error code: "
<< GetLastError();
LOG(ERROR) << __func__
<< ": Failed to update radio module local name. Error code: "
<< GetLastError();
return false;
}
@@ -757,8 +747,8 @@ void BluetoothAdapter::process_error() {
break;
}
NEARBY_LOGS(ERROR) << __func__ << ": Failed to convert guid to string "
<< errorResult << " Error code:" << errorMessageID;
LOG(ERROR) << __func__ << ": Failed to convert guid to string " << errorResult
<< " Error code:" << errorMessageID;
}
void BluetoothAdapter::find_and_replace(char *source, const char *strFind,
@@ -792,8 +782,8 @@ BluetoothAdapter::GetGenericBluetoothAdapterInstanceID() const {
SetupDiGetClassDevsA(&GUID_DEVCLASS_BLUETOOTH, NULL, NULL, DIGCF_PRESENT);
if (hDevInfo == INVALID_HANDLE_VALUE) {
NEARBY_LOGS(ERROR) << __func__
<< ": Could not find BluetoothDevice on this machine";
LOG(ERROR) << __func__
<< ": Could not find BluetoothDevice on this machine";
return std::nullopt;
}
@@ -825,8 +815,7 @@ BluetoothAdapter::GetGenericBluetoothAdapterInstanceID() const {
}
}
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to get the generic bluetooth adapter id";
LOG(ERROR) << __func__ << ": Failed to get the generic bluetooth adapter id";
SetupDiDestroyDeviceInfoList(hDevInfo);
return std::nullopt;
}
@@ -834,21 +823,21 @@ BluetoothAdapter::GetGenericBluetoothAdapterInstanceID() const {
// Returns BT MAC address assigned to this adapter.
std::string BluetoothAdapter::GetMacAddress() const {
if (windows_bluetooth_adapter_ == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": No Bluetooth adapter on this device.";
LOG(ERROR) << __func__ << ": No Bluetooth adapter on this device.";
return "";
}
try {
return uint64_to_mac_address_string(
windows_bluetooth_adapter_.BluetoothAddress());
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": exception:" << exception.what();
LOG(ERROR) << __func__ << ": exception:" << exception.what();
return "";
} catch (const winrt::hresult_error &ex) {
NEARBY_LOGS(ERROR) << __func__ << ": exception:" << ex.code() << ": "
<< winrt::to_string(ex.message());
LOG(ERROR) << __func__ << ": exception:" << ex.code() << ": "
<< winrt::to_string(ex.message());
return "";
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": unknown error.";
LOG(ERROR) << __func__ << ": unknown error.";
return "";
}
}
@@ -874,9 +863,8 @@ std::string BluetoothAdapter::GetNameFromRegistry(PHKEY hKey) const {
// size of the buffer pointed to by the lpData
// parameter, in bytes.
if (status != ERROR_SUCCESS) {
NEARBY_LOGS(ERROR)
<< __func__
<< ": Failed to get the required size of the local name buffer";
LOG(ERROR) << __func__
<< ": Failed to get the required size of the local name buffer";
return "";
}
unsigned char *local_name = new unsigned char[local_name_size];
@@ -914,7 +902,7 @@ std::string BluetoothAdapter::GetNameFromComputerName() const {
return std::string(computer_name);
}
NEARBY_LOGS(ERROR) << __func__ << ": Failed to get any computer name";
LOG(ERROR) << __func__ << ": Failed to get any computer name";
return "";
}
@@ -86,8 +86,8 @@ RfcommDeviceService BluetoothDevice::GetRfcommServiceForIdAsync(
}
try {
NEARBY_LOGS(INFO) << __func__ << ": Get RF services for service id:"
<< winrt::to_string(serviceId.AsString());
LOG(INFO) << __func__ << ": Get RF services for service id:"
<< winrt::to_string(serviceId.AsString());
RfcommDeviceServicesResult rfcomm_device_services = nullptr;
// Try to get service from un cached mode.
@@ -101,13 +101,12 @@ RfcommDeviceService BluetoothDevice::GetRfcommServiceForIdAsync(
rfcomm_device_services = rfcomm_device_services_async.GetResults();
break;
case winrt::Windows::Foundation::AsyncStatus::Started:
NEARBY_LOGS(ERROR)
<< __func__
<< ": Failed to get RfcommDeviceService due to timeout.";
LOG(ERROR) << __func__
<< ": Failed to get RfcommDeviceService due to timeout.";
rfcomm_device_services_async.Cancel();
return nullptr;
default:
NEARBY_LOGS(ERROR)
LOG(ERROR)
<< __func__
<< ": Failed to get RfcommDeviceService due to unknown reasons.";
return nullptr;
@@ -115,35 +114,33 @@ RfcommDeviceService BluetoothDevice::GetRfcommServiceForIdAsync(
if (rfcomm_device_services != nullptr &&
rfcomm_device_services.Services().Size() > 0) {
NEARBY_LOGS(INFO) << __func__ << ": Get "
<< rfcomm_device_services.Services().Size()
<< " services without cache.";
LOG(INFO) << __func__ << ": Get "
<< rfcomm_device_services.Services().Size()
<< " services without cache.";
// found the matched service.
for (auto rfcomm_device_service : rfcomm_device_services.Services()) {
if (rfcomm_device_service.Device() != nullptr &&
winrt::to_string(rfcomm_device_service.Device().DeviceId()) ==
id_) {
NEARBY_LOGS(INFO)
<< __func__ << ": Found service from no-cache mode.";
LOG(INFO) << __func__ << ": Found service from no-cache mode.";
return rfcomm_device_service;
}
}
}
NEARBY_LOGS(ERROR)
<< __func__
<< ": Failed to get RfcommDeviceService due to no any services.";
LOG(ERROR) << __func__
<< ": Failed to get RfcommDeviceService due to no any services.";
return nullptr;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to get RfcommDeviceService: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Failed to get RfcommDeviceService: " << exception.what();
return nullptr;
} catch (const winrt::hresult_error& ex) {
NEARBY_LOGS(ERROR) << __func__ << ": RfcommDeviceService: " << ex.code()
<< ", error message: " << winrt::to_string(ex.message());
LOG(ERROR) << __func__ << ": RfcommDeviceService: " << ex.code()
<< ", error message: " << winrt::to_string(ex.message());
return nullptr;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
return nullptr;
}
}
@@ -154,8 +151,8 @@ RfcommDeviceService BluetoothDevice::GetRfcommServiceForIdWithRetryAsync(
int check_service_count = 0;
while (check_service_count < kCheckBluetoothServiceMaxTimes) {
try {
NEARBY_LOGS(INFO) << __func__ << ": Get RF services for service id:"
<< winrt::to_string(serviceId.AsString());
LOG(INFO) << __func__ << ": Get RF services for service id:"
<< winrt::to_string(serviceId.AsString());
RfcommDeviceServicesResult rfcomm_device_services = nullptr;
// Try to get service from un cached mode.
@@ -169,13 +166,12 @@ RfcommDeviceService BluetoothDevice::GetRfcommServiceForIdWithRetryAsync(
rfcomm_device_services = rfcomm_device_services_async.GetResults();
break;
case winrt::Windows::Foundation::AsyncStatus::Started:
NEARBY_LOGS(ERROR)
<< __func__
<< ": Failed to get RfcommDeviceService due to timeout.";
LOG(ERROR) << __func__
<< ": Failed to get RfcommDeviceService due to timeout.";
rfcomm_device_services_async.Cancel();
return nullptr;
default:
NEARBY_LOGS(ERROR)
LOG(ERROR)
<< __func__
<< ": Failed to get RfcommDeviceService due to unknown reasons.";
return nullptr;
@@ -183,16 +179,15 @@ RfcommDeviceService BluetoothDevice::GetRfcommServiceForIdWithRetryAsync(
if (rfcomm_device_services != nullptr &&
rfcomm_device_services.Services().Size() > 0) {
NEARBY_LOGS(INFO) << __func__ << ": Get "
<< rfcomm_device_services.Services().Size()
<< " services without cache.";
LOG(INFO) << __func__ << ": Get "
<< rfcomm_device_services.Services().Size()
<< " services without cache.";
// found the matched service.
for (auto rfcomm_device_service : rfcomm_device_services.Services()) {
if (rfcomm_device_service.Device() != nullptr &&
winrt::to_string(rfcomm_device_service.Device().DeviceId()) ==
id_) {
NEARBY_LOGS(INFO)
<< __func__ << ": Found service from no-cache mode.";
LOG(INFO) << __func__ << ": Found service from no-cache mode.";
return rfcomm_device_service;
}
}
@@ -200,24 +195,23 @@ RfcommDeviceService BluetoothDevice::GetRfcommServiceForIdWithRetryAsync(
++check_service_count;
absl::SleepFor(kCheckBluetoothServiceInterval);
NEARBY_LOGS(ERROR) << __func__ << ": No any services at "
<< check_service_count << "th check.";
LOG(ERROR) << __func__ << ": No any services at " << check_service_count
<< "th check.";
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to get RfcommDeviceService: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Failed to get RfcommDeviceService: " << exception.what();
return nullptr;
} catch (const winrt::hresult_error& ex) {
NEARBY_LOGS(ERROR) << __func__ << ": RfcommDeviceService: " << ex.code()
<< ", error message: "
<< winrt::to_string(ex.message());
LOG(ERROR) << __func__ << ": RfcommDeviceService: " << ex.code()
<< ", error message: " << winrt::to_string(ex.message());
return nullptr;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
return nullptr;
}
}
NEARBY_LOGS(ERROR) << __func__ << ": Failed to get RfcommDeviceService.";
LOG(ERROR) << __func__ << ": Failed to get RfcommDeviceService.";
return nullptr;
}
@@ -87,20 +87,20 @@ void DumpDeviceInformation(
for (const auto& property : properties) {
if (property.Key() == L"System.ItemNameDisplay") {
NEARBY_LOGS(INFO) << "System.ItemNameDisplay: "
<< InspectableReader::ReadString(property.Value());
LOG(INFO) << "System.ItemNameDisplay: "
<< InspectableReader::ReadString(property.Value());
} else if (property.Key() == L"System.Devices.Aep.CanPair") {
NEARBY_LOGS(INFO) << "System.Devices.Aep.CanPair: "
<< InspectableReader::ReadBoolean(property.Value());
LOG(INFO) << "System.Devices.Aep.CanPair: "
<< InspectableReader::ReadBoolean(property.Value());
} else if (property.Key() == L"System.Devices.Aep.IsPaired") {
NEARBY_LOGS(INFO) << "System.Devices.Aep.IsPaired: "
<< InspectableReader::ReadBoolean(property.Value());
LOG(INFO) << "System.Devices.Aep.IsPaired: "
<< InspectableReader::ReadBoolean(property.Value());
} else if (property.Key() == L"System.Devices.Aep.IsPresent") {
NEARBY_LOGS(INFO) << "System.Devices.Aep.IsPresent: "
<< InspectableReader::ReadBoolean(property.Value());
LOG(INFO) << "System.Devices.Aep.IsPresent: "
<< InspectableReader::ReadBoolean(property.Value());
} else if (property.Key() == L"System.Devices.Aep.DeviceAddress") {
NEARBY_LOGS(INFO) << "System.Devices.Aep.DeviceAddress: "
<< InspectableReader::ReadString(property.Value());
LOG(INFO) << "System.Devices.Aep.DeviceAddress: "
<< InspectableReader::ReadString(property.Value());
}
}
}
@@ -121,12 +121,11 @@ BluetoothClassicMedium::~BluetoothClassicMedium() {}
void BluetoothClassicMedium::OnScanModeChanged(
BluetoothAdapter::ScanMode scan_mode) {
NEARBY_LOGS(INFO) << __func__
<< ": OnScanModeChanged is called with scanMode: "
<< static_cast<int>(scan_mode);
LOG(INFO) << __func__ << ": OnScanModeChanged is called with scanMode: "
<< static_cast<int>(scan_mode);
if (scan_mode == scan_mode_) {
NEARBY_LOGS(INFO) << __func__ << ": No change of scan mode.";
LOG(INFO) << __func__ << ": No change of scan mode.";
return;
}
@@ -142,12 +141,12 @@ void BluetoothClassicMedium::OnScanModeChanged(
}
if (is_radio_discoverable_ == radio_discoverable) {
NEARBY_LOGS(INFO) << __func__ << ": No change of radio discovery.";
LOG(INFO) << __func__ << ": No change of radio discovery.";
return;
}
if (rfcomm_provider_ == nullptr) {
NEARBY_LOGS(WARNING) << __func__ << ": No advertising.";
LOG(WARNING) << __func__ << ": No advertising.";
return;
}
@@ -158,23 +157,22 @@ void BluetoothClassicMedium::OnScanModeChanged(
is_radio_discoverable_ = radio_discoverable;
return;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__
<< ": OnScanModeChanged exception: " << exception.what();
LOG(ERROR) << __func__
<< ": OnScanModeChanged exception: " << exception.what();
return;
} catch (const winrt::hresult_error& ex) {
NEARBY_LOGS(ERROR) << __func__
<< ": OnScanModeChanged exception: " << ex.code() << ": "
<< winrt::to_string(ex.message());
LOG(ERROR) << __func__ << ": OnScanModeChanged exception: " << ex.code()
<< ": " << winrt::to_string(ex.message());
return;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
return;
}
}
bool BluetoothClassicMedium::StartDiscovery(
BluetoothClassicMedium::DiscoveryCallback discovery_callback) {
NEARBY_LOGS(INFO) << "StartDiscovery is called.";
LOG(INFO) << "StartDiscovery is called.";
bool result = false;
discovery_callback_ = std::move(discovery_callback);
@@ -187,7 +185,7 @@ bool BluetoothClassicMedium::StartDiscovery(
}
bool BluetoothClassicMedium::StopDiscovery() {
NEARBY_LOGS(INFO) << "StopDiscovery is called.";
LOG(INFO) << "StopDiscovery is called.";
bool result = false;
@@ -234,14 +232,14 @@ void BluetoothClassicMedium::InitializeDeviceWatcher() {
device_watcher_.Removed(
{this, &BluetoothClassicMedium::DeviceWatcher_Removed});
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": InitializeDeviceWatcher exception: "
<< exception.what();
LOG(ERROR) << __func__
<< ": InitializeDeviceWatcher exception: " << exception.what();
} catch (const winrt::hresult_error& ex) {
NEARBY_LOGS(ERROR) << __func__
<< ": InitializeDeviceWatcher exception: " << ex.code()
<< ": " << winrt::to_string(ex.message());
LOG(ERROR) << __func__
<< ": InitializeDeviceWatcher exception: " << ex.code() << ": "
<< winrt::to_string(ex.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
}
}
@@ -249,9 +247,9 @@ std::unique_ptr<api::BluetoothSocket> BluetoothClassicMedium::ConnectToService(
api::BluetoothDevice& remote_device, const std::string& service_uuid,
CancellationFlag* cancellation_flag) {
try {
NEARBY_LOGS(INFO) << "ConnectToService is called.";
LOG(INFO) << "ConnectToService is called.";
if (service_uuid.empty()) {
NEARBY_LOGS(ERROR) << __func__ << ": service_uuid not specified.";
LOG(ERROR) << __func__ << ": service_uuid not specified.";
return nullptr;
}
@@ -263,15 +261,14 @@ std::unique_ptr<api::BluetoothSocket> BluetoothClassicMedium::ConnectToService(
// Must check for valid pattern as the guid constructor will throw on an
// invalid format
if (!std::regex_match(service_uuid, pattern)) {
NEARBY_LOGS(ERROR) << __func__
<< ": invalid service_uuid: " << service_uuid;
LOG(ERROR) << __func__ << ": invalid service_uuid: " << service_uuid;
return nullptr;
}
winrt::guid service(service_uuid);
if (cancellation_flag == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": cancellation_flag not specified.";
LOG(ERROR) << __func__ << ": cancellation_flag not specified.";
return nullptr;
}
@@ -280,8 +277,8 @@ std::unique_ptr<api::BluetoothSocket> BluetoothClassicMedium::ConnectToService(
if (remote_device_to_connect_ == nullptr ||
remote_device_to_connect_->GetId().empty()) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to get remote device from MAC address.";
LOG(ERROR) << __func__
<< ": Failed to get remote device from MAC address.";
return nullptr;
}
@@ -289,8 +286,8 @@ std::unique_ptr<api::BluetoothSocket> BluetoothClassicMedium::ConnectToService(
winrt::to_hstring(remote_device_to_connect_->GetId());
if (!HaveAccess(device_id)) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to gain access to device: "
<< winrt::to_string(device_id);
LOG(ERROR) << __func__ << ": Failed to gain access to device: "
<< winrt::to_string(device_id);
return nullptr;
}
@@ -301,14 +298,14 @@ std::unique_ptr<api::BluetoothSocket> BluetoothClassicMedium::ConnectToService(
.GetFlags()
.skip_service_discovery_before_connecting_to_rfcomm &&
!CheckSdp(requested_service)) {
NEARBY_LOGS(ERROR) << __func__ << ": Invalid SDP.";
LOG(ERROR) << __func__ << ": Invalid SDP.";
return nullptr;
}
auto rfcomm_socket = std::make_unique<BluetoothSocket>();
if (cancellation_flag->Cancelled()) {
NEARBY_LOGS(INFO)
LOG(INFO)
<< __func__
<< ": Bluetooth Classic socket connection cancelled for device: "
<< winrt::to_string(device_id) << ", service: " << service_uuid;
@@ -328,25 +325,25 @@ std::unique_ptr<api::BluetoothSocket> BluetoothClassicMedium::ConnectToService(
} catch (std::exception exception) {
// We will log and eat the exception since the caller
// expects nullptr if it fails
NEARBY_LOGS(ERROR) << __func__ << ": Exception connecting bluetooth async: "
<< exception.what();
LOG(ERROR) << __func__ << ": Exception connecting bluetooth async: "
<< exception.what();
return nullptr;
} catch (const winrt::hresult_error& ex) {
NEARBY_LOGS(ERROR) << __func__
<< ": Exception connecting bluetooth async, error code: "
<< ex.code()
<< ", error message: " << winrt::to_string(ex.message());
LOG(ERROR) << __func__
<< ": Exception connecting bluetooth async, error code: "
<< ex.code()
<< ", error message: " << winrt::to_string(ex.message());
return nullptr;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
return nullptr;
}
}
std::unique_ptr<api::BluetoothPairing> BluetoothClassicMedium::CreatePairing(
api::BluetoothDevice& remote_device) {
NEARBY_VLOG(1) << __func__ << ": Start to createPairing with device: "
<< remote_device.GetMacAddress();
VLOG(1) << __func__ << ": Start to createPairing with device: "
<< remote_device.GetMacAddress();
try {
winrt::Windows::Devices::Bluetooth::BluetoothDevice bluetooth_device =
winrt::Windows::Devices::Bluetooth::BluetoothDevice::
@@ -360,18 +357,15 @@ std::unique_ptr<api::BluetoothPairing> BluetoothClassicMedium::CreatePairing(
return std::make_unique<BluetoothPairing>(bluetooth_device,
custom_pairing);
}
NEARBY_VLOG(1) << __func__
<< ": Failed to get DeviceInformationCustomPairing.";
VLOG(1) << __func__ << ": Failed to get DeviceInformationCustomPairing.";
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << " : Failed to create pairing. exception: "
<< exception.what();
LOG(ERROR) << __func__ << " : Failed to create pairing. exception: "
<< exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to create pairing. WinRT exception: "
<< error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": Failed to create pairing. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
}
return nullptr;
}
@@ -416,13 +410,13 @@ bool BluetoothClassicMedium::CheckSdp(RfcommDeviceService requested_service) {
// https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.rfcomm.rfcommdeviceservice.getsdprawattributesasync?view=winrt-20348
try {
if (requested_service == nullptr) {
NEARBY_LOGS(WARNING) << __func__ << ": Request service is empty.";
LOG(WARNING) << __func__ << ": Request service is empty.";
return false;
}
auto attributes = requested_service.GetSdpRawAttributesAsync().get();
if (!attributes.HasKey(Constants::SdpServiceNameAttributeId)) {
NEARBY_LOGS(ERROR) << __func__ << ": Missing SdpServiceNameAttributeId.";
LOG(ERROR) << __func__ << ": Missing SdpServiceNameAttributeId.";
return false;
}
@@ -432,14 +426,13 @@ bool BluetoothClassicMedium::CheckSdp(RfcommDeviceService requested_service) {
auto attribute_type = attribute_reader.ReadByte();
if (attribute_type != Constants::SdpServiceNameAttributeType) {
NEARBY_LOGS(ERROR) << __func__
<< ": Missing SdpServiceNameAttributeType.";
LOG(ERROR) << __func__ << ": Missing SdpServiceNameAttributeType.";
return false;
}
return true;
} catch (...) {
NEARBY_LOGS(ERROR) << "Failed to get SDP information.";
LOG(ERROR) << "Failed to get SDP information.";
return false;
}
}
@@ -456,15 +449,15 @@ bool BluetoothClassicMedium::CheckSdp(RfcommDeviceService requested_service) {
std::unique_ptr<api::BluetoothServerSocket>
BluetoothClassicMedium::ListenForService(const std::string& service_name,
const std::string& service_uuid) {
NEARBY_LOGS(INFO) << "ListenForService is called with service name: "
<< service_name << ".";
LOG(INFO) << "ListenForService is called with service name: " << service_name
<< ".";
if (service_uuid.empty()) {
NEARBY_LOGS(ERROR) << __func__ << ": service_uuid was empty.";
LOG(ERROR) << __func__ << ": service_uuid was empty.";
return nullptr;
}
if (service_name.empty()) {
NEARBY_LOGS(ERROR) << __func__ << ": service_name was empty.";
LOG(ERROR) << __func__ << ": service_name was empty.";
return nullptr;
}
@@ -473,15 +466,14 @@ BluetoothClassicMedium::ListenForService(const std::string& service_name,
scan_mode_ = bluetooth_adapter_.GetScanMode();
NEARBY_LOGS(INFO) << __func__
<< ": scan_mode: " << static_cast<int>(scan_mode_);
LOG(INFO) << __func__ << ": scan_mode: " << static_cast<int>(scan_mode_);
bool radio_discoverable =
scan_mode_ == BluetoothAdapter::ScanMode::kConnectableDiscoverable;
bool result = StartAdvertising(radio_discoverable);
if (!result) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to start listening.";
LOG(ERROR) << __func__ << ": Failed to start listening.";
return nullptr;
}
@@ -493,8 +485,8 @@ api::BluetoothDevice* BluetoothClassicMedium::GetRemoteDevice(
auto it = mac_address_to_bluetooth_device_map_.find(mac_address);
if (it == mac_address_to_bluetooth_device_map_.end()) {
NEARBY_LOGS(WARNING) << __func__ << ": Bluetooth device " << mac_address
<< " is not in list. create it";
LOG(WARNING) << __func__ << ": Bluetooth device " << mac_address
<< " is not in list. create it";
auto bluetooth_device = std::make_unique<BluetoothDevice>(mac_address);
mac_address_to_bluetooth_device_map_[mac_address] =
@@ -502,8 +494,8 @@ api::BluetoothDevice* BluetoothClassicMedium::GetRemoteDevice(
return mac_address_to_bluetooth_device_map_[mac_address].get();
}
NEARBY_LOGS(INFO) << __func__ << ": Bluetooth device " << mac_address
<< " is in cache";
LOG(INFO) << __func__ << ": Bluetooth device " << mac_address
<< " is in cache";
return it->second.get();
}
@@ -511,9 +503,8 @@ api::BluetoothDevice* BluetoothClassicMedium::GetRemoteDevice(
bool BluetoothClassicMedium::StartScanning() {
if (!IsWatcherStarted()) {
if (device_watcher_ == nullptr) {
NEARBY_LOGS(ERROR)
<< __func__
<< ": Failed to start scanning due to no available watcher.";
LOG(ERROR) << __func__
<< ": Failed to start scanning due to no available watcher.";
return false;
}
@@ -532,9 +523,8 @@ bool BluetoothClassicMedium::StartScanning() {
}
}
NEARBY_LOGS(ERROR)
<< __func__
<< ": Attempted to start scanning when watcher already started.";
LOG(ERROR) << __func__
<< ": Attempted to start scanning when watcher already started.";
return false;
}
@@ -543,15 +533,14 @@ bool BluetoothClassicMedium::StopScanning() {
device_watcher_.Stop();
return true;
}
NEARBY_LOGS(ERROR)
<< __func__
<< ": Attempted to stop scanning when watcher already stopped.";
LOG(ERROR) << __func__
<< ": Attempted to stop scanning when watcher already stopped.";
return false;
}
winrt::fire_and_forget BluetoothClassicMedium::DeviceWatcher_Added(
DeviceWatcher sender, DeviceInformation device_info) {
NEARBY_LOGS(INFO) << "Device added " << winrt::to_string(device_info.Id());
LOG(INFO) << "Device added " << winrt::to_string(device_info.Id());
IMapView<winrt::hstring, IInspectable> properties = device_info.Properties();
DumpDeviceInformation(properties);
@@ -561,32 +550,30 @@ winrt::fire_and_forget BluetoothClassicMedium::DeviceWatcher_Added(
// If device no item name, ignore it.
if (!properties.HasKey(L"System.ItemNameDisplay")) {
NEARBY_LOGS(WARNING) << __func__ << ": Ignore the Bluetooth device "
<< winrt::to_string(device_info.Id())
<< " due to no name.";
LOG(WARNING) << __func__ << ": Ignore the Bluetooth device "
<< winrt::to_string(device_info.Id()) << " due to no name.";
return winrt::fire_and_forget();
}
if (properties.Lookup(L"System.ItemNameDisplay") == nullptr) {
NEARBY_LOGS(WARNING) << __func__ << ": Ignore the Bluetooth device "
<< winrt::to_string(device_info.Id())
<< " due to empty name.";
LOG(WARNING) << __func__ << ": Ignore the Bluetooth device "
<< winrt::to_string(device_info.Id()) << " due to empty name.";
return winrt::fire_and_forget();
}
// If device doesn't support pair, ignore it.
if (!properties.HasKey(L"System.Devices.Aep.CanPair")) {
NEARBY_LOGS(WARNING) << __func__ << ": Ignore the Bluetooth device "
<< winrt::to_string(device_info.Id())
<< " due to no pair property.";
LOG(WARNING) << __func__ << ": Ignore the Bluetooth device "
<< winrt::to_string(device_info.Id())
<< " due to no pair property.";
return winrt::fire_and_forget();
}
if (!InspectableReader::ReadBoolean(
properties.Lookup(L"System.Devices.Aep.CanPair"))) {
NEARBY_LOGS(WARNING) << __func__ << ": Ignore the Bluetooth device "
<< winrt::to_string(device_info.Id())
<< " due to not support pair.";
LOG(WARNING) << __func__ << ": Ignore the Bluetooth device "
<< winrt::to_string(device_info.Id())
<< " due to not support pair.";
return winrt::fire_and_forget();
}
@@ -605,8 +592,8 @@ winrt::fire_and_forget BluetoothClassicMedium::DeviceWatcher_Added(
// Add to our internal list if necessary
if (it != mac_address_to_bluetooth_device_map_.end()) {
// We're already tracking this one
NEARBY_LOGS(WARNING) << __func__ << ": Bluetooth device " << mac_address
<< " is alreay added.";
LOG(WARNING) << __func__ << ": Bluetooth device " << mac_address
<< " is alreay added.";
return winrt::fire_and_forget();
}
@@ -616,8 +603,8 @@ winrt::fire_and_forget BluetoothClassicMedium::DeviceWatcher_Added(
mac_address_to_bluetooth_device_map_[mac_address] =
std::move(bluetooth_device);
NEARBY_LOGS(INFO) << __func__ << ": Notifying bluetooth device "
<< mac_address << " added";
LOG(INFO) << __func__ << ": Notifying bluetooth device " << mac_address
<< " added";
if (discovery_callback_.device_discovered_cb != nullptr) {
discovery_callback_.device_discovered_cb(
*mac_address_to_bluetooth_device_map_[mac_address]);
@@ -640,15 +627,14 @@ winrt::fire_and_forget BluetoothClassicMedium::DeviceWatcher_Updated(
auto it = mac_address_to_bluetooth_device_map_.find(mac_address);
if (it == mac_address_to_bluetooth_device_map_.end()) {
NEARBY_LOGS(WARNING) << __func__ << ": Bluetooth device " << mac_address
<< " is not in list.";
LOG(WARNING) << __func__ << ": Bluetooth device " << mac_address
<< " is not in list.";
return winrt::fire_and_forget();
}
NEARBY_LOGS(INFO)
<< "Device updated name: "
<< mac_address_to_bluetooth_device_map_[mac_address]->GetName() << " ("
<< mac_address << ")";
LOG(INFO) << "Device updated name: "
<< mac_address_to_bluetooth_device_map_[mac_address]->GetName()
<< " (" << mac_address << ")";
IMapView<winrt::hstring, IInspectable> properties =
device_update_info.Properties();
DumpDeviceInformation(properties);
@@ -665,14 +651,12 @@ winrt::fire_and_forget BluetoothClassicMedium::DeviceWatcher_Updated(
properties.Lookup(L"System.ItemNameDisplay"));
if (it->second->GetName() == new_device_name) {
NEARBY_LOGS(INFO)
<< "Device name is same as old name, ignore the update.";
LOG(INFO) << "Device name is same as old name, ignore the update.";
} else {
it->second->SetName(new_device_name);
NEARBY_LOGS(INFO)
<< "Updated device name:"
<< mac_address_to_bluetooth_device_map_[mac_address]->GetName();
LOG(INFO) << "Updated device name:"
<< mac_address_to_bluetooth_device_map_[mac_address]->GetName();
discovery_callback_.device_name_changed_cb(
*mac_address_to_bluetooth_device_map_[mac_address]);
@@ -683,9 +667,9 @@ winrt::fire_and_forget BluetoothClassicMedium::DeviceWatcher_Updated(
if (properties.HasKey(L"System.Devices.Aep.IsPaired")) {
bool new_paired_status = InspectableReader::ReadBoolean(
properties.Lookup(L"System.Devices.Aep.IsPaired"));
NEARBY_LOGS(INFO) << __func__
<< ": Notifying device paired changed: " << std::boolalpha
<< new_paired_status;
LOG(INFO) << __func__
<< ": Notifying device paired changed: " << std::boolalpha
<< new_paired_status;
for (auto& observer : observers_.GetObservers()) {
observer->DevicePairedChanged(
*mac_address_to_bluetooth_device_map_[mac_address],
@@ -704,7 +688,7 @@ winrt::fire_and_forget BluetoothClassicMedium::DeviceWatcher_Removed(
.get();
if (native_bluetooth_device == nullptr) {
NEARBY_LOGS(WARNING) << __func__ << ": cannot get native bluetooth device.";
LOG(WARNING) << __func__ << ": cannot get native bluetooth device.";
return winrt::fire_and_forget();
}
@@ -713,21 +697,20 @@ winrt::fire_and_forget BluetoothClassicMedium::DeviceWatcher_Removed(
auto it = mac_address_to_bluetooth_device_map_.find(mac_address);
if (it == mac_address_to_bluetooth_device_map_.end()) {
NEARBY_LOGS(WARNING) << __func__ << ": Bluetooth device " << mac_address
<< " is not in list.";
LOG(WARNING) << __func__ << ": Bluetooth device " << mac_address
<< " is not in list.";
return winrt::fire_and_forget();
}
NEARBY_LOGS(INFO)
<< "Device removed "
<< mac_address_to_bluetooth_device_map_[mac_address]->GetName() << " ("
<< mac_address << ")";
LOG(INFO) << "Device removed "
<< mac_address_to_bluetooth_device_map_[mac_address]->GetName()
<< " (" << mac_address << ")";
if (!IsWatcherStarted()) {
return winrt::fire_and_forget();
}
NEARBY_LOGS(INFO) << __func__ << ": Notifying bluetooth device removed";
LOG(INFO) << __func__ << ": Notifying bluetooth device removed";
if (discovery_callback_.device_lost_cb != nullptr) {
discovery_callback_.device_lost_cb(
*mac_address_to_bluetooth_device_map_[mac_address]);
@@ -764,23 +747,23 @@ bool BluetoothClassicMedium::IsWatcherRunning() {
}
bool BluetoothClassicMedium::StartAdvertising(bool radio_discoverable) {
NEARBY_LOGS(INFO) << __func__
<< ": StartAdvertising is called with radio_discoverable: "
<< radio_discoverable << ".";
LOG(INFO) << __func__
<< ": StartAdvertising is called with radio_discoverable: "
<< radio_discoverable << ".";
try {
if (rfcomm_provider_ != nullptr &&
is_radio_discoverable_ == radio_discoverable) {
NEARBY_LOGS(WARNING) << __func__
<< ": Ignore StartAdvertising due to no change to "
"current advertising.";
LOG(WARNING) << __func__
<< ": Ignore StartAdvertising due to no change to "
"current advertising.";
return true;
}
if (rfcomm_provider_ != nullptr && !StopAdvertising()) {
NEARBY_LOGS(WARNING) << __func__
<< ": Failed to StartAdvertising due to cannot stop "
"running advertising.";
LOG(WARNING) << __func__
<< ": Failed to StartAdvertising due to cannot stop "
"running advertising.";
return false;
}
@@ -795,9 +778,8 @@ bool BluetoothClassicMedium::StartAdvertising(bool radio_discoverable) {
raw_server_socket_ = server_socket_.get();
if (!server_socket_->listen()) {
NEARBY_LOGS(ERROR)
<< __func__
<< ": Failed to StartAdvertising due to cannot start socket.";
LOG(ERROR) << __func__
<< ": Failed to StartAdvertising due to cannot start socket.";
server_socket_->Close();
server_socket_ = nullptr;
rfcomm_provider_ = nullptr;
@@ -814,13 +796,13 @@ bool BluetoothClassicMedium::StartAdvertising(bool radio_discoverable) {
radio_discoverable);
is_radio_discoverable_ = radio_discoverable;
NEARBY_LOGS(INFO) << ": StartListening completed successfully.";
LOG(INFO) << ": StartListening completed successfully.";
return true;
} catch (std::exception exception) {
// We will log and eat the exception since the caller
// expects nullptr if it fails
NEARBY_LOGS(ERROR) << __func__ << ": Exception setting up for listen: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Exception setting up for listen: " << exception.what();
if (server_socket_ != nullptr) {
server_socket_->Close();
@@ -833,9 +815,8 @@ bool BluetoothClassicMedium::StartAdvertising(bool radio_discoverable) {
return false;
} catch (const winrt::hresult_error& ex) {
NEARBY_LOGS(ERROR) << __func__
<< ": Exception setting up for listen: " << ex.code()
<< ": " << winrt::to_string(ex.message());
LOG(ERROR) << __func__ << ": Exception setting up for listen: " << ex.code()
<< ": " << winrt::to_string(ex.message());
if (server_socket_ != nullptr) {
server_socket_->Close();
server_socket_ = nullptr;
@@ -847,7 +828,7 @@ bool BluetoothClassicMedium::StartAdvertising(bool radio_discoverable) {
return false;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
if (server_socket_ != nullptr) {
server_socket_->Close();
server_socket_ = nullptr;
@@ -862,12 +843,12 @@ bool BluetoothClassicMedium::StartAdvertising(bool radio_discoverable) {
}
bool BluetoothClassicMedium::StopAdvertising() {
NEARBY_LOGS(INFO) << __func__ << ": StopAdvertising is called";
LOG(INFO) << __func__ << ": StopAdvertising is called";
try {
if (rfcomm_provider_ == nullptr) {
NEARBY_LOGS(ERROR) << __func__
<< ": Ignore StopAdvertising due to no advertising.";
LOG(ERROR) << __func__
<< ": Ignore StopAdvertising due to no advertising.";
return true;
}
@@ -876,19 +857,18 @@ bool BluetoothClassicMedium::StopAdvertising() {
raw_server_socket_ = nullptr;
server_socket_ = nullptr;
NEARBY_LOGS(INFO) << ": StopAdvertising completed successfully.";
LOG(INFO) << ": StopAdvertising completed successfully.";
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__
<< ": StopAdvertising exception: " << exception.what();
LOG(ERROR) << __func__
<< ": StopAdvertising exception: " << exception.what();
return false;
} catch (const winrt::hresult_error& ex) {
NEARBY_LOGS(ERROR) << __func__
<< ": StopAdvertising exception: " << ex.code() << ": "
<< winrt::to_string(ex.message());
LOG(ERROR) << __func__ << ": StopAdvertising exception: " << ex.code()
<< ": " << winrt::to_string(ex.message());
return false;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
return false;
}
}
@@ -914,8 +894,7 @@ bool BluetoothClassicMedium::InitializeServiceSdpAttributes(
return true;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to InitializeServiceSdpAttributes.";
LOG(ERROR) << __func__ << ": Failed to InitializeServiceSdpAttributes.";
return false;
}
}
@@ -20,16 +20,20 @@
#include <memory>
#include <string>
#include "absl/functional/any_invocable.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "internal/platform/exception.h"
#include "internal/platform/implementation/bluetooth_classic.h"
#include "internal/platform/implementation/windows/bluetooth_classic_socket.h"
#include "internal/platform/logging.h"
namespace nearby {
namespace windows {
namespace {
using ::winrt::Windows::Networking::Sockets::StreamSocket;
using ::winrt::Windows::Networking::Sockets::SocketProtectionLevel;
using ::winrt::Windows::Networking::Sockets::SocketQualityOfService;
using ::winrt::Windows::Networking::Sockets::StreamSocket;
using ::winrt::Windows::Networking::Sockets::StreamSocketListener;
using ::winrt::Windows::Networking::Sockets::
StreamSocketListenerConnectionReceivedEventArgs;
@@ -48,7 +52,7 @@ BluetoothServerSocket::~BluetoothServerSocket() { Close(); }
// Once error is reported, it is permanent, and ServerSocket has to be closed.
std::unique_ptr<api::BluetoothSocket> BluetoothServerSocket::Accept() {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__ << ": Accept is called.";
LOG(INFO) << __func__ << ": Accept is called.";
while (!closed_ && pending_sockets_.empty()) {
cond_.Wait(&mutex_);
@@ -58,7 +62,7 @@ std::unique_ptr<api::BluetoothSocket> BluetoothServerSocket::Accept() {
StreamSocket bluetooth_socket = pending_sockets_.front();
pending_sockets_.pop_front();
NEARBY_LOGS(INFO) << __func__ << ": Accepted a remote connection.";
LOG(INFO) << __func__ << ": Accepted a remote connection.";
return std::make_unique<BluetoothSocket>(bluetooth_socket);
}
@@ -71,7 +75,7 @@ void BluetoothServerSocket::SetCloseNotifier(
Exception BluetoothServerSocket::Close() {
try {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__ << ": Close is called.";
LOG(INFO) << __func__ << ": Close is called.";
if (closed_) {
return {Exception::kSuccess};
@@ -95,23 +99,23 @@ Exception BluetoothServerSocket::Close() {
close_notifier_();
}
NEARBY_LOGS(INFO) << __func__ << ": Close completed succesfully.";
LOG(INFO) << __func__ << ": Close completed succesfully.";
return {Exception::kSuccess};
} catch (std::exception exception) {
closed_ = true;
cond_.SignalAll();
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
closed_ = true;
cond_.SignalAll();
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
closed_ = true;
cond_.SignalAll();
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -137,12 +141,12 @@ bool BluetoothServerSocket::listen() {
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
}
return false;
@@ -152,7 +156,7 @@ bool BluetoothServerSocket::listen() {
StreamSocketListener listener,
StreamSocketListenerConnectionReceivedEventArgs const& args) {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__ << ": Received connection.";
LOG(INFO) << __func__ << ": Received connection.";
if (closed_) {
return ::winrt::fire_and_forget{};
@@ -53,7 +53,7 @@ constexpr absl::Duration kConnectInterval = absl::Seconds(3);
BluetoothSocket::BluetoothSocket(StreamSocket stream_socket)
: windows_socket_(stream_socket) {
NEARBY_LOGS(INFO) << __func__ << ": Initialize bluetooth socket.";
LOG(INFO) << __func__ << ": Initialize bluetooth socket.";
native_bluetooth_device_ =
::winrt::Windows::Devices::Bluetooth::BluetoothDevice::FromHostNameAsync(
windows_socket_.Information().RemoteHostName())
@@ -61,8 +61,7 @@ BluetoothSocket::BluetoothSocket(StreamSocket stream_socket)
if (FeatureFlags::GetInstance()
.GetFlags()
.enable_bluetooth_connection_status_track) {
NEARBY_LOGS(INFO)
<< "Flag enable_bluetooth_connection_status_track is enabled.";
LOG(INFO) << "Flag enable_bluetooth_connection_status_track is enabled.";
connection_status_changed_token_ =
native_bluetooth_device_.ConnectionStatusChanged(
{this, &BluetoothSocket::Listener_ConnectionStatusChanged});
@@ -94,7 +93,7 @@ OutputStream& BluetoothSocket::GetOutputStream() { return output_stream_; }
// After this call object should be treated as not connected.
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
Exception BluetoothSocket::Close() {
NEARBY_LOGS(INFO) << __func__ << ": Close bluetooth socket.";
LOG(INFO) << __func__ << ": Close bluetooth socket.";
// The Close method aborts any pending operations and releases all unmanaged
// resources associated with the StreamSocket object, including the Input and
@@ -119,14 +118,14 @@ Exception BluetoothSocket::Close() {
is_bluetooth_socket_closed_ = true;
return {Exception::kSuccess};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -143,8 +142,8 @@ api::BluetoothDevice* BluetoothSocket::GetRemoteDevice() {
// service name.
bool BluetoothSocket::Connect(HostName connection_host_name,
::winrt::hstring connection_service_name) {
NEARBY_LOGS(INFO) << __func__ << ": start to connect to bluetooth service:"
<< winrt::to_string(connection_service_name);
LOG(INFO) << __func__ << ": start to connect to bluetooth service:"
<< winrt::to_string(connection_service_name);
if (nearby::NearbyFlags::GetInstance().GetBoolFlag(
platform::config_package_nearby::nearby_platform_feature::
@@ -164,15 +163,14 @@ bool BluetoothSocket::Connect(HostName connection_host_name,
return connect_result;
}
NEARBY_LOGS(WARNING) << __func__
<< ": Failed to connect bluetooth at the "
<< connect_called_count << "th call.";
LOG(WARNING) << __func__ << ": Failed to connect bluetooth at the "
<< connect_called_count << "th call.";
absl::SleepFor(kConnectInterval);
}
}
NEARBY_LOGS(WARNING) << __func__ << ": Failed to connect bluetooth";
LOG(WARNING) << __func__ << ": Failed to connect bluetooth";
return false;
}
@@ -185,15 +183,13 @@ ExceptionOr<ByteArray> BluetoothSocket::BluetoothInputStream::Read(
std::int64_t size) {
try {
if (size <= 0) {
NEARBY_LOGS(ERROR) << __func__
<< ": Invalid transmit packet size: " << size;
LOG(ERROR) << __func__ << ": Invalid transmit packet size: " << size;
return {Exception::kIo};
}
if (size > read_buffer_.Capacity()) {
NEARBY_LOGS(WARNING) << __func__
<< ": resize receive buffer to packet size: "
<< size;
LOG(WARNING) << __func__
<< ": resize receive buffer to packet size: " << size;
read_buffer_ = Buffer(size);
}
@@ -205,27 +201,27 @@ ExceptionOr<ByteArray> BluetoothSocket::BluetoothInputStream::Read(
.get();
if (ibuffer.Length() != size) {
NEARBY_LOGS(WARNING) << __func__ << ": Got " << ibuffer.Length()
<< " bytes of total " << size << " bytes.";
LOG(WARNING) << __func__ << ": Got " << ibuffer.Length()
<< " bytes of total " << size << " bytes.";
}
ByteArray data((char*)ibuffer.data(), ibuffer.Length());
return ExceptionOr(data);
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
Exception BluetoothSocket::BluetoothInputStream::Close() {
NEARBY_LOGS(INFO) << __func__ << ": Close bluetooth input stream.";
LOG(INFO) << __func__ << ": Close bluetooth input stream.";
try {
if (winrt_input_stream_ != nullptr) {
@@ -233,14 +229,14 @@ Exception BluetoothSocket::BluetoothInputStream::Close() {
}
return {Exception::kSuccess};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -253,9 +249,8 @@ BluetoothSocket::BluetoothOutputStream::BluetoothOutputStream(
Exception BluetoothSocket::BluetoothOutputStream::Write(const ByteArray& data) {
try {
if (data.size() > write_buffer_.Capacity()) {
NEARBY_LOGS(WARNING) << __func__
<< ": resize write buffer to packet size: "
<< data.size();
LOG(WARNING) << __func__
<< ": resize write buffer to packet size: " << data.size();
write_buffer_ = Buffer(data.size());
}
@@ -266,14 +261,14 @@ Exception BluetoothSocket::BluetoothOutputStream::Write(const ByteArray& data) {
winrt_output_stream_.WriteAsync(write_buffer_).get();
return {Exception::kSuccess};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -287,34 +282,34 @@ Exception BluetoothSocket::BluetoothOutputStream::Flush() {
winrt_output_stream_.FlushAsync().get();
return {Exception::kSuccess};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
Exception BluetoothSocket::BluetoothOutputStream::Close() {
NEARBY_LOGS(INFO) << __func__ << ": Close bluetooth output stream.";
LOG(INFO) << __func__ << ": Close bluetooth output stream.";
try {
if (winrt_output_stream_ != nullptr) {
winrt_output_stream_.Close();
}
return {Exception::kSuccess};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -323,18 +318,15 @@ bool BluetoothSocket::InternalConnect(HostName connection_host_name,
winrt::hstring connection_service_name) {
try {
if (connection_host_name == nullptr || connection_service_name.empty()) {
NEARBY_LOGS(ERROR)
<< __func__
<< ": Bluetooth socket connection failed. Attempting to "
"connect to empty HostName/MAC address or ServiceName.";
LOG(ERROR) << __func__
<< ": Bluetooth socket connection failed. Attempting to "
"connect to empty HostName/MAC address or ServiceName.";
return false;
}
NEARBY_LOGS(INFO) << __func__
<< ": Bluetooth socket connection to host name:"
<< winrt::to_string(connection_host_name.DisplayName())
<< ", service name:"
<< winrt::to_string(connection_service_name);
LOG(INFO) << __func__ << ": Bluetooth socket connection to host name:"
<< winrt::to_string(connection_host_name.DisplayName())
<< ", service name:" << winrt::to_string(connection_service_name);
windows_socket_ = winrt::Windows::Networking::Sockets::StreamSocket();
@@ -353,8 +345,7 @@ bool BluetoothSocket::InternalConnect(HostName connection_host_name,
if (FeatureFlags::GetInstance()
.GetFlags()
.enable_bluetooth_connection_status_track) {
NEARBY_LOGS(INFO)
<< "Flag enable_bluetooth_connection_status_track is enabled.";
LOG(INFO) << "Flag enable_bluetooth_connection_status_track is enabled.";
connection_status_changed_token_ =
native_bluetooth_device_.ConnectionStatusChanged(
{this, &BluetoothSocket::Listener_ConnectionStatusChanged});
@@ -366,19 +357,18 @@ bool BluetoothSocket::InternalConnect(HostName connection_host_name,
input_stream_ = BluetoothInputStream(windows_socket_.InputStream());
output_stream_ = BluetoothOutputStream(windows_socket_.OutputStream());
NEARBY_LOGS(INFO) << __func__
<< ": Bluetooth socket successfully connected to "
<< bluetooth_device_->GetName();
LOG(INFO) << __func__ << ": Bluetooth socket successfully connected to "
<< bluetooth_device_->GetName();
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return false;
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return false;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return false;
}
}
@@ -391,12 +381,10 @@ winrt::fire_and_forget BluetoothSocket::Listener_ConnectionStatusChanged(
// Based on the test, the args are empty, so cannot provide more information
// on the status change.
BluetoothConnectionStatus connection_status = device.ConnectionStatus();
NEARBY_LOGS(WARNING) << __func__
<< ": Bluetooth connection status changed to:"
<< ((connection_status ==
BluetoothConnectionStatus::Connected)
? "Connected"
: "Disconnected");
LOG(WARNING) << __func__ << ": Bluetooth connection status changed to:"
<< ((connection_status == BluetoothConnectionStatus::Connected)
? "Connected"
: "Disconnected");
return {};
}
@@ -53,7 +53,7 @@ BluetoothPairing::BluetoothPairing(
BluetoothDevice bluetooth_device,
DeviceInformationCustomPairing custom_pairing)
: bluetooth_device_(bluetooth_device), custom_pairing_(custom_pairing) {
NEARBY_VLOG(1) << __func__ << ": BluetoothPairing is created for device.";
VLOG(1) << __func__ << ": BluetoothPairing is created for device.";
}
BluetoothPairing::~BluetoothPairing() {
@@ -62,17 +62,17 @@ BluetoothPairing::~BluetoothPairing() {
std::exchange(pairing_requested_token_, {}));
}
CancelPairing();
NEARBY_VLOG(1) << __func__ << ": BluetoothPairing is destroyed for device.";
VLOG(1) << __func__ << ": BluetoothPairing is destroyed for device.";
}
bool BluetoothPairing::InitiatePairing(
api::BluetoothPairingCallback pairing_cb) {
NEARBY_VLOG(1) << __func__ << ": Start to initiate pairing process.";
VLOG(1) << __func__ << ": Start to initiate pairing process.";
try {
pairing_requested_token_ = custom_pairing_.PairingRequested(
{this, &BluetoothPairing::OnPairingRequested});
if (!pairing_requested_token_) {
NEARBY_VLOG(1) << __func__ << " Failed to registered pairing callback.";
VLOG(1) << __func__ << " Failed to registered pairing callback.";
return false;
}
pairing_callback_ = std::move(pairing_cb);
@@ -87,35 +87,32 @@ bool BluetoothPairing::InitiatePairing(
OnPair(pairing_result);
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to initiate pairing. exception: "
<< exception.what();
LOG(ERROR) << __func__ << ": Failed to initiate pairing. exception: "
<< exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to initiate pairing. WinRT exception: "
<< error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": Failed to initiate pairing. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
}
return false;
}
bool BluetoothPairing::FinishPairing(
std::optional<absl::string_view> pin_code) {
NEARBY_VLOG(1) << __func__ << "Start to finish pairing.";
VLOG(1) << __func__ << "Start to finish pairing.";
try {
if (!pairing_requested_) {
NEARBY_VLOG(1) << __func__ << "No pairing requested.";
VLOG(1) << __func__ << "No pairing requested.";
return false;
}
if (!pairing_deferral_) {
NEARBY_VLOG(1) << __func__ << "No ongoing pairing process.";
VLOG(1) << __func__ << "No ongoing pairing process.";
return false;
}
if (expecting_pin_code_) {
if (!pin_code.has_value()) {
NEARBY_LOGS(INFO) << __func__ << " Failed to get pin code";
LOG(INFO) << __func__ << " Failed to get pin code";
return false;
}
expecting_pin_code_ = false;
@@ -125,27 +122,25 @@ bool BluetoothPairing::FinishPairing(
pairing_requested_.Accept();
}
pairing_deferral_.Complete();
NEARBY_VLOG(1) << "Successfully finished pairing.";
VLOG(1) << "Successfully finished pairing.";
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to finish pairing. exception: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Failed to finish pairing. exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to finish pairing. WinRT exception: "
<< error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": Failed to finish pairing. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
}
return false;
}
bool BluetoothPairing::CancelPairing() {
NEARBY_VLOG(1) << __func__ << " Start to cancel ongoing pairing process.";
VLOG(1) << __func__ << " Start to cancel ongoing pairing process.";
try {
if (!pairing_deferral_) {
NEARBY_VLOG(1) << __func__ << "No ongoing pairing process.";
VLOG(1) << __func__ << "No ongoing pairing process.";
return true;
}
// There is no way to explicitly cancel an in-progress pairing on Windows as
@@ -156,47 +151,44 @@ bool BluetoothPairing::CancelPairing() {
// deferral is completed, will know that cancellation was the actual result.
was_cancelled_ = true;
pairing_deferral_.Close();
NEARBY_VLOG(1) << __func__ << "Canceled ongoing pairing process.";
VLOG(1) << __func__ << "Canceled ongoing pairing process.";
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to cancel ongoing pairing "
<< "process. exception: " << exception.what();
LOG(ERROR) << __func__ << ": Failed to cancel ongoing pairing "
<< "process. exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to cancel ongoing pairing process. "
<< "WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": Failed to cancel ongoing pairing process. "
<< "WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
}
return false;
}
bool BluetoothPairing::Unpair() {
NEARBY_VLOG(1) << __func__ << ": Start to unpair with remote device.";
VLOG(1) << __func__ << ": Start to unpair with remote device.";
try {
if (!IsPaired()) {
NEARBY_VLOG(1) << __func__ << " : Remote device Was not paired.";
VLOG(1) << __func__ << " : Remote device Was not paired.";
return true;
}
DeviceUnpairingResult unpairing_result =
bluetooth_device_.DeviceInformation().Pairing().UnpairAsync().get();
if (unpairing_result.Status() == DeviceUnpairingResultStatus::Unpaired) {
NEARBY_VLOG(1) << __func__ << ": Unpaired with remote device.";
VLOG(1) << __func__ << ": Unpaired with remote device.";
return true;
}
NEARBY_VLOG(1) << __func__ << ": Failed to unpaired with remote device.";
VLOG(1) << __func__ << ": Failed to unpaired with remote device.";
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to unpaired with device. exception: "
<< exception.what();
LOG(ERROR) << __func__ << ": Failed to unpaired with device. exception: "
<< exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to unpaired with device. WinRT exception: "
<< error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << __func__
<< ": Failed to unpaired with device. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
}
return false;
}
@@ -204,18 +196,17 @@ bool BluetoothPairing::Unpair() {
bool BluetoothPairing::IsPaired() {
try {
bool is_paired = bluetooth_device_.DeviceInformation().Pairing().IsPaired();
NEARBY_LOGS(INFO) << __func__ << (is_paired ? " True" : " False");
LOG(INFO) << __func__ << (is_paired ? " True" : " False");
return is_paired;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to get IsPaired. exception: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Failed to get IsPaired. exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to get IsPaired. WinRT exception: "
<< error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << __func__
<< ": Failed to get IsPaired. WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
}
return false;
}
@@ -223,7 +214,7 @@ bool BluetoothPairing::IsPaired() {
void BluetoothPairing::OnPairingRequested(
DeviceInformationCustomPairing custom_pairing,
DevicePairingRequestedEventArgs pairing_requested) {
NEARBY_VLOG(1) << __func__ << "Requested to pair.";
VLOG(1) << __func__ << "Requested to pair.";
try {
DevicePairingKinds pairing_kind = pairing_requested.PairingKind();
pairing_requested_ = pairing_requested;
@@ -231,40 +222,38 @@ void BluetoothPairing::OnPairingRequested(
api::PairingParams params;
switch (pairing_kind) {
case DevicePairingKinds::ProvidePin:
NEARBY_LOGS(INFO) << __func__ << "DevicePairingKind: RequestPinCode.";
LOG(INFO) << __func__ << "DevicePairingKind: RequestPinCode.";
expecting_pin_code_ = true;
params.pairing_type = PairingType::kRequestPin;
pairing_callback_.on_pairing_initiated_cb(params);
return;
case DevicePairingKinds::ConfirmOnly:
NEARBY_LOGS(INFO) << __func__ << "DevicePairingKind: ConfirmOnly.";
LOG(INFO) << __func__ << "DevicePairingKind: ConfirmOnly.";
params.pairing_type = PairingType::kConsent;
pairing_callback_.on_pairing_initiated_cb(params);
return;
case DevicePairingKinds::ConfirmPinMatch:
NEARBY_LOGS(INFO) << __func__
<< "DevicePairingKind: Confirm Pin Match.";
LOG(INFO) << __func__ << "DevicePairingKind: Confirm Pin Match.";
params.pairing_type = PairingType::kConfirmPasskey;
params.passkey = winrt::to_string(pairing_requested.Pin());
pairing_callback_.on_pairing_initiated_cb(params);
return;
default:
params.pairing_type = PairingType::kUnknown;
NEARBY_LOGS(INFO) << __func__ << "Unsupported DevicePairingKind:"
<< static_cast<int>(pairing_kind);
LOG(INFO) << __func__ << "Unsupported DevicePairingKind:"
<< static_cast<int>(pairing_kind);
break;
}
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to request to pair with device. exception: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Failed to request to pair with device. exception: "
<< exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR)
<< __func__
<< ": Failed to request to pair with device. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__
<< ": Failed to request to pair with device. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
}
pairing_callback_.on_pairing_error_cb(PairingError::kFailed);
}
@@ -272,8 +261,8 @@ void BluetoothPairing::OnPairingRequested(
void BluetoothPairing::OnPair(DevicePairingResult& pairing_result) {
try {
DevicePairingResultStatus status = pairing_result.Status();
NEARBY_LOGS(INFO) << __func__
<< "Pairing Result Status: " << static_cast<int>(status);
LOG(INFO) << __func__
<< "Pairing Result Status: " << static_cast<int>(status);
if (was_cancelled_ &&
status == DevicePairingResultStatus::RejectedByHandler) {
// See comment in CancelPairing() for explanation of why was_cancelled_
@@ -283,53 +272,52 @@ void BluetoothPairing::OnPair(DevicePairingResult& pairing_result) {
switch (status) {
case DevicePairingResultStatus::AlreadyPaired:
case DevicePairingResultStatus::Paired:
NEARBY_LOGS(ERROR) << __func__ << "Pairing Result Status: Paired.";
LOG(ERROR) << __func__ << "Pairing Result Status: Paired.";
pairing_callback_.on_paired_cb();
return;
case DevicePairingResultStatus::PairingCanceled:
NEARBY_LOGS(ERROR) << __func__
<< "Pairing Result Status: Pairing Canceled.";
LOG(ERROR) << __func__ << "Pairing Result Status: Pairing Canceled.";
pairing_callback_.on_pairing_error_cb(PairingError::kAuthCanceled);
return;
case DevicePairingResultStatus::AuthenticationFailure:
NEARBY_LOGS(ERROR) << __func__
<< "Pairing Result Status: Authentication Failure.";
LOG(ERROR) << __func__
<< "Pairing Result Status: Authentication Failure.";
pairing_callback_.on_pairing_error_cb(PairingError::kAuthFailed);
return;
case DevicePairingResultStatus::ConnectionRejected:
case DevicePairingResultStatus::RejectedByHandler:
NEARBY_LOGS(ERROR) << __func__
<< "Pairing Result Status: Authentication Rejected.";
LOG(ERROR) << __func__
<< "Pairing Result Status: Authentication Rejected.";
pairing_callback_.on_pairing_error_cb(PairingError::kAuthRejected);
return;
case DevicePairingResultStatus::AuthenticationTimeout:
NEARBY_LOGS(ERROR) << __func__
<< "Pairing Result Status: Authentication Timeout.";
LOG(ERROR) << __func__
<< "Pairing Result Status: Authentication Timeout.";
pairing_callback_.on_pairing_error_cb(PairingError::kAuthTimeout);
return;
case DevicePairingResultStatus::Failed:
NEARBY_LOGS(ERROR) << __func__ << "Pairing Result Status: Failed.";
LOG(ERROR) << __func__ << "Pairing Result Status: Failed.";
pairing_callback_.on_pairing_error_cb(PairingError::kFailed);
return;
case DevicePairingResultStatus::OperationAlreadyInProgress:
NEARBY_LOGS(ERROR) << __func__
<< "Pairing Result Status: Operation In Progress.";
LOG(ERROR) << __func__
<< "Pairing Result Status: Operation In Progress.";
pairing_callback_.on_pairing_error_cb(PairingError::kRepeatedAttempts);
return;
default:
break;
}
NEARBY_LOGS(ERROR) << __func__ << "Pairing Result Status: Failed.";
LOG(ERROR) << __func__ << "Pairing Result Status: Failed.";
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to get Pairing Result Status. exception: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Failed to get Pairing Result Status. exception: "
<< exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to get Pairing Result Status."
<< " WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": Failed to get Pairing Result Status."
<< " WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
}
pairing_callback_.on_pairing_error_cb(PairingError::kFailed);
}
@@ -59,8 +59,8 @@ std::optional<std::string> DeviceInfo::GetOsDeviceName() const {
// Get length of the computer name.
if (!GetComputerNameExW(ComputerNameDnsHostname, nullptr, &size)) {
if (GetLastError() != ERROR_MORE_DATA) {
NEARBY_LOGS(ERROR) << ": Failed to get device name size, error:"
<< GetLastError();
LOG(ERROR) << ": Failed to get device name size, error:"
<< GetLastError();
return std::nullopt;
}
}
@@ -71,7 +71,7 @@ std::optional<std::string> DeviceInfo::GetOsDeviceName() const {
return winrt::to_string(device_name_str);
}
NEARBY_LOGS(ERROR) << ": Failed to get device name, error:" << GetLastError();
LOG(ERROR) << ": Failed to get device name, error:" << GetLastError();
return std::nullopt;
}
@@ -97,8 +97,7 @@ std::optional<std::string> DeviceInfo::GetFullName() const {
UserAuthenticationStatus::LocallyAuthenticated)
.get();
if (users == nullptr) {
NEARBY_LOGS(ERROR) << __func__
<< ": Error retrieving locally authenticated user.";
LOG(ERROR) << __func__ << ": Error retrieving locally authenticated user.";
return std::nullopt;
}
@@ -112,15 +111,15 @@ std::optional<std::string> DeviceInfo::GetFullName() const {
current_user.GetPropertyAsync(KnownUserProperties::DisplayName());
IInspectable full_name_obj = full_name_obj_async.get();
if (full_name_obj == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": Error retrieving full name of user.";
LOG(ERROR) << __func__ << ": Error retrieving full name of user.";
return std::nullopt;
}
winrt::hstring full_name = full_name_obj.as<winrt::hstring>();
std::string full_name_str = winrt::to_string(full_name);
if (full_name_str.empty()) {
NEARBY_LOGS(ERROR)
<< __func__ << ": Error unboxing string value for full name of user.";
LOG(ERROR) << __func__
<< ": Error unboxing string value for full name of user.";
return std::nullopt;
}
@@ -140,8 +139,7 @@ std::optional<std::string> DeviceInfo::GetGivenName() const {
UserAuthenticationStatus::LocallyAuthenticated)
.get();
if (users == nullptr) {
NEARBY_LOGS(ERROR) << __func__
<< ": Error retrieving locally authenticated user.";
LOG(ERROR) << __func__ << ": Error retrieving locally authenticated user.";
return std::nullopt;
}
@@ -155,15 +153,15 @@ std::optional<std::string> DeviceInfo::GetGivenName() const {
current_user.GetPropertyAsync(KnownUserProperties::FirstName());
IInspectable given_name_obj = given_name_obj_async.get();
if (given_name_obj == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": Error retrieving first name of user.";
LOG(ERROR) << __func__ << ": Error retrieving first name of user.";
return std::nullopt;
}
winrt::hstring given_name = given_name_obj.as<winrt::hstring>();
std::string given_name_str = winrt::to_string(given_name);
if (given_name_str.empty()) {
NEARBY_LOGS(ERROR)
<< __func__ << ": Error unboxing string value for first name of user.";
LOG(ERROR) << __func__
<< ": Error unboxing string value for first name of user.";
return std::nullopt;
}
@@ -183,8 +181,7 @@ std::optional<std::string> DeviceInfo::GetLastName() const {
UserAuthenticationStatus::LocallyAuthenticated)
.get();
if (users == nullptr) {
NEARBY_LOGS(ERROR) << __func__
<< ": Error retrieving locally authenticated user.";
LOG(ERROR) << __func__ << ": Error retrieving locally authenticated user.";
return std::nullopt;
}
@@ -198,15 +195,15 @@ std::optional<std::string> DeviceInfo::GetLastName() const {
current_user.GetPropertyAsync(KnownUserProperties::LastName());
IInspectable last_name_obj = last_name_obj_async.get();
if (last_name_obj == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": Error retrieving last name of user.";
LOG(ERROR) << __func__ << ": Error retrieving last name of user.";
return std::nullopt;
}
winrt::hstring last_name = last_name_obj.as<winrt::hstring>();
std::string last_name_str = winrt::to_string(last_name);
if (last_name_str.empty()) {
NEARBY_LOGS(ERROR)
<< __func__ << ": Error unboxing string value for last name of user.";
LOG(ERROR) << __func__
<< ": Error unboxing string value for last name of user.";
return std::nullopt;
}
@@ -226,8 +223,7 @@ std::optional<std::string> DeviceInfo::GetProfileUserName() const {
UserAuthenticationStatus::LocallyAuthenticated)
.get();
if (users == nullptr) {
NEARBY_LOGS(ERROR) << __func__
<< ": Error retrieving locally authenticated user.";
LOG(ERROR) << __func__ << ": Error retrieving locally authenticated user.";
return std::nullopt;
}
@@ -241,17 +237,15 @@ std::optional<std::string> DeviceInfo::GetProfileUserName() const {
current_user.GetPropertyAsync(KnownUserProperties::AccountName());
IInspectable account_name_obj = account_name_obj_async.get();
if (account_name_obj == nullptr) {
NEARBY_LOGS(ERROR) << __func__
<< ": Error retrieving account name of user.";
LOG(ERROR) << __func__ << ": Error retrieving account name of user.";
return std::nullopt;
}
winrt::hstring account_name = account_name_obj.as<winrt::hstring>();
std::string account_name_string = winrt::to_string(account_name);
if (account_name_string.empty()) {
NEARBY_LOGS(ERROR)
<< __func__
<< ": Error unboxing string value for profile username of user.";
LOG(ERROR) << __func__
<< ": Error unboxing string value for profile username of user.";
return std::nullopt;
}
@@ -15,8 +15,10 @@
#include "internal/platform/implementation/windows/executor.h"
#include <cassert>
#include <cstdint>
#include "internal/platform/logging.h"
#include "internal/platform/runnable.h"
namespace nearby {
namespace windows {
@@ -32,13 +34,13 @@ Executor::Executor(int32_t max_concurrency)
void Executor::Execute(Runnable&& runnable) {
if (shut_down_) {
NEARBY_VLOG(1) << "Warning: " << __func__
<< ": Attempt to execute on a shut down pool.";
VLOG(1) << "Warning: " << __func__
<< ": Attempt to execute on a shut down pool.";
return;
}
if (runnable == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": Runnable was null.";
LOG(ERROR) << __func__ << ": Runnable was null.";
return;
}
@@ -88,7 +88,7 @@ ExceptionOr<ByteArray> IOFile::Read(std::int64_t size) {
}
return ExceptionOr<ByteArray>(ByteArray(buffer_.data(), num_bytes_read));
} catch (...) {
NEARBY_LOGS(ERROR) << "Fail to read";
LOG(ERROR) << "Fail to read";
return ExceptionOr<ByteArray>{Exception::kIo};
}
}
@@ -114,7 +114,7 @@ Exception IOFile::Write(const ByteArray& data) {
file_.flush();
return {file_.good() ? Exception::kSuccess : Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << "Fail to write";
LOG(ERROR) << "Fail to write";
return {Exception::kIo};
}
}
@@ -14,6 +14,7 @@
#include "internal/platform/implementation/windows/file_path.h"
// clang-format off
#include <windows.h>
#include <winver.h>
#include <PathCch.h>
@@ -23,6 +24,7 @@
#include <shlwapi.h>
#include <strsafe.h>
#include <wchar.h>
// clang-format on
#include <algorithm>
#include <cctype>
@@ -175,8 +177,8 @@ std::wstring FilePath::CreateOutputFileWithRename(std::wstring path) {
}
if (count > 0) {
NEARBY_LOGS(INFO) << "Renamed " << wstring_to_string(path) << " to "
<< wstring_to_string(target);
LOG(INFO) << "Renamed " << wstring_to_string(path) << " to "
<< wstring_to_string(target);
}
// The above leaves the file open, so close it.
@@ -214,9 +216,8 @@ std::wstring FilePath::MutateForbiddenPathElements(std::wstring& str) {
if (tmp_path_element.size() == 1 && tmp_path_element[0] == kDot) {
// Change the dot path name to an underscore.
tmp_path_element[0] = kReplacementChar;
NEARBY_LOGS(INFO) << "Renamed path element "
<< wstring_to_string(path_element) << " to "
<< wstring_to_string(tmp_path_element);
LOG(INFO) << "Renamed path element " << wstring_to_string(path_element)
<< " to " << wstring_to_string(tmp_path_element);
path_element[0] = kReplacementChar;
}
@@ -227,9 +228,8 @@ std::wstring FilePath::MutateForbiddenPathElements(std::wstring& str) {
while (std::find(forbidden.begin(), forbidden.end(), tmp_path_element) !=
forbidden.end()) {
tmp_path_element.insert(tmp_path_element.begin(), kReplacementChar);
NEARBY_LOGS(INFO) << "Renamed path element "
<< wstring_to_string(path_element) << " to "
<< wstring_to_string(tmp_path_element);
LOG(INFO) << "Renamed path element " << wstring_to_string(path_element)
<< " to " << wstring_to_string(tmp_path_element);
path_element.insert(path_element.begin(), kReplacementChar);
}
@@ -263,22 +263,22 @@ void FilePath::ReplaceInvalidCharacters(std::wstring& path) {
for (; it != path.end(); it++) {
// If 0 < character < 32, it's illegal, replace it
if (*it > 0 && *it < 32) {
NEARBY_LOGS(INFO) << "In path " << wstring_to_string(path)
<< " replaced \'" << std::string(1, *it) << "\' with \'"
<< std::string(1, kReplacementChar);
LOG(INFO) << "In path " << wstring_to_string(path) << " replaced \'"
<< std::string(1, *it) << "\' with \'"
<< std::string(1, kReplacementChar);
*it = kReplacementChar;
}
if (*it == 0) { // character is null
NEARBY_LOGS(INFO) << "In path " << wstring_to_string(path)
<< " replaced \'NULL\' with \'"
<< std::string(1, kReplacementChar) << "\'";
LOG(INFO) << "In path " << wstring_to_string(path)
<< " replaced \'NULL\' with \'"
<< std::string(1, kReplacementChar) << "\'";
*it = kReplacementChar;
}
for (auto illegal_character : kIllegalFileCharacters) {
if (*it == illegal_character) {
NEARBY_LOGS(INFO) << "In path " << wstring_to_string(path)
<< " replaced \'" << std::string(1, *it)
<< "\' with \'" << std::string(1, kReplacementChar);
LOG(INFO) << "In path " << wstring_to_string(path) << " replaced \'"
<< std::string(1, *it) << "\' with \'"
<< std::string(1, kReplacementChar);
*it = kReplacementChar;
}
}
@@ -22,6 +22,8 @@
#include "absl/strings/ascii.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "internal/platform/implementation/http_loader.h"
#include "internal/platform/logging.h"
namespace nearby {
@@ -202,8 +204,8 @@ absl::Status HttpLoader::ConnectWebServer() {
0); /*Flags*/
if (internet_handle_ == nullptr) {
NEARBY_LOGS(ERROR) << "Failed to open internet with error "
<< GetLastError() << ".";
LOG(ERROR) << "Failed to open internet with error " << GetLastError()
<< ".";
return absl::FailedPreconditionError(absl::StrCat(GetLastError()));
}
@@ -217,8 +219,8 @@ absl::Status HttpLoader::ConnectWebServer() {
0); /*Context*/
if (connect_handle_ == nullptr) {
NEARBY_LOGS(ERROR) << "Failed to connect remote web server with error "
<< GetLastError() << ".";
LOG(ERROR) << "Failed to connect remote web server with error "
<< GetLastError() << ".";
InternetCloseHandle(internet_handle_);
return absl::FailedPreconditionError(absl::StrCat(GetLastError()));
}
@@ -242,9 +244,8 @@ absl::Status HttpLoader::SendRequest() {
0);
if (request_handle_ == nullptr) {
NEARBY_LOGS(ERROR)
<< "Failed to open request to remote web server with error "
<< GetLastError() << ".";
LOG(ERROR) << "Failed to open request to remote web server with error "
<< GetLastError() << ".";
InternetCloseHandle(internet_handle_);
InternetCloseHandle(connect_handle_);
@@ -284,9 +285,8 @@ absl::Status HttpLoader::SendRequest() {
data_size); /*Data size*/
if (result == FALSE) {
NEARBY_LOGS(ERROR)
<< "Failed to send request to remote web server with error "
<< GetLastError() << ".";
LOG(ERROR) << "Failed to send request to remote web server with error "
<< GetLastError() << ".";
InternetCloseHandle(request_handle_);
InternetCloseHandle(connect_handle_);
InternetCloseHandle(internet_handle_);
@@ -334,9 +334,8 @@ absl::StatusOr<WebResponse> HttpLoader::ProcessResponse() {
web_response.body.append(buffer, read_size);
}
} else {
NEARBY_LOGS(ERROR)
<< "Failed to read response from remote web server with error "
<< GetLastError() << ".";
LOG(ERROR) << "Failed to read response from remote web server with error "
<< GetLastError() << ".";
InternetCloseHandle(request_handle_);
InternetCloseHandle(connect_handle_);
InternetCloseHandle(internet_handle_);
@@ -75,7 +75,6 @@
#include "internal/platform/implementation/windows/wifi.h"
#include "internal/platform/implementation/windows/wifi_hotspot.h"
#include "internal/platform/implementation/windows/wifi_lan.h"
#include "internal/platform/logging.h"
#include "internal/platform/os_name.h"
#include "internal/platform/payload_id.h"
@@ -14,6 +14,7 @@
#include "internal/platform/implementation/windows/preferences_manager.h"
#include <cstdint>
#include <filesystem> // NOLINT(build/c++17)
#include <memory>
#include <optional>
@@ -21,11 +22,16 @@
#include <string>
#include <vector>
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "nlohmann/json.hpp"
#include "nlohmann/json_fwd.hpp"
#include "internal/base/files.h"
#include "internal/platform/implementation/platform.h"
#include "internal/platform/implementation/preferences_manager.h"
#include "internal/platform/implementation/windows/preferences_repository.h"
#include "internal/platform/logging.h"
@@ -190,7 +196,7 @@ void PreferencesManager::Remove(absl::string_view key) {
// Writes data to storage.
bool PreferencesManager::Commit() {
if (!preferences_repository_->SavePreferences(value_)) {
NEARBY_LOGS(ERROR) << "Failed to save preference." << std::endl;
LOG(ERROR) << "Failed to save preference." << std::endl;
return false;
}
return true;
@@ -198,8 +204,8 @@ bool PreferencesManager::Commit() {
bool PreferencesManager::SetValue(absl::string_view key, const json& value) {
if (!value_.is_object()) {
NEARBY_LOGS(ERROR) << "Preferences is no longer an object! value_="
<< value_.dump(4);
LOG(ERROR) << "Preferences is no longer an object! value_="
<< value_.dump(4);
value_ = json::object();
}
@@ -215,8 +221,8 @@ template <typename T>
T PreferencesManager::GetValue(absl::string_view key,
const T& default_value) const {
if (!value_.is_object()) {
NEARBY_LOGS(ERROR) << "Preferences is no longer an object! value_="
<< value_.dump(4);
LOG(ERROR) << "Preferences is no longer an object! value_="
<< value_.dump(4);
return default_value;
}
@@ -231,8 +237,8 @@ template <typename T>
bool PreferencesManager::SetArrayValue(absl::string_view key,
absl::Span<const T> value) {
if (!value_.is_object()) {
NEARBY_LOGS(ERROR) << "Preferences is no longer an object! value_="
<< value_.dump(4);
LOG(ERROR) << "Preferences is no longer an object! value_="
<< value_.dump(4);
value_ = json::object();
}
@@ -255,8 +261,8 @@ std::vector<T> PreferencesManager::GetArrayValue(
std::vector<T> result;
if (!value_.is_object()) {
NEARBY_LOGS(ERROR) << "Preferences is no longer an object! value_="
<< value_.dump(4);
LOG(ERROR) << "Preferences is no longer an object! value_="
<< value_.dump(4);
for (const T& value : default_value) {
result.push_back(value);
@@ -41,26 +41,23 @@ constexpr absl::Duration kTimeOut = absl::Milliseconds(200);
constexpr char kPreferencesFilePath[] = "Google/Nearby/Sharing";
} // namespace
TEST(PreferencesManager, CorruptedConfigFile) {
std::filesystem::path settingsPath =
std::filesystem::temp_directory_path();
std::filesystem::path settingsPath = std::filesystem::temp_directory_path();
std::ofstream output_stream{settingsPath / "preferences.json"};
output_stream << "CORRUPTED" << std::endl;
NEARBY_LOGS(INFO) << "Loading preferences from: " << settingsPath.string();
LOG(INFO) << "Loading preferences from: " << settingsPath.string();
EXPECT_EQ(PreferencesManager(settingsPath.string()).GetInteger("data", 100),
100);
}
TEST(PreferencesManager, ValidConfigFile) {
std::filesystem::path settingsPath =
std::filesystem::temp_directory_path();
std::filesystem::path settingsPath = std::filesystem::temp_directory_path();
std::ofstream output_stream{settingsPath / "preferences.json"};
output_stream << "{\"data\":8, \"name\": \"Valid\"}" << std::endl;
output_stream.close();
NEARBY_LOGS(INFO) << "Loading preferences from: " << settingsPath.string();
LOG(INFO) << "Loading preferences from: " << settingsPath.string();
EXPECT_EQ(PreferencesManager(settingsPath.string()).GetInteger("data", 100),
8);
}
@@ -19,6 +19,7 @@
#include <fstream>
#include <optional>
#include "absl/synchronization/mutex.h"
#include "nlohmann/json.hpp"
#include "nlohmann/json_fwd.hpp"
#include "internal/base/files.h"
@@ -41,8 +42,8 @@ json PreferencesRepository::LoadPreferences() {
// The top level root should be an object, if it's not then something went
// wrong or the file was corrupted.
if (!preferences.value().is_object()) {
NEARBY_LOGS(ERROR) << "Preferences loaded was not a valid object: "
<< preferences.value().dump(4);
LOG(ERROR) << "Preferences loaded was not a valid object: "
<< preferences.value().dump(4);
return json::object();
}
@@ -50,17 +51,17 @@ json PreferencesRepository::LoadPreferences() {
return preferences.value();
}
NEARBY_LOGS(ERROR) << "Could not load preferences file, trying backup.";
LOG(ERROR) << "Could not load preferences file, trying backup.";
// In the future we should switch to using a transaction log or another
// stable method which doesn't pose a risk of losing settings
preferences = RestoreFromBackup();
if (preferences.has_value()) {
NEARBY_LOGS(ERROR) << "Successfully recovered from backup.";
LOG(ERROR) << "Successfully recovered from backup.";
return preferences.value();
}
NEARBY_LOGS(ERROR) << "Failed to load preferences file from back up.";
LOG(ERROR) << "Failed to load preferences file from back up.";
return json::object();
}
@@ -71,7 +72,7 @@ bool PreferencesRepository::SavePreferences(json preferences) {
std::filesystem::path path = path_;
if (!nearby::sharing::FileExists(path) &&
!nearby::sharing::CreateDirectories(path)) {
NEARBY_LOGS(ERROR) << "Failed to create preferences path.";
LOG(ERROR) << "Failed to create preferences path.";
return false;
}
@@ -80,9 +81,9 @@ bool PreferencesRepository::SavePreferences(json preferences) {
// Create a backup without moving the bytes on disk
if (nearby::sharing::FileExists(full_name)) {
NEARBY_LOGS(INFO) << "Making backup of preferences file.";
LOG(INFO) << "Making backup of preferences file.";
if (!nearby::sharing::Rename(full_name, full_name_backup)) {
NEARBY_LOGS(ERROR) << "Failed to rename preferences backup file.";
LOG(ERROR) << "Failed to rename preferences backup file.";
}
}
@@ -92,19 +93,19 @@ bool PreferencesRepository::SavePreferences(json preferences) {
// Make sure the file wasn't saved in a corrupted state
if (!AttemptLoad().has_value()) {
NEARBY_LOGS(ERROR) << "Preferences saved to disk in corrupted state. "
"Restoring from backup.";
LOG(ERROR) << "Preferences saved to disk in corrupted state. "
"Restoring from backup.";
if (!RestoreFromBackup().has_value()) {
NEARBY_LOGS(ERROR) << "Failed to restore preferences file.";
LOG(ERROR) << "Failed to restore preferences file.";
return false;
}
}
} catch (const std::exception& e) {
NEARBY_LOGS(ERROR) << "Failed to save preferences file: " << e.what();
LOG(ERROR) << "Failed to save preferences file: " << e.what();
return false;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
return false;
}
@@ -129,16 +130,16 @@ std::optional<json> PreferencesRepository::AttemptLoad() {
preferences_file.close();
if (preferences.is_discarded()) {
NEARBY_LOGS(ERROR) << "Preferences file corrupted.";
LOG(ERROR) << "Preferences file corrupted.";
return std::nullopt;
}
return preferences;
} catch (const std::exception& e) {
NEARBY_LOGS(ERROR) << "Exception while loading preferences: " << e.what();
LOG(ERROR) << "Exception while loading preferences: " << e.what();
return std::nullopt;
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
return std::nullopt;
}
}
@@ -149,16 +150,15 @@ std::optional<json> PreferencesRepository::RestoreFromBackup() {
std::filesystem::path full_name_backup = path / kPreferencesBackupFileName;
if (!nearby::sharing::FileExists(full_name_backup)) {
NEARBY_LOGS(WARNING)
<< "Backup requested but no backup preferences file found.";
LOG(WARNING) << "Backup requested but no backup preferences file found.";
return std::nullopt;
}
if (!nearby::sharing::Rename(full_name_backup, full_name)) {
NEARBY_LOGS(ERROR) << "Failed to rename preferences backup file.";
LOG(ERROR) << "Failed to rename preferences backup file.";
}
NEARBY_LOGS(INFO) << "Attempting load from backup preferences.";
LOG(INFO) << "Attempting load from backup preferences.";
return AttemptLoad();
}
@@ -44,16 +44,16 @@ std::shared_ptr<api::Cancelable> ScheduledExecutor::Schedule(
Runnable&& runnable, absl::Duration duration) {
if (use_task_scheduler_) {
if (shut_down_) {
NEARBY_LOGS(ERROR) << __func__
<< ": Attempt to Schedule on a shut down executor.";
LOG(ERROR) << __func__
<< ": Attempt to Schedule on a shut down executor.";
return nullptr;
}
return task_scheduler_.Schedule(std::move(runnable), duration);
} else {
if (shut_down_) {
NEARBY_LOGS(ERROR) << __func__
<< ": Attempt to Schedule on a shut down executor.";
LOG(ERROR) << __func__
<< ": Attempt to Schedule on a shut down executor.";
return nullptr;
}
@@ -79,8 +79,7 @@ std::shared_ptr<api::Cancelable> ScheduledExecutor::Schedule(
void ScheduledExecutor::Execute(Runnable&& runnable) {
if (shut_down_) {
NEARBY_LOGS(ERROR) << __func__
<< ": Attempt to Execute on a shut down executor.";
LOG(ERROR) << __func__ << ": Attempt to Execute on a shut down executor.";
return;
}
@@ -107,8 +106,7 @@ void ScheduledExecutor::Shutdown() {
return;
}
}
NEARBY_LOGS(ERROR) << __func__
<< ": Attempt to Shutdown on a shut down executor.";
LOG(ERROR) << __func__ << ": Attempt to Shutdown on a shut down executor.";
}
} // namespace windows
} // namespace nearby
@@ -24,6 +24,7 @@
#include "absl/base/const_init.h"
#include "absl/container/flat_hash_map.h"
#include "absl/functional/any_invocable.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "absl/synchronization/notification.h"
#include "internal/platform/implementation/windows/submittable_executor.h"
@@ -91,7 +92,7 @@ bool SessionManager::RegisterSessionListener(
absl::string_view listener_name,
absl::AnyInvocable<void(SessionState)> callback) {
absl::MutexLock lock(&session_mutex_);
NEARBY_LOGS(INFO) << __func__ << ": Registering listener: " << listener_name;
LOG(INFO) << __func__ << ": Registering listener: " << listener_name;
// Create session thread if no running thread.
if (session_thread_ == nullptr) {
@@ -114,38 +115,36 @@ bool SessionManager::RegisterSessionListener(
session_callbacks_->emplace(listener_name, std::move(callback));
listeners_.emplace(listener_name);
NEARBY_LOGS(INFO) << __func__ << ": Session listener: " << listener_name
<< " is registered.";
LOG(INFO) << __func__ << ": Session listener: " << listener_name
<< " is registered.";
return true;
}
bool SessionManager::UnregisterSessionListener(
absl::string_view listener_name) {
absl::MutexLock lock(&session_mutex_);
NEARBY_LOGS(INFO) << __func__
<< ": Unregistering listener: " << listener_name;
LOG(INFO) << __func__ << ": Unregistering listener: " << listener_name;
if (session_thread_ == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": No running listener.";
LOG(ERROR) << __func__ << ": No running listener.";
return false;
}
if (!session_callbacks_->contains(listener_name) ||
!listeners_.contains(listener_name)) {
NEARBY_LOGS(ERROR) << __func__
<< ": No listener with name:" << listener_name;
LOG(ERROR) << __func__ << ": No listener with name:" << listener_name;
return false;
}
session_callbacks_->erase(listener_name);
listeners_.erase(listener_name);
if (!session_callbacks_->empty()) {
NEARBY_LOGS(INFO) << __func__ << ": Session listener: " << listener_name
<< " is unregistered.";
LOG(INFO) << __func__ << ": Session listener: " << listener_name
<< " is unregistered.";
return true;
}
CleanUp();
NEARBY_LOGS(INFO) << __func__ << ": Session listener: " << listener_name
<< " is unregistered.";
LOG(INFO) << __func__ << ": Session listener: " << listener_name
<< " is unregistered.";
return true;
}
@@ -178,8 +177,7 @@ bool SessionManager::PreventSleep() const {
EXECUTION_STATE execution_state =
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
if (execution_state == 0) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to set execution state of the thread.";
LOG(ERROR) << __func__ << ": Failed to set execution state of the thread.";
return false;
}
return true;
@@ -188,16 +186,15 @@ bool SessionManager::PreventSleep() const {
bool SessionManager::AllowSleep() const {
EXECUTION_STATE execution_state = SetThreadExecutionState(ES_CONTINUOUS);
if (execution_state == 0) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to set execution state of the thread.";
LOG(ERROR) << __func__ << ": Failed to set execution state of the thread.";
return false;
}
return true;
}
void SessionManager::NotifySessionState(SessionState state) {
NEARBY_LOGS(INFO) << __func__
<< ": Notifying session state: " << static_cast<int>(state);
LOG(INFO) << __func__
<< ": Notifying session state: " << static_cast<int>(state);
if (state == SessionManager::SessionState::kLock) {
absl::MutexLock lock(&session_mutex_);
for (auto& it : *SessionManager::session_callbacks_) {
@@ -214,19 +211,18 @@ void SessionManager::NotifySessionState(SessionState state) {
void SessionManager::StartSession(absl::Notification& notification) {
session_hwnd_ = CreateNearbyWindow();
if (session_hwnd_ == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to create session Window.";
LOG(ERROR) << __func__ << ": Failed to create session Window.";
return;
}
if (!WTSRegisterSessionNotification(session_hwnd_, NOTIFY_FOR_THIS_SESSION)) {
NEARBY_LOGS(ERROR) << __func__
<< ":Failed to register session notification.";
LOG(ERROR) << __func__ << ":Failed to register session notification.";
return;
}
notification.Notify();
NEARBY_LOGS(INFO) << __func__ << ": Session thread started.";
LOG(INFO) << __func__ << ": Session thread started.";
// Main message loop
MSG msg = {};
@@ -237,17 +233,16 @@ void SessionManager::StartSession(absl::Notification& notification) {
}
if (!WTSUnRegisterSessionNotification(session_hwnd_)) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to register session notification.";
LOG(ERROR) << __func__ << ": Failed to register session notification.";
return;
}
if (!UnregisterClassA(/*lpClassName=*/kMessageWindowClass,
/*hInstance=*/(HINSTANCE)GetModuleHandle(nullptr))) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to unregister window class.";
LOG(ERROR) << __func__ << ": Failed to unregister window class.";
}
NEARBY_LOGS(INFO) << __func__ << ": Completed Message loop.";
LOG(INFO) << __func__ << ": Completed Message loop.";
}
void SessionManager::StopSession() {
@@ -14,9 +14,11 @@
#include "internal/platform/implementation/windows/submittable_executor.h"
#include <cstdint>
#include "internal/platform/implementation/windows/executor.h"
#include "internal/platform/logging.h"
#include "internal/platform/runnable.h"
namespace nearby {
namespace windows {
@@ -32,8 +34,8 @@ bool SubmittableExecutor::DoSubmit(Runnable&& wrapped_callable) {
return true;
}
NEARBY_LOGS(ERROR) << "Error: " << __func__
<< ": Attempt to DoSubmit on a shutdown executor.";
LOG(ERROR) << "Error: " << __func__
<< ": Attempt to DoSubmit on a shutdown executor.";
return false;
}
@@ -43,8 +45,8 @@ void SubmittableExecutor::Execute(Runnable&& runnable) {
if (!shut_down_) {
executor_->Execute(std::move(runnable));
} else {
NEARBY_LOGS(ERROR) << "Error: " << __func__
<< ": Attempt to Execute on a shutdown executor.";
LOG(ERROR) << "Error: " << __func__
<< ": Attempt to Execute on a shutdown executor.";
}
}
@@ -55,8 +57,8 @@ void SubmittableExecutor::Shutdown() {
shut_down_ = true;
}
NEARBY_LOGS(ERROR) << "Error: " << __func__
<< ": Attempt to Shutdown on a shutdown executor.";
LOG(ERROR) << "Error: " << __func__
<< ": Attempt to Shutdown on a shutdown executor.";
}
} // namespace windows
@@ -15,8 +15,13 @@
#ifndef PLATFORM_IMPL_WINDOWS_SUBMITTABLE_EXECUTOR_H_
#define PLATFORM_IMPL_WINDOWS_SUBMITTABLE_EXECUTOR_H_
#include <atomic>
#include <cstdint>
#include <memory>
#include "internal/platform/implementation/submittable_executor.h"
#include "internal/platform/implementation/windows/executor.h"
#include "internal/platform/runnable.h"
namespace nearby {
namespace windows {
@@ -28,7 +33,7 @@ namespace windows {
class SubmittableExecutor : public api::SubmittableExecutor {
public:
SubmittableExecutor();
SubmittableExecutor(int32_t maxConcurrancy);
explicit SubmittableExecutor(int32_t max_concurrancy);
~SubmittableExecutor() override = default;
// Submit a callable (with no delay).
@@ -37,12 +37,12 @@ void CALLBACK TimerRoutine(PVOID lpParam, BOOLEAN TimerOrWaitFired) {
} // namespace
TaskScheduler::TaskScheduler() {
NEARBY_LOGS(INFO) << __func__ << ": Created task scheduler: " << this;
LOG(INFO) << __func__ << ": Created task scheduler: " << this;
}
TaskScheduler::~TaskScheduler() {
Shutdown();
NEARBY_LOGS(INFO) << __func__ << ": Destroyed task scheduler: " << this;
LOG(INFO) << __func__ << ": Destroyed task scheduler: " << this;
}
std::shared_ptr<api::Cancelable> TaskScheduler::Schedule(
@@ -54,16 +54,15 @@ std::shared_ptr<api::Cancelable> TaskScheduler::Schedule(
Runnable&& runnable, absl::Duration duration,
absl::Duration repeat_interval) {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__
<< ": Scheduling task on task scheduler:" << this
<< ", duration: " << absl::ToInt64Milliseconds(duration)
<< "ms, repeat_interval: "
<< absl::ToInt64Milliseconds(repeat_interval) << "ms";
LOG(INFO) << __func__ << ": Scheduling task on task scheduler:" << this
<< ", duration: " << absl::ToInt64Milliseconds(duration)
<< "ms, repeat_interval: "
<< absl::ToInt64Milliseconds(repeat_interval) << "ms";
if (is_shutdown_) {
NEARBY_LOGS(ERROR) << __func__
<< ": Attempt to schedule task on a shut down task "
"scheduler: "
<< this;
LOG(ERROR) << __func__
<< ": Attempt to schedule task on a shut down task "
"scheduler: "
<< this;
return nullptr;
}
@@ -79,24 +78,23 @@ std::shared_ptr<api::Cancelable> TaskScheduler::Schedule(
task->runnable(),
absl::ToInt64Milliseconds(duration),
absl::ToInt64Milliseconds(repeat_interval), 0)) {
NEARBY_LOGS(ERROR)
<< __func__
<< ": Failed to create timer queue timer in task scheduler:" << this
<< " error: " << GetLastError();
LOG(ERROR) << __func__
<< ": Failed to create timer queue timer in task scheduler:"
<< this << " error: " << GetLastError();
return nullptr;
}
task->set_timer_handle(reinterpret_cast<intptr_t>(timer_handle));
scheduled_tasks_.insert({reinterpret_cast<intptr_t>(timer_handle), task});
NEARBY_LOGS(INFO) << __func__ << ": Scheduled task " << task.get()
<< " on task scheduler:" << this
<< " timer handle: " << task->timer_handle();
LOG(INFO) << __func__ << ": Scheduled task " << task.get()
<< " on task scheduler:" << this
<< " timer handle: " << task->timer_handle();
return task;
}
void TaskScheduler::Shutdown() {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__ << ": Shutting down task scheduler:" << this;
LOG(INFO) << __func__ << ": Shutting down task scheduler:" << this;
if (is_shutdown_) {
return;
}
@@ -109,16 +107,15 @@ void TaskScheduler::Shutdown() {
nullptr, reinterpret_cast<HANDLE>(task.second->timer_handle()),
INVALID_HANDLE_VALUE)) {
if (GetLastError() != ERROR_IO_PENDING) {
NEARBY_LOGS(ERROR) << __func__
<< ": Failed to delete timer queue timer: "
<< task.second->timer_handle()
<< " error: " << GetLastError();
LOG(ERROR) << __func__ << ": Failed to delete timer queue timer: "
<< task.second->timer_handle()
<< " error: " << GetLastError();
}
}
}
scheduled_tasks_.clear();
is_shutdown_ = true;
NEARBY_LOGS(INFO) << __func__ << ": Shut down task scheduler:" << this;
LOG(INFO) << __func__ << ": Shut down task scheduler:" << this;
}
TaskScheduler::ScheduledTask::ScheduledTask(TaskScheduler& task_scheduler,
@@ -137,8 +134,8 @@ TaskScheduler::ScheduledTask::ScheduledTask(TaskScheduler& task_scheduler,
}
bool TaskScheduler::ScheduledTask::Cancel() {
NEARBY_LOGS(INFO) << __func__ << ": Cancelling timer " << timer_handle()
<< " from task scheduler:" << this;
LOG(INFO) << __func__ << ": Cancelling timer " << timer_handle()
<< " from task scheduler:" << this;
{
absl::MutexLock lock(&mutex_);
if (is_cancelled_) {
@@ -188,8 +185,9 @@ bool TaskScheduler::CancelScheduledTask(intptr_t timer_handle) {
if (!DeleteTimerQueueTimer(nullptr, reinterpret_cast<HANDLE>(timer_handle),
INVALID_HANDLE_VALUE)) {
if (GetLastError() != ERROR_IO_PENDING) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to delete timer queue timer: "
<< timer_handle << " error: " << GetLastError();
LOG(ERROR) << __func__
<< ": Failed to delete timer queue timer: " << timer_handle
<< " error: " << GetLastError();
return false;
}
}
@@ -17,10 +17,13 @@
#include <shlobj.h>
#include <algorithm>
#include <cstddef>
#include <sstream>
#include <string>
#include "absl/strings/str_format.h"
#include "absl/strings/str_replace.h"
#include "internal/platform/payload_id.h"
namespace test_utils {
std::wstring StringToWideString(const std::string& s) {
@@ -44,7 +47,7 @@ std::string GetPayloadPath(nearby::PayloadId payload_id) {
FOLDERID_Downloads, // rfid: A reference to the KNOWNFOLDERID that
// identifies the folder.
0, // dwFlags: Flags that specify special retrieval options.
NULL, // hToken: An access token that represents a particular user.
nullptr, // hToken: An access token that represents a particular user.
&basePath); // ppszPath: When this method returns, contains the address
// of a pointer to a null-terminated Unicode string that
// specifies the path of the known folder. The calling
@@ -54,8 +57,8 @@ std::string GetPayloadPath(nearby::PayloadId payload_id) {
size_t bufferSize;
// Get the required buffer size.
wcstombs_s(&bufferSize, NULL, 0, basePath, 0);
std::string fullpathUTF8(bufferSize, NULL);
wcstombs_s(&bufferSize, nullptr, 0, basePath, 0);
std::string fullpathUTF8(bufferSize, 0);
wcstombs_s(&bufferSize, fullpathUTF8.data(), bufferSize, basePath, _TRUNCATE);
std::string fullPath = std::string(fullpathUTF8);
// Clean up the string by removing null's
@@ -16,12 +16,13 @@
#include <windows.h>
#include <memory>
#include <queue>
#include <utility>
#include "absl/memory/memory.h"
#include "absl/synchronization/mutex.h"
#include "internal/platform/count_down_latch.h"
#include "internal/platform/implementation/shared/count_down_latch.h"
#include "internal/platform/logging.h"
#include "internal/platform/runnable.h"
@@ -44,16 +45,15 @@ std::unique_ptr<ThreadPool> ThreadPool::Create(int max_pool_size) {
InitializeThreadpoolEnvironment(&thread_pool_environ);
if (max_pool_size <= 0) {
NEARBY_LOGS(ERROR) << __func__
<< ": Maximum pool size must be positive integer value.";
LOG(ERROR) << __func__
<< ": Maximum pool size must be positive integer value.";
return nullptr;
}
thread_pool = CreateThreadpool(NULL);
if (thread_pool == nullptr) {
NEARBY_LOGS(ERROR) << __func__
<< ": failed to create thread pool. LastError: "
<< GetLastError();
LOG(ERROR) << __func__ << ": failed to create thread pool. LastError: "
<< GetLastError();
return nullptr;
}
@@ -61,9 +61,9 @@ std::unique_ptr<ThreadPool> ThreadPool::Create(int max_pool_size) {
// it will keep at least one thread.
SetThreadpoolThreadMaximum(thread_pool, max_pool_size);
if (!SetThreadpoolThreadMinimum(thread_pool, 1)) {
NEARBY_LOGS(ERROR)
<< __func__ << ": failed to set minimum thread pool size. LastError: "
<< GetLastError();
LOG(ERROR) << __func__
<< ": failed to set minimum thread pool size. LastError: "
<< GetLastError();
CloseThreadpool(thread_pool);
return nullptr;
}
@@ -83,12 +83,12 @@ ThreadPool::ThreadPool(PTP_POOL thread_pool,
: thread_pool_(thread_pool),
thread_pool_environ_(thread_pool_environ),
max_pool_size_(max_pool_size) {
NEARBY_VLOG(1) << __func__ << ": Thread pool(" << this
<< ") is created with size:" << max_pool_size_;
VLOG(1) << __func__ << ": Thread pool(" << this
<< ") is created with size:" << max_pool_size_;
}
ThreadPool::~ThreadPool() {
NEARBY_VLOG(1) << __func__ << ": Thread pool(" << this << ") is released.";
VLOG(1) << __func__ << ": Thread pool(" << this << ") is released.";
if (thread_pool_ == nullptr) {
return;
@@ -105,20 +105,18 @@ bool ThreadPool::Run(Runnable task) {
}
if (shutdown_latch_ != nullptr) {
NEARBY_LOGS(WARNING) << __func__ << ": Thread pool is in shutting down.";
LOG(WARNING) << __func__ << ": Thread pool is in shutting down.";
return false;
}
PTP_WORK work;
tasks_.push(std::move(task));
NEARBY_VLOG(1) << __func__ << ": Scheduled to run task(" << &tasks_.back()
<< ").";
VLOG(1) << __func__ << ": Scheduled to run task(" << &tasks_.back() << ").";
work = CreateThreadpoolWork(WorkCallback, this, &thread_pool_environ_);
if (work == nullptr) {
NEARBY_LOGS(ERROR) << __func__
<< ": failed to create thread pool work. LastError: "
<< GetLastError();
LOG(ERROR) << __func__ << ": failed to create thread pool work. LastError: "
<< GetLastError();
return false;
}
@@ -137,29 +135,27 @@ void ThreadPool::ShutDown() {
absl::MutexLock lock(&mutex_);
if (thread_pool_ == nullptr) {
NEARBY_LOGS(WARNING) << __func__ << ": Shutdown on closed thread pool("
<< this << ").";
LOG(WARNING) << __func__ << ": Shutdown on closed thread pool(" << this
<< ").";
return;
}
if (running_tasks_count_ == 0) {
CloseThreadpool(thread_pool_);
thread_pool_ = nullptr;
NEARBY_VLOG(1) << __func__ << ": Thread pool(" << this
<< ") is shut down.";
VLOG(1) << __func__ << ": Thread pool(" << this << ") is shut down.";
return;
}
if (shutdown_latch_ != nullptr) {
NEARBY_VLOG(1) << __func__ << ": Thread pool(" << this
<< ") is already in shutting down.";
VLOG(1) << __func__ << ": Thread pool(" << this
<< ") is already in shutting down.";
return;
}
NEARBY_VLOG(1) << __func__ << ": Thread pool(" << this
<< ") is shutting down.";
VLOG(1) << __func__ << ": Thread pool(" << this << ") is shutting down.";
shutdown_latch_ = std::make_unique<CountDownLatch>(1);
shutdown_latch_ = std::make_unique<shared::CountDownLatch>(1);
}
// Wait for all tasks to complete.
@@ -169,7 +165,7 @@ void ThreadPool::ShutDown() {
absl::MutexLock lock(&mutex_);
CloseThreadpool(thread_pool_);
thread_pool_ = nullptr;
NEARBY_VLOG(1) << __func__ << ": Thread pool(" << this << ") is shut down.";
VLOG(1) << __func__ << ": Thread pool(" << this << ") is shut down.";
}
}
@@ -183,14 +179,14 @@ void ThreadPool::RunNextTask() {
return;
}
if (!tasks_.empty()) {
NEARBY_VLOG(1) << __func__ << ": Run task(" << &tasks_.front() << ").";
VLOG(1) << __func__ << ": Run task(" << &tasks_.front() << ").";
task = std::move(tasks_.front());
tasks_.pop();
if (task == nullptr) {
NEARBY_LOGS(WARNING)
<< __func__ << ": Tried to run task in an empty thread pool.";
LOG(WARNING) << __func__
<< ": Tried to run task in an empty thread pool.";
--running_tasks_count_;
if (running_tasks_count_ == 0 && shutdown_latch_ != nullptr) {
shutdown_latch_->CountDown();
@@ -23,7 +23,7 @@
#include "absl/base/thread_annotations.h"
#include "absl/synchronization/mutex.h"
#include "internal/platform/count_down_latch.h"
#include "internal/platform/implementation/shared/count_down_latch.h"
#include "internal/platform/runnable.h"
namespace nearby {
@@ -68,7 +68,7 @@ class ThreadPool {
int running_tasks_count_ ABSL_GUARDED_BY(mutex_) = 0;
// The latch is used to wait for running tasks
std::unique_ptr<CountDownLatch> shutdown_latch_ = nullptr;
std::unique_ptr<shared::CountDownLatch> shutdown_latch_ = nullptr;
friend VOID CALLBACK WorkCallback(PTP_CALLBACK_INSTANCE instance,
PVOID parameter, PTP_WORK work);
@@ -41,8 +41,7 @@ bool Timer::Create(int delay, int interval,
if (use_task_scheduler_) {
absl::MutexLock lock(&mutex_);
if ((delay < 0) || (interval < 0)) {
NEARBY_LOGS(WARNING)
<< "Delay and interval shouldn\'t be negative value.";
LOG(WARNING) << "Delay and interval shouldn\'t be negative value.";
return false;
}
@@ -63,8 +62,7 @@ bool Timer::Create(int delay, int interval,
absl::MutexLock lock(&mutex_);
if ((delay < 0) || (interval < 0)) {
NEARBY_LOGS(WARNING)
<< "Delay and interval shouldn\'t be negative value.";
LOG(WARNING) << "Delay and interval shouldn\'t be negative value.";
return false;
}
@@ -74,7 +72,7 @@ bool Timer::Create(int delay, int interval,
timer_queue_handle_ = CreateTimerQueue();
if (timer_queue_handle_ == nullptr) {
NEARBY_LOGS(ERROR) << "Failed to create timer queue.";
LOG(ERROR) << "Failed to create timer queue.";
return false;
}
@@ -87,7 +85,7 @@ bool Timer::Create(int delay, int interval,
&callback_, delay, interval,
WT_EXECUTEDEFAULT)) {
if (!DeleteTimerQueueEx(timer_queue_handle_, nullptr)) {
NEARBY_LOGS(ERROR) << "Failed to create timer in timer queue.";
LOG(ERROR) << "Failed to create timer in timer queue.";
}
timer_queue_handle_ = nullptr;
return false;
@@ -116,7 +114,7 @@ bool Timer::Stop() {
if (!DeleteTimerQueueTimer(timer_queue_handle_, handle_, nullptr)) {
if (GetLastError() != ERROR_IO_PENDING) {
NEARBY_LOGS(ERROR) << "Failed to delete timer from timer queue.";
LOG(ERROR) << "Failed to delete timer from timer queue.";
return false;
}
}
@@ -124,7 +122,7 @@ bool Timer::Stop() {
handle_ = nullptr;
if (!DeleteTimerQueueEx(timer_queue_handle_, nullptr)) {
NEARBY_LOGS(ERROR) << "Failed to delete timer queue.";
LOG(ERROR) << "Failed to delete timer queue.";
return false;
}
@@ -137,7 +135,7 @@ bool Timer::FireNow() {
absl::MutexLock lock(&mutex_);
if (!callback_) {
NEARBY_LOGS(ERROR) << "callback_ is empty";
LOG(ERROR) << "callback_ is empty";
return false;
}
@@ -146,8 +144,7 @@ bool Timer::FireNow() {
}
if (task_executor_ == nullptr) {
NEARBY_LOGS(ERROR)
<< "Failed to fire the task due to cannot create executor.";
LOG(ERROR) << "Failed to fire the task due to cannot create executor.";
return false;
}
@@ -145,16 +145,13 @@ std::vector<std::string> GetIpv4Addresses() {
}
}
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__
<< ": Cannot get IPv4 addresses. Exception : "
<< exception.what();
LOG(ERROR) << __func__ << ": Cannot get IPv4 addresses. Exception : "
<< exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__
<< ": Cannot get IPv4 addresses. WinRT exception: "
<< error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": Cannot get IPv4 addresses. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
}
result.insert(result.end(), wifi_addresses.begin(), wifi_addresses.end());
@@ -20,9 +20,14 @@
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "internal/account/account_manager_impl.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/implementation/webrtc.h"
#include "internal/platform/logging.h"
#include "webrtc/api/peer_connection_interface.h"
#include "webrtc/api/task_queue/default_task_queue_factory.h"
#include "webrtc/rtc_base/thread.h"
namespace nearby {
namespace windows {
@@ -54,13 +59,13 @@ const std::string WebRtcMedium::GetDefaultCountryCode() {
wchar_t systemGeoName[LOCALE_NAME_MAX_LENGTH];
if (!GetUserDefaultGeoName(systemGeoName, LOCALE_NAME_MAX_LENGTH)) {
NEARBY_LOGS(ERROR) << __func__ << ": Failed to GetUserDefaultGeoName: "
<< ". Fall back to US.";
LOG(ERROR) << __func__
<< ": Failed to GetUserDefaultGeoName: " << ". Fall back to US.";
return "US";
}
std::wstring wideGeo(systemGeoName);
std::string systemGeoNameString(wideGeo.begin(), wideGeo.end());
NEARBY_VLOG(1) << "GetUserDefaultGeoName() returns: " << systemGeoNameString;
VLOG(1) << "GetUserDefaultGeoName() returns: " << systemGeoNameString;
return systemGeoNameString;
}
@@ -80,7 +85,7 @@ void WebRtcMedium::CreatePeerConnection(
std::unique_ptr<rtc::Thread> signaling_thread = rtc::Thread::Create();
signaling_thread->SetName("signaling_thread", nullptr);
if (!signaling_thread->Start()) {
NEARBY_LOGS(FATAL) << "Failed to start thread";
LOG(FATAL) << "Failed to start thread";
}
webrtc::PeerConnectionDependencies dependencies(observer);
@@ -97,7 +102,7 @@ void WebRtcMedium::CreatePeerConnection(
if (peer_connection_or_error.ok()) {
callback(peer_connection_or_error.MoveValue());
} else {
NEARBY_LOGS(FATAL) << "Failed to create peer connection";
LOG(FATAL) << "Failed to create peer connection";
callback(/*peer_connection=*/nullptr);
}
}
@@ -20,6 +20,8 @@
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "internal/platform/cancellation_flag.h"
#include "internal/platform/implementation/wifi_direct.h"
#include "internal/platform/implementation/windows/wifi_direct.h"
#include "internal/platform/wifi_utils.h"
@@ -66,23 +68,23 @@ bool WifiDirectMedium::IsInterfaceValid() const {
DWORD result =
WFDOpenHandle(WFD_API_VERSION, &negotiated_version, &wifi_direct_handle);
if (result == ERROR_SUCCESS) {
NEARBY_LOGS(INFO) << "WiFi can support WifiDirect";
LOG(INFO) << "WiFi can support WifiDirect";
WFDCloseHandle(wifi_direct_handle);
return true;
}
NEARBY_LOGS(ERROR) << "WiFi can't support WifiDirect";
LOG(ERROR) << "WiFi can't support WifiDirect";
return false;
}
std::unique_ptr<api::WifiDirectSocket> WifiDirectMedium::ConnectToService(
absl::string_view ip_address, int port,
CancellationFlag* cancellation_flag) {
NEARBY_LOGS(WARNING) << __func__ << " : Connect to remote service.";
LOG(WARNING) << __func__ << " : Connect to remote service.";
if (ip_address.empty() || port == 0) {
NEARBY_LOGS(ERROR) << "no valid service address and port to connect: "
<< "ip_address = " << ip_address << ", port = " << port;
LOG(ERROR) << "no valid service address and port to connect: "
<< "ip_address = " << ip_address << ", port = " << port;
return nullptr;
}
@@ -94,7 +96,7 @@ std::unique_ptr<api::WifiDirectSocket> WifiDirectMedium::ConnectToService(
}
if (!WifiUtils::ValidateIPV4(ipv4_address)) {
NEARBY_LOGS(ERROR) << "Invalid IP address parameter.";
LOG(ERROR) << "Invalid IP address parameter.";
return nullptr;
}
@@ -113,23 +115,22 @@ std::unique_ptr<api::WifiDirectSocket> WifiDirectMedium::ConnectToService(
// setup cancel listener
if (cancellation_flag != nullptr) {
if (cancellation_flag->Cancelled()) {
NEARBY_LOGS(INFO) << "connect has been cancelled to service "
<< ipv4_address << ":" << port;
LOG(INFO) << "connect has been cancelled to service " << ipv4_address
<< ":" << port;
return nullptr;
}
connection_cancellation_listener =
std::make_unique<nearby::CancellationFlagListener>(
cancellation_flag, [socket]() {
NEARBY_LOGS(WARNING)
<< "connect is closed due to it is cancelled.";
LOG(WARNING) << "connect is closed due to it is cancelled.";
socket.Close();
});
}
connection_timeout_ = scheduled_executor_.Schedule(
[socket]() {
NEARBY_LOGS(WARNING) << "connect is closed due to timeout.";
LOG(WARNING) << "connect is closed due to timeout.";
socket.Close();
},
kWifiDirectClientSocketConnectTimeoutMillis);
@@ -143,12 +144,12 @@ std::unique_ptr<api::WifiDirectSocket> WifiDirectMedium::ConnectToService(
auto client_socket = std::make_unique<WifiDirectSocket>(socket);
NEARBY_LOGS(INFO) << "connected to remote service " << ipv4_address << ":"
<< port;
LOG(INFO) << "connected to remote service " << ipv4_address << ":"
<< port;
return client_socket;
} catch (...) {
NEARBY_LOGS(ERROR) << "failed to connect remote service " << ipv4_address
<< ":" << port << " for the " << i + 1 << " time";
LOG(ERROR) << "failed to connect remote service " << ipv4_address << ":"
<< port << " for the " << i + 1 << " time";
}
if (connection_timeout_ != nullptr) {
@@ -167,8 +168,8 @@ std::unique_ptr<api::WifiDirectServerSocket> WifiDirectMedium::ListenForService(
// check current status
if (IsAccepting()) {
NEARBY_LOGS(WARNING) << "accepting connections already started on port "
<< server_socket_ptr_->GetPort();
LOG(WARNING) << "accepting connections already started on port "
<< server_socket_ptr_->GetPort();
return nullptr;
}
@@ -179,18 +180,18 @@ std::unique_ptr<api::WifiDirectServerSocket> WifiDirectMedium::ListenForService(
medium_status_ |= kMediumStatusAccepting;
server_socket->SetCloseNotifier([this]() {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << "server socket was closed on port "
<< server_socket_ptr_->GetPort();
LOG(INFO) << "server socket was closed on port "
<< server_socket_ptr_->GetPort();
medium_status_ &= (~kMediumStatusAccepting);
server_socket_ptr_ = nullptr;
});
NEARBY_LOGS(INFO) << "started to listen serive on port "
<< server_socket_ptr_->GetPort();
LOG(INFO) << "started to listen serive on port "
<< server_socket_ptr_->GetPort();
return server_socket;
}
NEARBY_LOGS(ERROR) << "Failed to listen service on port " << port;
LOG(ERROR) << "Failed to listen service on port " << port;
return nullptr;
}
@@ -200,7 +201,7 @@ bool WifiDirectMedium::StartWifiDirect(
absl::MutexLock lock(&mutex_);
if (IsBeaconing()) {
NEARBY_LOGS(WARNING) << "cannot create SoftAP again when it is running.";
LOG(WARNING) << "cannot create SoftAP again when it is running.";
return true;
}
@@ -245,29 +246,26 @@ bool WifiDirectMedium::StartWifiDirect(
publisher_.Start();
if (publisher_.Status() ==
WiFiDirectAdvertisementPublisherStatus::Started) {
NEARBY_LOGS(INFO) << "Windows WiFiDirect GO(SoftAP) started";
LOG(INFO) << "Windows WiFiDirect GO(SoftAP) started";
medium_status_ |= kMediumStatusBeaconing;
return true;
}
// Clean up when fail
NEARBY_LOGS(ERROR) << "Windows WiFiDirect GO(SoftAP) fails to start";
LOG(ERROR) << "Windows WiFiDirect GO(SoftAP) fails to start";
publisher_.StatusChanged(publisher_status_changed_token_);
listener_.ConnectionRequested(connection_requested_token_);
listener_ = nullptr;
publisher_ = nullptr;
return false;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__
<< ": Cannot start WiFiDirect GO. Exception: "
<< exception.what();
LOG(ERROR) << __func__ << ": Cannot start WiFiDirect GO. Exception: "
<< exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__
<< ": Cannot start WiFiDirect GO. WinRT exception: "
<< error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": Cannot start WiFiDirect GO. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
}
return false;
}
@@ -277,7 +275,7 @@ bool WifiDirectMedium::StopWifiDirect() {
absl::MutexLock lock(&mutex_);
if (!IsBeaconing()) {
NEARBY_LOGS(WARNING)
LOG(WARNING)
<< "Cannot stop WiFiDirect GO(SoftAP) because no GO was started.";
return true;
}
@@ -290,21 +288,19 @@ bool WifiDirectMedium::StopWifiDirect() {
wifi_direct_device_ = nullptr;
listener_ = nullptr;
publisher_ = nullptr;
NEARBY_LOGS(INFO) << "succeeded to stop WiFiDirect GO(SoftAP)";
LOG(INFO) << "succeeded to stop WiFiDirect GO(SoftAP)";
}
medium_status_ &= (~kMediumStatusBeaconing);
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Stop WiFiDirect GO failed. Exception: "
<< exception.what();
LOG(ERROR) << __func__ << ": Stop WiFiDirect GO failed. Exception: "
<< exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__
<< ": Stop WiFiDirect GO failed. WinRT exception: "
<< error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": Stop WiFiDirect GO failed. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
}
return false;
}
@@ -314,34 +310,33 @@ fire_and_forget WifiDirectMedium::OnStatusChanged(
WiFiDirectAdvertisementPublisherStatusChangedEventArgs event) {
if (event.Status() == WiFiDirectAdvertisementPublisherStatus::Started) {
if (sender.Advertisement().LegacySettings().IsEnabled()) {
NEARBY_LOGS(INFO)
<< "WiFiDirect GO SSID: "
<< winrt::to_string(
publisher_.Advertisement().LegacySettings().Ssid());
NEARBY_LOGS(INFO) << "WiFiDirect GO PW: "
<< winrt::to_string(publisher_.Advertisement()
.LegacySettings()
.Passphrase()
.Password());
LOG(INFO) << "WiFiDirect GO SSID: "
<< winrt::to_string(
publisher_.Advertisement().LegacySettings().Ssid());
LOG(INFO) << "WiFiDirect GO PW: "
<< winrt::to_string(publisher_.Advertisement()
.LegacySettings()
.Passphrase()
.Password());
}
return winrt::fire_and_forget();
} else if (event.Status() ==
WiFiDirectAdvertisementPublisherStatus::Created) {
NEARBY_LOGS(INFO) << "Receive WiFiDirect/SoftAP Created event.";
LOG(INFO) << "Receive WiFiDirect/SoftAP Created event.";
return winrt::fire_and_forget();
} else if (event.Status() ==
WiFiDirectAdvertisementPublisherStatus::Stopped) {
NEARBY_LOGS(INFO) << "Receive WiFiDirect/SoftAP Stopped event.";
LOG(INFO) << "Receive WiFiDirect/SoftAP Stopped event.";
} else if (event.Status() ==
WiFiDirectAdvertisementPublisherStatus::Aborted) {
NEARBY_LOGS(INFO) << "Receive WiFiDirect/SoftAP Aborted event.";
LOG(INFO) << "Receive WiFiDirect/SoftAP Aborted event.";
}
// Publisher is stopped. Need to clean up the publisher.
{
absl::MutexLock lock(&mutex_);
if (publisher_ != nullptr) {
NEARBY_LOGS(ERROR) << "Windows WiFiDirect GO(SoftAP) cleanup.";
LOG(ERROR) << "Windows WiFiDirect GO(SoftAP) cleanup.";
listener_.ConnectionRequested(connection_requested_token_);
publisher_.StatusChanged(publisher_status_changed_token_);
wifi_direct_device_ = nullptr;
@@ -358,8 +353,8 @@ fire_and_forget WifiDirectMedium::OnConnectionRequested(
WiFiDirectConnectionRequestedEventArgs const& event) {
WiFiDirectConnectionRequest connection_request = event.GetConnectionRequest();
winrt::hstring device_name = connection_request.DeviceInformation().Name();
NEARBY_LOGS(INFO) << "Receive connection request from: "
<< winrt::to_string(device_name);
LOG(INFO) << "Receive connection request from: "
<< winrt::to_string(device_name);
try {
// This is to solve b/236805122.
@@ -372,9 +367,9 @@ fire_and_forget WifiDirectMedium::OnConnectionRequested(
wifi_direct_device_ = WiFiDirectDevice::FromIdAsync(
connection_request.DeviceInformation().Id())
.get();
NEARBY_LOGS(INFO) << "Registered the device in WLAN-AutoConfig";
LOG(INFO) << "Registered the device in WLAN-AutoConfig";
} catch (...) {
NEARBY_LOGS(ERROR) << "Failed to registered the device in WLAN-AutoConfig";
LOG(ERROR) << "Failed to registered the device in WLAN-AutoConfig";
wifi_direct_device_ = nullptr;
connection_request.Close();
}
@@ -387,20 +382,19 @@ bool WifiDirectMedium::ConnectWifiDirect(
try {
if (IsConnected()) {
NEARBY_LOGS(WARNING) << "Already connected to AP, disconnect first.";
LOG(WARNING) << "Already connected to AP, disconnect first.";
InternalDisconnectWifiDirect();
}
auto access = WiFiAdapter::RequestAccessAsync().get();
if (access != WiFiAccessStatus::Allowed) {
NEARBY_LOGS(WARNING) << "Access Denied with reason: "
<< static_cast<int>(access);
LOG(WARNING) << "Access Denied with reason: " << static_cast<int>(access);
return false;
}
auto adapters = WiFiAdapter::FindAllAdaptersAsync().get();
if (adapters.Size() < 1) {
NEARBY_LOGS(WARNING) << "No WiFi Adapter found.";
LOG(WARNING) << "No WiFi Adapter found.";
return false;
}
wifi_adapter_ = adapters.GetAt(0);
@@ -417,8 +411,8 @@ bool WifiDirectMedium::ConnectWifiDirect(
// SoftAP is an abbreviation for "software enabled access point".
WiFiAvailableNetwork nearby_softap{nullptr};
NEARBY_LOGS(INFO) << "Scanning for Nearby WifiDirect GO's SSID: "
<< wifi_direct_credentials->GetSSID();
LOG(INFO) << "Scanning for Nearby WifiDirect GO's SSID: "
<< wifi_direct_credentials->GetSSID();
// First time scan may not find our target GO, try 2 more times can
// almost guarantee to find the GO
@@ -431,22 +425,22 @@ bool WifiDirectMedium::ConnectWifiDirect(
if (!wifi_connected_network_ && !ssid.empty() &&
(winrt::to_string(network.Ssid()) == ssid)) {
wifi_connected_network_ = network;
NEARBY_LOGS(INFO) << "Save the current connected network: " << ssid;
LOG(INFO) << "Save the current connected network: " << ssid;
} else if (!nearby_softap && winrt::to_string(network.Ssid()) ==
wifi_direct_credentials->GetSSID()) {
NEARBY_LOGS(INFO)
<< "Found Nearby SSID: " << winrt::to_string(network.Ssid());
LOG(INFO) << "Found Nearby SSID: "
<< winrt::to_string(network.Ssid());
nearby_softap = network;
}
if (nearby_softap && wifi_connected_network_) break;
}
if (nearby_softap) break;
NEARBY_LOGS(INFO) << "Scan ... ";
LOG(INFO) << "Scan ... ";
wifi_adapter_.ScanAsync().get();
}
if (!nearby_softap) {
NEARBY_LOGS(INFO) << "WifiDirect GO is not found";
LOG(INFO) << "WifiDirect GO is not found";
return false;
}
@@ -460,15 +454,15 @@ bool WifiDirectMedium::ConnectWifiDirect(
if (connect_result == nullptr ||
connect_result.ConnectionStatus() != WiFiConnectionStatus::Success) {
NEARBY_LOGS(INFO) << "Connecting failed with reason: "
<< static_cast<int>(connect_result.ConnectionStatus());
LOG(INFO) << "Connecting failed with reason: "
<< static_cast<int>(connect_result.ConnectionStatus());
return false;
}
// Make sure IP address is ready.
std::string ip_address;
for (int i = 0; i < kIpAddressMaxRetries; i++) {
NEARBY_LOGS(INFO) << "Check IP address at attempt " << i;
LOG(INFO) << "Check IP address at attempt " << i;
std::vector<std::string> ip_addresses = GetIpv4Addresses();
if (ip_addresses.empty()) {
Sleep(kIpAddressRetryIntervalMillis / absl::Milliseconds(1));
@@ -479,28 +473,26 @@ bool WifiDirectMedium::ConnectWifiDirect(
}
if (ip_address.empty()) {
NEARBY_LOGS(INFO) << "Failed to get IP address from WifiDirect GO.";
LOG(INFO) << "Failed to get IP address from WifiDirect GO.";
return false;
}
NEARBY_LOGS(INFO) << "Got IP: " << ip_address << " from WifiDirect GO.";
LOG(INFO) << "Got IP: " << ip_address << " from WifiDirect GO.";
std::string last_ssid = wifi_direct_credentials->GetSSID();
medium_status_ |= kMediumStatusConnected;
NEARBY_LOGS(INFO) << "Connected to WifiDirect GO: " << last_ssid;
LOG(INFO) << "Connected to WifiDirect GO: " << last_ssid;
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__
<< ": Cannot connet to WifiDirect GO. Exception: "
<< exception.what();
LOG(ERROR) << __func__ << ": Cannot connet to WifiDirect GO. Exception: "
<< exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__
<< ": Cannot connet to WifiDirect GO. WinRT exception: "
<< error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << __func__
<< ": Cannot connet to WifiDirect GO. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
}
return false;
}
@@ -520,15 +512,15 @@ void WifiDirectMedium::RestoreWifiConnection() {
profile.WlanConnectionProfileDetails().GetConnectedSsid());
if (!ssid.empty() &&
(winrt::to_string(wifi_connected_network_.Ssid()) == ssid)) {
NEARBY_LOGS(INFO) << "Already conneted to the previous WIFI network "
<< ssid << "! Skip restoration.";
LOG(INFO) << "Already conneted to the previous WIFI network " << ssid
<< "! Skip restoration.";
return;
}
}
// Disconnect to the WiFi connection through the WiFi adapter.
wifi_adapter_.Disconnect();
NEARBY_LOGS(INFO) << "Disconnected to current network.";
LOG(INFO) << "Disconnected to current network.";
auto connect_result = wifi_adapter_
.ConnectAsync(wifi_connected_network_,
@@ -537,11 +529,11 @@ void WifiDirectMedium::RestoreWifiConnection() {
if (connect_result == nullptr ||
connect_result.ConnectionStatus() != WiFiConnectionStatus::Success) {
NEARBY_LOGS(INFO) << "Connecting to previous network failed with reason: "
<< static_cast<int>(connect_result.ConnectionStatus());
LOG(INFO) << "Connecting to previous network failed with reason: "
<< static_cast<int>(connect_result.ConnectionStatus());
} else {
NEARBY_LOGS(INFO) << "Restored the previous WIFI connection: "
<< winrt::to_string(wifi_connected_network_.Ssid());
LOG(INFO) << "Restored the previous WIFI connection: "
<< winrt::to_string(wifi_connected_network_.Ssid());
}
wifi_connected_network_ = nullptr;
}
@@ -552,23 +544,21 @@ bool WifiDirectMedium::DisconnectWifiDirect() {
try {
return InternalDisconnectWifiDirect();
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__
<< ": Disconnect WifiDirect GO failed. Exception: "
<< exception.what();
LOG(ERROR) << __func__ << ": Disconnect WifiDirect GO failed. Exception: "
<< exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__
<< ": Disconnect WifiDirect GO failed. WinRT exception: "
<< error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << __func__
<< ": Disconnect WifiDirect GO failed. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exception.";
LOG(ERROR) << __func__ << ": Unknown exception.";
}
return false;
}
bool WifiDirectMedium::InternalDisconnectWifiDirect() {
if (!IsConnected()) {
NEARBY_LOGS(WARNING)
LOG(WARNING)
<< "Cannot disconnect WifiDirect GO because it is not connected.";
return true;
}
@@ -591,23 +581,19 @@ bool WifiDirectMedium::InternalDisconnectWifiDirect() {
auto profile_delete_status = profile.TryDeleteAsync().get();
switch (profile_delete_status) {
case ConnectionProfileDeleteStatus::Success:
NEARBY_LOGS(INFO)
<< "WiFi profile with SSID:" << ssid << " is deleted.";
LOG(INFO) << "WiFi profile with SSID:" << ssid << " is deleted.";
break;
case ConnectionProfileDeleteStatus::DeniedBySystem:
NEARBY_LOGS(ERROR)
<< "Failed to delete WiFi profile with SSID:" << ssid
<< " due to denied by system.";
LOG(ERROR) << "Failed to delete WiFi profile with SSID:" << ssid
<< " due to denied by system.";
break;
case ConnectionProfileDeleteStatus::DeniedByUser:
NEARBY_LOGS(ERROR)
<< "Failed to delete WiFi profile with SSID:" << ssid
<< " due to denied by user.";
LOG(ERROR) << "Failed to delete WiFi profile with SSID:" << ssid
<< " due to denied by user.";
break;
case ConnectionProfileDeleteStatus::UnknownError:
NEARBY_LOGS(ERROR)
<< "Failed to delete WiFi profile with SSID:" << ssid
<< " due to unknonw error.";
LOG(ERROR) << "Failed to delete WiFi profile with SSID:" << ssid
<< " due to unknonw error.";
break;
default:
break;
@@ -20,9 +20,13 @@
#include <vector>
// ABSL headers
#include "absl/functional/any_invocable.h"
#include "absl/strings/match.h"
// Nearby connections headers
#include "absl/synchronization/mutex.h"
#include "internal/platform/exception.h"
#include "internal/platform/implementation/wifi_direct.h"
#include "internal/platform/implementation/windows/generated/winrt/Windows.Networking.Sockets.h"
#include "internal/platform/implementation/windows/utils.h"
#include "internal/platform/implementation/windows/wifi_direct.h"
@@ -67,7 +71,7 @@ int WifiDirectServerSocket::GetPort() const {
std::unique_ptr<api::WifiDirectSocket> WifiDirectServerSocket::Accept() {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__ << ": Accept is called.";
LOG(INFO) << __func__ << ": Accept is called.";
while (!closed_ && pending_sockets_.empty()) {
cond_.Wait(&mutex_);
@@ -77,7 +81,7 @@ std::unique_ptr<api::WifiDirectSocket> WifiDirectServerSocket::Accept() {
StreamSocket wifi_direct_socket = pending_sockets_.front();
pending_sockets_.pop_front();
NEARBY_LOGS(INFO) << __func__ << ": Accepted a remote connection.";
LOG(INFO) << __func__ << ": Accepted a remote connection.";
return std::make_unique<WifiDirectSocket>(wifi_direct_socket);
}
@@ -89,7 +93,7 @@ void WifiDirectServerSocket::SetCloseNotifier(
Exception WifiDirectServerSocket::Close() {
try {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__ << ": Close is called.";
LOG(INFO) << __func__ << ": Close is called.";
if (closed_) {
return {Exception::kSuccess};
@@ -112,23 +116,23 @@ Exception WifiDirectServerSocket::Close() {
close_notifier_();
}
NEARBY_LOGS(INFO) << __func__ << ": Close completed succesfully.";
LOG(INFO) << __func__ << ": Close completed succesfully.";
return {Exception::kSuccess};
} catch (std::exception exception) {
closed_ = true;
cond_.SignalAll();
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error &error) {
closed_ = true;
cond_.SignalAll();
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
closed_ = true;
cond_.SignalAll();
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -138,17 +142,17 @@ bool WifiDirectServerSocket::listen() {
for (int i = 0; i < kMaxRetries; i++) {
wifi_direct_go_ipaddr_ = GetDirectGOIpAddresses();
if (wifi_direct_go_ipaddr_.empty()) {
NEARBY_LOGS(WARNING)
<< "Failed to find WifiDirect GO's IP addr for the try: " << i + 1
<< ". Wait " << kRetryIntervalMilliSeconds << "ms snd try again";
LOG(WARNING) << "Failed to find WifiDirect GO's IP addr for the try: "
<< i + 1 << ". Wait " << kRetryIntervalMilliSeconds
<< "ms snd try again";
Sleep(kRetryIntervalMilliSeconds);
} else {
break;
}
}
if (wifi_direct_go_ipaddr_.empty()) {
NEARBY_LOGS(WARNING) << "Failed to start accepting connection without IP "
"addresses configured on computer.";
LOG(WARNING) << "Failed to start accepting connection without IP "
"addresses configured on computer.";
return false;
}
@@ -176,17 +180,16 @@ bool WifiDirectServerSocket::listen() {
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR)
<< __func__
<< ": Cannot accept connection on preferred port. Exception: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Cannot accept connection on preferred port. Exception: "
<< exception.what();
} catch (const winrt::hresult_error &error) {
NEARBY_LOGS(ERROR)
LOG(ERROR)
<< __func__
<< ":Cannot accept connection on preferred port. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
}
try {
@@ -194,18 +197,17 @@ bool WifiDirectServerSocket::listen() {
// need to save the port information.
port_ =
std::stoi(stream_socket_listener_.Information().LocalPort().c_str());
NEARBY_LOGS(INFO) << "Server Socket port: " << port_;
LOG(INFO) << "Server Socket port: " << port_;
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Cannot bind to any port. Exception: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Cannot bind to any port. Exception: " << exception.what();
} catch (const winrt::hresult_error &error) {
NEARBY_LOGS(ERROR) << __func__
<< ": Cannot bind to any port. WinRT exception: "
<< error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << __func__
<< ": Cannot bind to any port. WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
}
return false;
@@ -215,7 +217,7 @@ fire_and_forget WifiDirectServerSocket::Listener_ConnectionReceived(
StreamSocketListener listener,
StreamSocketListenerConnectionReceivedEventArgs const &args) {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__ << ": Received connection.";
LOG(INFO) << __func__ << ": Received connection.";
if (closed_) {
return fire_and_forget{};
@@ -236,7 +238,7 @@ std::vector<std::string> WifiDirectServerSocket::GetIpAddresses() const {
std::string ipv4_s = winrt::to_string(host_name.ToString());
if (absl::EndsWith(ipv4_s, ".1")) {
NEARBY_LOGS(INFO) << "Found WifiDirect GO IP: " << ipv4_s;
LOG(INFO) << "Found WifiDirect GO IP: " << ipv4_s;
result.push_back(ipv4_s);
}
}
@@ -256,7 +258,7 @@ std::string WifiDirectServerSocket::GetDirectGOIpAddresses() const {
if (absl::EndsWith(ipv4_s, ".1")) {
// TODO(b/228541380): replace when we find a better way to
// identifying the WifiDirect GO IP address
NEARBY_LOGS(INFO) << "Found WifiDirect GO IP: " << ipv4_s;
LOG(INFO) << "Found WifiDirect GO IP: " << ipv4_s;
return ipv4_s;
}
}
@@ -264,14 +266,14 @@ std::string WifiDirectServerSocket::GetDirectGOIpAddresses() const {
}
return {};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {};
} catch (const winrt::hresult_error &error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {};
}
}
@@ -12,12 +12,16 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include <cstdint>
#include <cstring>
#include <exception>
#include "internal/platform/byte_array.h"
#include "internal/platform/exception.h"
#include "internal/platform/implementation/windows/wifi_direct.h"
#include "internal/platform/input_stream.h"
#include "internal/platform/logging.h"
#include "internal/platform/output_stream.h"
namespace nearby {
namespace windows {
@@ -33,12 +37,12 @@ WifiDirectSocket::~WifiDirectSocket() {
Close();
}
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
}
}
@@ -53,14 +57,14 @@ Exception WifiDirectSocket::Close() {
}
return {Exception::kSuccess};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -79,21 +83,21 @@ ExceptionOr<ByteArray> WifiDirectSocket::SocketInputStream::Read(
input_stream_.ReadAsync(buffer, size, InputStreamOptions::None).get();
if (ibuffer.Length() != size) {
NEARBY_LOGS(WARNING) << "Only got part of data of needed.";
LOG(WARNING) << "Only got part of data of needed.";
}
ByteArray data((char*)ibuffer.data(), ibuffer.Length());
return ExceptionOr(data);
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -106,14 +110,14 @@ ExceptionOr<size_t> WifiDirectSocket::SocketInputStream::Skip(size_t offset) {
input_stream_.ReadAsync(buffer, offset, InputStreamOptions::None).get();
return ExceptionOr((size_t)ibuffer.Length());
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -123,14 +127,14 @@ Exception WifiDirectSocket::SocketInputStream::Close() {
input_stream_.Close();
return {Exception::kSuccess};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -150,14 +154,14 @@ Exception WifiDirectSocket::SocketOutputStream::Write(const ByteArray& data) {
output_stream_.WriteAsync(buffer).get();
return {Exception::kSuccess};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -167,14 +171,14 @@ Exception WifiDirectSocket::SocketOutputStream::Flush() {
output_stream_.FlushAsync().get();
return {Exception::kSuccess};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -184,14 +188,14 @@ Exception WifiDirectSocket::SocketOutputStream::Close() {
output_stream_.Close();
return {Exception::kSuccess};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -12,23 +12,27 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal/platform/implementation/windows/wifi_hotspot.h"
#include <cstdint>
#include <exception>
#include <memory>
#include <string>
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "internal/flags/nearby_flags.h"
#include "internal/platform/cancellation_flag.h"
#include "internal/platform/cancellation_flag_listener.h"
#include "internal/platform/feature_flags.h"
#include "internal/platform/flags/nearby_platform_feature_flags.h"
#include "internal/platform/implementation/wifi_hotspot.h"
#include "internal/platform/implementation/windows/utils.h"
#include "internal/platform/implementation/windows/wifi_hotspot.h"
#include "internal/platform/implementation/windows/wifi_intel.h"
#include "internal/platform/cancellation_flag_listener.h"
#include "internal/platform/wifi_utils.h"
#include "internal/platform/logging.h"
#include "internal/platform/prng.h"
#include "internal/platform/wifi_credential.h"
#include "internal/platform/wifi_utils.h"
namespace nearby {
namespace windows {
@@ -41,30 +45,30 @@ WifiHotspotMedium::~WifiHotspotMedium() {
}
bool WifiHotspotMedium::IsInterfaceValid() const {
HANDLE wifi_direct_handle = NULL;
HANDLE wifi_direct_handle = nullptr;
DWORD negotiated_version = 0;
DWORD result = 0;
result =
WFDOpenHandle(WFD_API_VERSION, &negotiated_version, &wifi_direct_handle);
if (result == ERROR_SUCCESS) {
NEARBY_LOGS(INFO) << "WiFi can support Hotspot";
LOG(INFO) << "WiFi can support Hotspot";
WFDCloseHandle(wifi_direct_handle);
return true;
}
NEARBY_LOGS(ERROR) << "WiFi can't support Hotspot";
LOG(ERROR) << "WiFi can't support Hotspot";
return false;
}
std::unique_ptr<api::WifiHotspotSocket> WifiHotspotMedium::ConnectToService(
absl::string_view ip_address, int port,
CancellationFlag* cancellation_flag) {
NEARBY_LOGS(WARNING) << __func__ << " : Connect to remote service.";
LOG(WARNING) << __func__ << " : Connect to remote service.";
if (ip_address.empty() || port == 0) {
NEARBY_LOGS(ERROR) << "no valid service address and port to connect: "
<< "ip_address = " << ip_address << ", port = " << port;
LOG(ERROR) << "no valid service address and port to connect: "
<< "ip_address = " << ip_address << ", port = " << port;
return nullptr;
}
@@ -75,7 +79,7 @@ std::unique_ptr<api::WifiHotspotSocket> WifiHotspotMedium::ConnectToService(
ipv4_address = std::string(ip_address);
}
if (ipv4_address.empty()) {
NEARBY_LOGS(ERROR) << "Invalid IP address parameter.";
LOG(ERROR) << "Invalid IP address parameter.";
return nullptr;
}
@@ -97,13 +101,11 @@ std::unique_ptr<api::WifiHotspotSocket> WifiHotspotMedium::ConnectToService(
platform::config_package_nearby::nearby_platform_feature::
kWifiHotspotConnectionTimeoutMillis);
NEARBY_LOGS(INFO) << "maximum connection retries="
<< wifi_hotspot_max_connection_retries
<< ", connection interval="
<< wifi_hotspot_retry_interval_millis
<< "ms, connection timeout="
<< wifi_hotspot_client_socket_connect_timeout_millis
<< "ms";
LOG(INFO) << "maximum connection retries="
<< wifi_hotspot_max_connection_retries
<< ", connection interval=" << wifi_hotspot_retry_interval_millis
<< "ms, connection timeout="
<< wifi_hotspot_client_socket_connect_timeout_millis << "ms";
for (int i = 0; i < wifi_hotspot_max_connection_retries; i++) {
try {
StreamSocket socket{};
@@ -114,16 +116,15 @@ std::unique_ptr<api::WifiHotspotSocket> WifiHotspotMedium::ConnectToService(
// setup cancel listener
if (cancellation_flag != nullptr) {
if (cancellation_flag->Cancelled()) {
NEARBY_LOGS(INFO) << "connect has been cancelled to service "
<< ipv4_address << ":" << port;
LOG(INFO) << "connect has been cancelled to service " << ipv4_address
<< ":" << port;
return nullptr;
}
connection_cancellation_listener =
std::make_unique<nearby::CancellationFlagListener>(
cancellation_flag, [socket]() {
NEARBY_LOGS(WARNING)
<< "connect is closed due to it is cancelled.";
LOG(WARNING) << "connect is closed due to it is cancelled.";
socket.Close();
});
}
@@ -131,7 +132,7 @@ std::unique_ptr<api::WifiHotspotSocket> WifiHotspotMedium::ConnectToService(
if (FeatureFlags::GetInstance().GetFlags().enable_connection_timeout) {
connection_timeout_ = scheduled_executor_.Schedule(
[socket]() {
NEARBY_LOGS(WARNING) << "connect is closed due to timeout.";
LOG(WARNING) << "connect is closed due to timeout.";
socket.Close();
},
absl::Milliseconds(
@@ -147,22 +148,22 @@ std::unique_ptr<api::WifiHotspotSocket> WifiHotspotMedium::ConnectToService(
auto wifi_hotspot_socket = std::make_unique<WifiHotspotSocket>(socket);
NEARBY_LOGS(INFO) << "connected to remote service " << ipv4_address << ":"
<< port;
LOG(INFO) << "connected to remote service " << ipv4_address << ":"
<< port;
return wifi_hotspot_socket;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << "failed to connect remote service " << ipv4_address
<< ":" << port << " for the " << i + 1
<< " time. Exception: " << exception.what();
LOG(ERROR) << "failed to connect remote service " << ipv4_address << ":"
<< port << " for the " << i + 1
<< " time. Exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << "failed to connect remote service " << ipv4_address
<< ":" << port << " for the " << i + 1
<< " time. WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << "failed to connect remote service " << ipv4_address << ":"
<< port << " for the " << i + 1
<< " time. WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << "failed to connect remote service " << ipv4_address
<< ":" << port << " for the " << i + 1
<< " time due to unknown reason.";
LOG(ERROR) << "failed to connect remote service " << ipv4_address << ":"
<< port << " for the " << i + 1
<< " time due to unknown reason.";
}
if (connection_timeout_ != nullptr) {
@@ -178,13 +179,13 @@ std::unique_ptr<api::WifiHotspotSocket> WifiHotspotMedium::ConnectToService(
std::unique_ptr<api::WifiHotspotServerSocket>
WifiHotspotMedium::ListenForService(int port) {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__
<< " :Start to listen connection from WiFi Hotspot client.";
LOG(INFO) << __func__
<< " :Start to listen connection from WiFi Hotspot client.";
// check current status
if (IsAccepting()) {
NEARBY_LOGS(WARNING) << "accepting connections already started on port "
<< server_socket_ptr_->GetPort();
LOG(WARNING) << "accepting connections already started on port "
<< server_socket_ptr_->GetPort();
return nullptr;
}
@@ -197,16 +198,16 @@ WifiHotspotMedium::ListenForService(int port) {
// Setup close notifier after listen started.
server_socket->SetCloseNotifier([this]() {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << "Server socket was closed.";
LOG(INFO) << "Server socket was closed.";
medium_status_ &= (~kMediumStatusAccepting);
server_socket_ptr_ = nullptr;
});
NEARBY_LOGS(INFO) << "Started to listen serive on port "
<< server_socket_ptr_->GetPort();
LOG(INFO) << "Started to listen serive on port "
<< server_socket_ptr_->GetPort();
return server_socket;
}
NEARBY_LOGS(ERROR) << "Failed to listen service on port " << port;
LOG(ERROR) << "Failed to listen service on port " << port;
return nullptr;
}
@@ -214,11 +215,10 @@ WifiHotspotMedium::ListenForService(int port) {
bool WifiHotspotMedium::StartWifiHotspot(
HotspotCredentials* hotspot_credentials_) {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__ << ": Start to create WiFi Hotspot.";
LOG(INFO) << __func__ << ": Start to create WiFi Hotspot.";
if (IsBeaconing()) {
NEARBY_LOGS(WARNING)
<< "Cannot create WiFi Hotspot again when it is running.";
LOG(WARNING) << "Cannot create WiFi Hotspot again when it is running.";
return true;
}
@@ -253,7 +253,7 @@ bool WifiHotspotMedium::StartWifiHotspot(
publisher_.Start();
if (publisher_.Status() ==
WiFiDirectAdvertisementPublisherStatus::Started) {
NEARBY_LOGS(INFO) << __func__ << ": WiFi Hotspot created and started.";
LOG(INFO) << __func__ << ": WiFi Hotspot created and started.";
medium_status_ |= kMediumStatusBeaconing;
if (NearbyFlags::GetInstance().GetBoolFlag(
platform::config_package_nearby::nearby_platform_feature::
@@ -261,39 +261,36 @@ bool WifiHotspotMedium::StartWifiHotspot(
WifiIntel& intel_wifi{WifiIntel::GetInstance()};
if (intel_wifi.Start()) {
int GO_channel = intel_wifi.GetGOChannel();
NEARBY_LOGS(INFO)
<< "Intel PIE enabled, Hotspot is running on channel: "
<< GO_channel;
LOG(INFO) << "Intel PIE enabled, Hotspot is running on channel: "
<< GO_channel;
intel_wifi.Stop();
hotspot_credentials_->SetFrequency(
WifiUtils::ConvertChannelToFrequencyMhz(GO_channel,
WifiBandType::kUnknown));
}
} else {
NEARBY_LOGS(INFO)
<< "Intel PIE disabled, Can't extract Hotspot channel info!";
LOG(INFO) << "Intel PIE disabled, Can't extract Hotspot channel info!";
hotspot_credentials_->SetFrequency(-1);
}
return true;
}
// Clean up when fail
NEARBY_LOGS(ERROR) << "Windows WiFi Hotspot fails to start";
LOG(ERROR) << "Windows WiFi Hotspot fails to start";
publisher_.StatusChanged(publisher_status_changed_token_);
listener_.ConnectionRequested(connection_requested_token_);
listener_ = nullptr;
publisher_ = nullptr;
return false;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Cannot start Hotspot. Exception: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Cannot start Hotspot. Exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__
<< ": Cannot start Hotspot. WinRT exception: "
<< error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << __func__
<< ": Cannot start Hotspot. WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
}
return false;
}
@@ -303,7 +300,7 @@ bool WifiHotspotMedium::StopWifiHotspot() {
absl::MutexLock lock(&mutex_);
if (!IsBeaconing()) {
NEARBY_LOGS(WARNING) << "Cannot stop SoftAP because no SoftAP is started.";
LOG(WARNING) << "Cannot stop SoftAP because no SoftAP is started.";
return true;
}
try {
@@ -314,20 +311,20 @@ bool WifiHotspotMedium::StopWifiHotspot() {
wifi_direct_device_ = nullptr;
listener_ = nullptr;
publisher_ = nullptr;
NEARBY_LOGS(INFO) << "succeeded to stop WiFi Hotspot";
LOG(INFO) << "succeeded to stop WiFi Hotspot";
}
medium_status_ &= (~kMediumStatusBeaconing);
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Stop Hotspot failed. Exception: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Stop Hotspot failed. Exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": Stop Hotspot failed. WinRT exception: "
<< error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << __func__
<< ": Stop Hotspot failed. WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
}
return false;
}
@@ -337,34 +334,33 @@ fire_and_forget WifiHotspotMedium::OnStatusChanged(
WiFiDirectAdvertisementPublisherStatusChangedEventArgs event) {
if (event.Status() == WiFiDirectAdvertisementPublisherStatus::Started) {
if (sender.Advertisement().LegacySettings().IsEnabled()) {
NEARBY_LOGS(INFO)
<< "WiFi SoftAP SSID: "
<< winrt::to_string(
publisher_.Advertisement().LegacySettings().Ssid());
NEARBY_LOGS(INFO) << "WiFi SoftAP PW: "
<< winrt::to_string(publisher_.Advertisement()
.LegacySettings()
.Passphrase()
.Password());
LOG(INFO) << "WiFi SoftAP SSID: "
<< winrt::to_string(
publisher_.Advertisement().LegacySettings().Ssid());
LOG(INFO) << "WiFi SoftAP PW: "
<< winrt::to_string(publisher_.Advertisement()
.LegacySettings()
.Passphrase()
.Password());
}
return winrt::fire_and_forget();
} else if (event.Status() ==
WiFiDirectAdvertisementPublisherStatus::Created) {
NEARBY_LOGS(INFO) << "Receive WiFi direct/SoftAP Created event.";
LOG(INFO) << "Receive WiFi direct/SoftAP Created event.";
return winrt::fire_and_forget();
} else if (event.Status() ==
WiFiDirectAdvertisementPublisherStatus::Stopped) {
NEARBY_LOGS(INFO) << "Receive WiFi direct/SoftAP Stopped event.";
LOG(INFO) << "Receive WiFi direct/SoftAP Stopped event.";
} else if (event.Status() ==
WiFiDirectAdvertisementPublisherStatus::Aborted) {
NEARBY_LOGS(INFO) << "Receive WiFi direct/SoftAP Aborted event.";
LOG(INFO) << "Receive WiFi direct/SoftAP Aborted event.";
}
// Publisher is stopped. Need to clean up the publisher.
{
absl::MutexLock lock(&mutex_);
if (publisher_ != nullptr) {
NEARBY_LOGS(ERROR) << "Windows WiFi Hotspot cleanup.";
LOG(ERROR) << "Windows WiFi Hotspot cleanup.";
listener_.ConnectionRequested(connection_requested_token_);
publisher_.StatusChanged(publisher_status_changed_token_);
wifi_direct_device_ = nullptr;
@@ -381,8 +377,8 @@ fire_and_forget WifiHotspotMedium::OnConnectionRequested(
WiFiDirectConnectionRequestedEventArgs const& event) {
WiFiDirectConnectionRequest connection_request = event.GetConnectionRequest();
winrt::hstring device_name = connection_request.DeviceInformation().Name();
NEARBY_LOGS(INFO) << "Receive connection request from: "
<< winrt::to_string(device_name);
LOG(INFO) << "Receive connection request from: "
<< winrt::to_string(device_name);
try {
// This is to solve b/236805122.
@@ -395,9 +391,9 @@ fire_and_forget WifiHotspotMedium::OnConnectionRequested(
wifi_direct_device_ = WiFiDirectDevice::FromIdAsync(
connection_request.DeviceInformation().Id())
.get();
NEARBY_LOGS(INFO) << "Registered the device in WLAN-AutoConfig";
LOG(INFO) << "Registered the device in WLAN-AutoConfig";
} catch (...) {
NEARBY_LOGS(ERROR) << "Failed to registered the device in WLAN-AutoConfig";
LOG(ERROR) << "Failed to registered the device in WLAN-AutoConfig";
wifi_direct_device_ = nullptr;
connection_request.Close();
}
@@ -410,27 +406,26 @@ bool WifiHotspotMedium::ConnectWifiHotspot(
try {
if (!wifi_connected_hotspot_ssid_.empty()) {
NEARBY_LOGS(INFO) << "Before connecting to Hotspot, Delete the previous "
"Hotspot profile with SSID: "
<< winrt::to_string(wifi_connected_hotspot_ssid_);
LOG(INFO) << "Before connecting to Hotspot, Delete the previous "
"Hotspot profile with SSID: "
<< winrt::to_string(wifi_connected_hotspot_ssid_);
DeleteNetworkProfile(wifi_connected_hotspot_ssid_);
wifi_connected_hotspot_ssid_ = winrt::hstring(L"");
}
if (IsConnected()) {
NEARBY_LOGS(WARNING) << "Already connected to Hotspot, disconnect first.";
LOG(WARNING) << "Already connected to Hotspot, disconnect first.";
InternalDisconnectWifiHotspot();
}
auto access = WiFiAdapter::RequestAccessAsync().get();
if (access != WiFiAccessStatus::Allowed) {
NEARBY_LOGS(WARNING) << "Access Denied with reason: "
<< static_cast<int>(access);
LOG(WARNING) << "Access Denied with reason: " << static_cast<int>(access);
return false;
}
auto adapters = WiFiAdapter::FindAllAdaptersAsync().get();
if (adapters.Size() < 1) {
NEARBY_LOGS(WARNING) << "No WiFi Adapter found.";
LOG(WARNING) << "No WiFi Adapter found.";
return false;
}
wifi_adapter_ = adapters.GetAt(0);
@@ -461,8 +456,8 @@ bool WifiHotspotMedium::ConnectWifiHotspot(
}
}
NEARBY_LOGS(INFO) << "Scanning for Nearby Hotspot SSID: "
<< hotspot_credentials_->GetSSID();
LOG(INFO) << "Scanning for Nearby Hotspot SSID: "
<< hotspot_credentials_->GetSSID();
// First time scan may not find our target hotspot, try 2 more times can
// almost guarantee to find the Hotspot
wifi_adapter_.ScanAsync().get();
@@ -479,23 +474,22 @@ bool WifiHotspotMedium::ConnectWifiHotspot(
if (!wifi_original_network_ && !ssid.empty() &&
(winrt::to_string(network.Ssid()) == ssid)) {
wifi_original_network_ = network;
NEARBY_LOGS(INFO) << "Save the current connected network: " << ssid;
LOG(INFO) << "Save the current connected network: " << ssid;
} else if (!nearby_softap && winrt::to_string(network.Ssid()) ==
hotspot_credentials_->GetSSID()) {
NEARBY_LOGS(INFO)
<< "Found Nearby SSID: " << winrt::to_string(network.Ssid());
LOG(INFO) << "Found Nearby SSID: "
<< winrt::to_string(network.Ssid());
nearby_softap = network;
}
if (nearby_softap && (ssid.empty() || wifi_original_network_))
break;
if (nearby_softap && (ssid.empty() || wifi_original_network_)) break;
}
if (nearby_softap) break;
NEARBY_LOGS(INFO) << "Scan ... ";
LOG(INFO) << "Scan ... ";
wifi_adapter_.ScanAsync().get();
}
NEARBY_LOGS(INFO) << "Finish scanning "
<< (nearby_softap ? "successfully" : "failed") << " with "
<< i+1 << " times trying.";
LOG(INFO) << "Finish scanning "
<< (nearby_softap ? "successfully" : "failed") << " with "
<< i + 1 << " times trying.";
if (intel_wifi_started) {
WifiIntel& intel_wifi{WifiIntel::GetInstance()};
@@ -504,7 +498,7 @@ bool WifiHotspotMedium::ConnectWifiHotspot(
}
if (!nearby_softap) {
NEARBY_LOGS(INFO) << "Hotspot is not found";
LOG(INFO) << "Hotspot is not found";
return false;
}
PasswordCredential creds;
@@ -517,8 +511,8 @@ bool WifiHotspotMedium::ConnectWifiHotspot(
if (connect_result == nullptr ||
connect_result.ConnectionStatus() != WiFiConnectionStatus::Success) {
NEARBY_LOGS(INFO) << "Connecting failed with reason: "
<< static_cast<int>(connect_result.ConnectionStatus());
LOG(INFO) << "Connecting failed with reason: "
<< static_cast<int>(connect_result.ConnectionStatus());
RestoreWifiConnection();
return false;
}
@@ -532,11 +526,11 @@ bool WifiHotspotMedium::ConnectWifiHotspot(
NearbyFlags::GetInstance().GetInt64Flag(
platform::config_package_nearby::nearby_platform_feature::
kWifiHotspotCheckIpIntervalMillis);
NEARBY_LOGS(INFO) << "maximum IP check retries=" << ip_address_max_retries
<< ", IP check interval="
<< ip_address_retry_interval_millis << "ms";
LOG(INFO) << "maximum IP check retries=" << ip_address_max_retries
<< ", IP check interval=" << ip_address_retry_interval_millis
<< "ms";
for (int i = 0; i < ip_address_max_retries; i++) {
NEARBY_LOGS(INFO) << "Check IP address at attemp " << i;
LOG(INFO) << "Check IP address at attemp " << i;
std::vector<std::string> ip_addresses = GetIpv4Addresses();
if (ip_addresses.empty()) {
Sleep(ip_address_retry_interval_millis);
@@ -547,30 +541,28 @@ bool WifiHotspotMedium::ConnectWifiHotspot(
}
if (ip_address.empty()) {
NEARBY_LOGS(INFO) << "Failed to get IP address from hotspot.";
LOG(INFO) << "Failed to get IP address from hotspot.";
RestoreWifiConnection();
DeleteNetworkProfile(nearby_softap.Ssid());
return false;
}
NEARBY_LOGS(INFO) << "Got IP address " << ip_address << " from hotspot.";
LOG(INFO) << "Got IP address " << ip_address << " from hotspot.";
std::string last_ssid = hotspot_credentials_->GetSSID();
wifi_connected_hotspot_ssid_ = nearby_softap.Ssid();
medium_status_ |= kMediumStatusConnected;
NEARBY_LOGS(INFO) << "Connected to hotspot: " << last_ssid;
LOG(INFO) << "Connected to hotspot: " << last_ssid;
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Cannot connet to Hotspot. Exception: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Cannot connet to Hotspot. Exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__
<< ": Cannot connet to Hotspot. WinRT exception: "
<< error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": Cannot connet to Hotspot. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
}
return false;
}
@@ -590,15 +582,15 @@ void WifiHotspotMedium::RestoreWifiConnection() {
profile.WlanConnectionProfileDetails().GetConnectedSsid());
if (!ssid.empty() &&
(winrt::to_string(wifi_original_network_.Ssid()) == ssid)) {
NEARBY_LOGS(INFO) << "Already conneted to the previous WIFI network "
<< ssid << "! Skip restoration.";
LOG(INFO) << "Already conneted to the previous WIFI network " << ssid
<< "! Skip restoration.";
return;
}
}
// Disconnect to the WiFi connection through the WiFi adapter.
wifi_adapter_.Disconnect();
NEARBY_LOGS(INFO) << "Disconnected to current network.";
LOG(INFO) << "Disconnected to current network.";
auto connect_result = wifi_adapter_
.ConnectAsync(wifi_original_network_,
@@ -607,11 +599,11 @@ void WifiHotspotMedium::RestoreWifiConnection() {
if (connect_result == nullptr ||
connect_result.ConnectionStatus() != WiFiConnectionStatus::Success) {
NEARBY_LOGS(INFO) << "Connecting to previous network failed with reason: "
<< static_cast<int>(connect_result.ConnectionStatus());
LOG(INFO) << "Connecting to previous network failed with reason: "
<< static_cast<int>(connect_result.ConnectionStatus());
} else {
NEARBY_LOGS(INFO) << "Restored the previous WIFI connection: "
<< winrt::to_string(wifi_original_network_.Ssid());
LOG(INFO) << "Restored the previous WIFI connection: "
<< winrt::to_string(wifi_original_network_.Ssid());
}
wifi_original_network_ = nullptr;
}
@@ -622,22 +614,21 @@ bool WifiHotspotMedium::DisconnectWifiHotspot() {
try {
return InternalDisconnectWifiHotspot();
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Stop Hotspot failed. Exception: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Stop Hotspot failed. Exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": Stop Hotspot failed. WinRT exception: "
<< error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << __func__
<< ": Stop Hotspot failed. WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
}
return false;
}
bool WifiHotspotMedium::InternalDisconnectWifiHotspot() {
if (!IsConnected()) {
NEARBY_LOGS(WARNING)
<< "Cannot disconnect SoftAP because it is not connected.";
LOG(WARNING) << "Cannot disconnect SoftAP because it is not connected.";
return true;
}
@@ -647,9 +638,8 @@ bool WifiHotspotMedium::InternalDisconnectWifiHotspot() {
wifi_adapter_ = nullptr;
if (!wifi_connected_hotspot_ssid_.empty()) {
NEARBY_LOGS(INFO)
<< "Delete the previous connected network profile with SSID: "
<< winrt::to_string(wifi_connected_hotspot_ssid_);
LOG(INFO) << "Delete the previous connected network profile with SSID: "
<< winrt::to_string(wifi_connected_hotspot_ssid_);
DeleteNetworkProfile(wifi_connected_hotspot_ssid_);
wifi_connected_hotspot_ssid_ = winrt::hstring(L"");
}
@@ -665,21 +655,20 @@ bool WifiHotspotMedium::DeleteNetworkProfile(winrt::hstring ssid) {
auto connections = NetworkInformation::GetConnectionProfiles();
auto ssid_string = winrt::to_string(ssid);
if (ssid_string.empty()) {
NEARBY_LOGS(INFO) << "SSID is empty. No need to delete the network profile";
LOG(INFO) << "SSID is empty. No need to delete the network profile";
return true;
}
NEARBY_LOGS(INFO) << "Search profile with SSID: " << ssid_string;
LOG(INFO) << "Search profile with SSID: " << ssid_string;
for (const auto& connection_profile : connections) {
if (connection_profile.ProfileName() == ssid) {
NEARBY_LOGS(INFO) << "Found the network profile with SSID: "
<< ssid_string;
LOG(INFO) << "Found the network profile with SSID: " << ssid_string;
profile = connection_profile;
break;
}
}
if (profile == nullptr) {
NEARBY_LOGS(INFO) << "No network profile found with SSID: " << ssid_string;
LOG(INFO) << "No network profile found with SSID: " << ssid_string;
return result;
}
@@ -688,21 +677,20 @@ bool WifiHotspotMedium::DeleteNetworkProfile(winrt::hstring ssid) {
auto profile_delete_status = profile.TryDeleteAsync().get();
switch (profile_delete_status) {
case ConnectionProfileDeleteStatus::Success:
NEARBY_LOGS(INFO) << "WiFi profile with SSID:" << ssid_string
<< " is deleted.";
LOG(INFO) << "WiFi profile with SSID:" << ssid_string << " is deleted.";
result = true;
break;
case ConnectionProfileDeleteStatus::DeniedBySystem:
NEARBY_LOGS(ERROR) << "Failed to delete WiFi profile with SSID:"
<< ssid_string << " due to denied by system.";
LOG(ERROR) << "Failed to delete WiFi profile with SSID:" << ssid_string
<< " due to denied by system.";
break;
case ConnectionProfileDeleteStatus::DeniedByUser:
NEARBY_LOGS(ERROR) << "Failed to delete WiFi profile with SSID:"
<< ssid_string << " due to denied by user.";
LOG(ERROR) << "Failed to delete WiFi profile with SSID:" << ssid_string
<< " due to denied by user.";
break;
case ConnectionProfileDeleteStatus::UnknownError:
NEARBY_LOGS(ERROR) << "Failed to delete WiFi profile with SSID:"
<< ssid_string << " due to unknonw error.";
LOG(ERROR) << "Failed to delete WiFi profile with SSID:" << ssid_string
<< " due to unknonw error.";
break;
default:
break;
@@ -58,8 +58,8 @@ std::string WifiHotspotServerSocket::GetIPAddress() const {
}
std::string hotspot_ip_address = GetHotspotIpAddress();
NEARBY_LOGS(INFO) << __func__
<< ": Return hotspot IP address: " << hotspot_ip_address;
LOG(INFO) << __func__
<< ": Return hotspot IP address: " << hotspot_ip_address;
return hotspot_ip_address;
}
@@ -69,7 +69,7 @@ int WifiHotspotServerSocket::GetPort() const {
platform::config_package_nearby::nearby_platform_feature::
kEnableHotspotWin32Socket)) {
if (listen_socket_ == INVALID_SOCKET) {
NEARBY_LOGS(WARNING) << __func__ << ": listen_socket_ is invalid.";
LOG(WARNING) << __func__ << ": listen_socket_ is invalid.";
return 0;
}
return port_;
@@ -83,7 +83,7 @@ int WifiHotspotServerSocket::GetPort() const {
std::unique_ptr<api::WifiHotspotSocket> WifiHotspotServerSocket::Accept() {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__ << ": Accept is called.";
LOG(INFO) << __func__ << ": Accept is called.";
if (NearbyFlags::GetInstance().GetBoolFlag(
platform::config_package_nearby::nearby_platform_feature::
@@ -95,7 +95,7 @@ std::unique_ptr<api::WifiHotspotSocket> WifiHotspotServerSocket::Accept() {
SOCKET wifi_hotspot_socket = pending_client_sockets_.front();
pending_client_sockets_.pop_front();
NEARBY_LOGS(INFO) << __func__ << ": Accepted a remote connection.";
LOG(INFO) << __func__ << ": Accepted a remote connection.";
return std::make_unique<WifiHotspotSocket>(wifi_hotspot_socket);
}
@@ -107,7 +107,7 @@ std::unique_ptr<api::WifiHotspotSocket> WifiHotspotServerSocket::Accept() {
StreamSocket wifi_hotspot_socket = pending_sockets_.front();
pending_sockets_.pop_front();
NEARBY_LOGS(INFO) << __func__ << ": Accepted a remote connection.";
LOG(INFO) << __func__ << ": Accepted a remote connection.";
return std::make_unique<WifiHotspotSocket>(wifi_hotspot_socket);
}
@@ -119,7 +119,7 @@ void WifiHotspotServerSocket::SetCloseNotifier(
Exception WifiHotspotServerSocket::Close() {
try {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__ << ": Close is called.";
LOG(INFO) << __func__ << ": Close is called.";
if (closed_) {
return {Exception::kSuccess};
@@ -129,7 +129,7 @@ Exception WifiHotspotServerSocket::Close() {
platform::config_package_nearby::nearby_platform_feature::
kEnableHotspotWin32Socket)) {
if (listen_socket_ != INVALID_SOCKET) {
NEARBY_LOGS(INFO) << ": Close listen_socket_: " << listen_socket_;
LOG(INFO) << ": Close listen_socket_: " << listen_socket_;
// Trigger close event manually
WSASetEvent(socket_events_[kSocketEventClose]);
shutdown(listen_socket_, 2);
@@ -170,23 +170,23 @@ Exception WifiHotspotServerSocket::Close() {
close_notifier_();
}
NEARBY_LOGS(INFO) << __func__ << ": Close completed succesfully.";
LOG(INFO) << __func__ << ": Close completed succesfully.";
return {Exception::kSuccess};
} catch (std::exception exception) {
closed_ = true;
cond_.SignalAll();
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error &error) {
closed_ = true;
cond_.SignalAll();
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
closed_ = true;
cond_.SignalAll();
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -195,7 +195,7 @@ fire_and_forget WifiHotspotServerSocket::Listener_ConnectionReceived(
StreamSocketListener listener,
StreamSocketListenerConnectionReceivedEventArgs const &args) {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__ << ": Received connection.";
LOG(INFO) << __func__ << ": Received connection.";
if (closed_) {
return fire_and_forget{};
@@ -231,17 +231,16 @@ bool WifiHotspotServerSocket::SetupServerSocketWinRT() {
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR)
<< __func__
<< ": Cannot accept connection on preferred port. Exception: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Cannot accept connection on preferred port. Exception: "
<< exception.what();
} catch (const winrt::hresult_error &error) {
NEARBY_LOGS(ERROR)
LOG(ERROR)
<< __func__
<< ":Cannot accept connection on preferred port. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
}
try {
@@ -249,26 +248,25 @@ bool WifiHotspotServerSocket::SetupServerSocketWinRT() {
// need to save the port information.
port_ =
std::stoi(stream_socket_listener_.Information().LocalPort().c_str());
NEARBY_LOGS(INFO) << "Server Socket port: " << port_;
LOG(INFO) << "Server Socket port: " << port_;
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Cannot bind to any port. Exception: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Cannot bind to any port. Exception: " << exception.what();
} catch (const winrt::hresult_error &error) {
NEARBY_LOGS(ERROR) << __func__
<< ": Cannot bind to any port. WinRT exception: "
<< error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << __func__
<< ": Cannot bind to any port. WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
}
return false;
}
void WifiHotspotServerSocket::SocketErrorNotice(absl::string_view reason) {
NEARBY_LOGS(WARNING) << "socket error. " << reason
<< " failed with error: " << WSAGetLastError();
LOG(WARNING) << "socket error. " << reason
<< " failed with error: " << WSAGetLastError();
for (auto &it : socket_events_) {
if (it != WSA_INVALID_EVENT) {
WSACloseEvent(it);
@@ -285,13 +283,13 @@ bool WifiHotspotServerSocket::SetupServerSocketWinSock() {
int result = WSAStartup(MAKEWORD(2, 2), &wsa_data);
if (result != 0) {
NEARBY_LOGS(WARNING) << "WSAStartup failed with error:" << result;
LOG(WARNING) << "WSAStartup failed with error:" << result;
return false;
}
listen_socket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listen_socket_ == INVALID_SOCKET) {
NEARBY_LOGS(WARNING) << "Failed to get socket";
LOG(WARNING) << "Failed to get socket";
WSACleanup();
return false;
}
@@ -309,7 +307,7 @@ bool WifiHotspotServerSocket::SetupServerSocketWinSock() {
SocketErrorNotice("Bind");
return false;
}
NEARBY_LOGS(INFO) << "Bind socket successful";
LOG(INFO) << "Bind socket successful";
int size = sizeof(serv_addr);
memset(&serv_addr, 0, size);
@@ -319,7 +317,7 @@ bool WifiHotspotServerSocket::SetupServerSocketWinSock() {
return false;
}
port_ = ntohs(serv_addr.sin_port);
NEARBY_LOGS(INFO) << "Hotspot Server bound to port: " << port_;
LOG(INFO) << "Hotspot Server bound to port: " << port_;
socket_events_[kSocketEventListen] = WSACreateEvent();
if (socket_events_[kSocketEventListen] == WSA_INVALID_EVENT) {
@@ -345,8 +343,8 @@ bool WifiHotspotServerSocket::SetupServerSocketWinSock() {
SocketErrorNotice("Listen");
return false;
}
NEARBY_LOGS(INFO) << "Hotspot Server Socket " << listen_socket_
<< " started to listen.";
LOG(INFO) << "Hotspot Server Socket " << listen_socket_
<< " started to listen.";
submittable_executor_.Execute([this]() {
DWORD index;
@@ -355,33 +353,33 @@ bool WifiHotspotServerSocket::SetupServerSocketWinSock() {
index = WSAWaitForMultipleEvents(kSocketEventsCount, socket_events_, FALSE,
WSA_INFINITE, FALSE);
NEARBY_LOGS(INFO) << "Hotspot Server Socket " << listen_socket_
<< " received event index: " << index;
LOG(INFO) << "Hotspot Server Socket " << listen_socket_
<< " received event index: " << index;
if (index == WSA_WAIT_TIMEOUT || index == WSA_WAIT_FAILED) {
NEARBY_LOGS(INFO) << "Hotspot Server Socket timout or failed ";
LOG(INFO) << "Hotspot Server Socket timout or failed ";
return false;
}
index = index - WSA_WAIT_EVENT_0;
if (index == kSocketEventClose) {
// the socket is closed by SDK
NEARBY_LOGS(INFO) << "listner socket is closed.";
LOG(INFO) << "listner socket is closed.";
return false;
}
// Iterate through all events and enumerate
if (WSAEnumNetworkEvents(listen_socket_, socket_events_[index],
&network_events) == SOCKET_ERROR) {
NEARBY_LOGS(INFO) << "Iterate through all events failed";
LOG(INFO) << "Iterate through all events failed";
return false;
}
if (network_events.lNetworkEvents & FD_CLOSE) {
NEARBY_LOGS(INFO) << "Reveived FD_CLOSE event";
LOG(INFO) << "Reveived FD_CLOSE event";
return false;
}
if (network_events.lNetworkEvents & FD_ACCEPT) {
client_socket_ = accept(listen_socket_, nullptr, nullptr);
NEARBY_LOGS(INFO) << "Reveived FD_ACCEPT event.";
LOG(INFO) << "Reveived FD_ACCEPT event.";
if (client_socket_ == INVALID_SOCKET) {
return false;
@@ -389,13 +387,12 @@ bool WifiHotspotServerSocket::SetupServerSocketWinSock() {
if (WSAEventSelect(listen_socket_, socket_events_[kSocketEventListen],
0) == SOCKET_ERROR) {
NEARBY_LOGS(WARNING)
LOG(WARNING)
<< "Remove association between listen_socket_ and event failed: "
<< WSAGetLastError();
}
NEARBY_LOGS(INFO) << "Hotspot Server Client Socket created: "
<< client_socket_;
LOG(INFO) << "Hotspot Server Client Socket created: " << client_socket_;
if (closed_) {
return false;
}
@@ -419,24 +416,23 @@ bool WifiHotspotServerSocket::listen() {
NearbyFlags::GetInstance().GetInt64Flag(
platform::config_package_nearby::nearby_platform_feature::
kWifiHotspotCheckIpIntervalMillis);
NEARBY_LOGS(INFO) << "maximum IP check retries=" << ip_address_max_retries
<< ", IP check interval="
<< ip_address_retry_interval_millis << "ms";
LOG(INFO) << "maximum IP check retries=" << ip_address_max_retries
<< ", IP check interval=" << ip_address_retry_interval_millis
<< "ms";
for (int i = 0; i < ip_address_max_retries; i++) {
hotspot_ipaddr_ = GetHotspotIpAddress();
if (hotspot_ipaddr_.empty()) {
NEARBY_LOGS(WARNING) << "Failed to find Hotspot's IP addr for the try: "
<< i + 1 << ". Wait "
<< ip_address_retry_interval_millis
<< "ms snd try again";
LOG(WARNING) << "Failed to find Hotspot's IP addr for the try: " << i + 1
<< ". Wait " << ip_address_retry_interval_millis
<< "ms snd try again";
Sleep(ip_address_retry_interval_millis);
} else {
break;
}
}
if (hotspot_ipaddr_.empty()) {
NEARBY_LOGS(WARNING) << "Failed to start accepting connection without IP "
"addresses configured on computer.";
LOG(WARNING) << "Failed to start accepting connection without IP "
"addresses configured on computer.";
return false;
}
@@ -476,24 +472,24 @@ std::string WifiHotspotServerSocket::GetHotspotIpAddress() const {
// Windows always creates Hotspot at address "192.168.137.1".
for (auto &ip_candidate : ip_candidates) {
if (ip_candidate == "192.168.137.1") {
NEARBY_LOGS(INFO) << "Found Hotspot IP: " << ip_candidate;
LOG(INFO) << "Found Hotspot IP: " << ip_candidate;
return ip_candidate;
}
}
NEARBY_LOGS(INFO) << "Found Hotspot IP: " << ip_candidates.front();
LOG(INFO) << "Found Hotspot IP: " << ip_candidates.front();
return ip_candidates.front();
}
return {};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {};
} catch (const winrt::hresult_error &error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {};
}
}
@@ -12,11 +12,16 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include <cstdint>
#include <cstring>
#include <exception>
#include "internal/platform/byte_array.h"
#include "internal/platform/exception.h"
#include "internal/platform/implementation/windows/wifi_hotspot.h"
#include "internal/platform/input_stream.h"
#include "internal/platform/logging.h"
#include "internal/platform/output_stream.h"
namespace nearby {
namespace windows {
@@ -44,12 +49,12 @@ WifiHotspotSocket::~WifiHotspotSocket() {
Close();
}
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
}
}
@@ -68,14 +73,14 @@ Exception WifiHotspotSocket::Close() {
}
return {Exception::kSuccess};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -101,7 +106,7 @@ ExceptionOr<ByteArray> WifiHotspotSocket::SocketInputStream::Read(
input_stream_.ReadAsync(buffer, size, InputStreamOptions::None).get();
if (ibuffer.Length() != size) {
NEARBY_LOGS(WARNING) << "Only got part of data of needed.";
LOG(WARNING) << "Only got part of data of needed.";
}
ByteArray data((char*)ibuffer.data(), ibuffer.Length());
@@ -118,7 +123,7 @@ ExceptionOr<ByteArray> WifiHotspotSocket::SocketInputStream::Read(
return ExceptionOr<ByteArray>(data);
}
if (result == 0) {
NEARBY_LOGS(INFO) << "Connection closed.";
LOG(INFO) << "Connection closed.";
return {Exception::kIo};
}
// When WSAEWOULDBLOCK happens, it means the packet for receive is not
@@ -139,14 +144,14 @@ ExceptionOr<ByteArray> WifiHotspotSocket::SocketInputStream::Read(
}
return {Exception::kIo};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -171,7 +176,7 @@ ExceptionOr<size_t> WifiHotspotSocket::SocketInputStream::Skip(size_t offset) {
return ExceptionOr<size_t>((size_t)result);
}
if (result == 0) {
NEARBY_LOGS(INFO) << "Connection closed.";
LOG(INFO) << "Connection closed.";
} else {
// When WSAEWOULDBLOCK happens, it means the packet for receive is not
// ready at the moment. The API select() will block till the packet is
@@ -191,14 +196,14 @@ ExceptionOr<size_t> WifiHotspotSocket::SocketInputStream::Skip(size_t offset) {
}
return {Exception::kIo};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -213,14 +218,14 @@ Exception WifiHotspotSocket::SocketInputStream::Close() {
}
return {Exception::kSuccess};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -256,18 +261,18 @@ Exception WifiHotspotSocket::SocketOutputStream::Write(const ByteArray& data) {
if (result > 0) {
return {Exception::kSuccess};
}
NEARBY_LOGS(INFO) << "recv failed: " << WSAGetLastError();
LOG(INFO) << "recv failed: " << WSAGetLastError();
return {Exception::kIo};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -279,14 +284,14 @@ Exception WifiHotspotSocket::SocketOutputStream::Flush() {
}
return {Exception::kSuccess};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -301,14 +306,14 @@ Exception WifiHotspotSocket::SocketOutputStream::Close() {
}
return {Exception::kSuccess};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -12,16 +12,18 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal/platform/implementation/windows/wifi_hotspot.h"
#include <iostream>
#include <memory>
#include <string>
#include "gtest/gtest.h"
#include "absl/time/clock.h"
#include "internal/flags/nearby_flags.h"
#include "internal/platform/flags/nearby_platform_feature_flags.h"
#include "internal/platform/logging.h"
#include "internal/platform/wifi_credential.h"
#include "internal/platform/implementation/windows/wifi_hotspot.h"
namespace nearby {
namespace windows {
@@ -29,7 +31,7 @@ namespace {
TEST(WifiHotspotMedium, DISABLED_StartWifiHotspot) {
int run_test;
NEARBY_LOGS(INFO) << "Run StartWifiHotspot test case? input 0 or 1:";
LOG(INFO) << "Run StartWifiHotspot test case? input 0 or 1:";
std::cin >> run_test;
if (run_test) {
@@ -45,23 +47,23 @@ TEST(WifiHotspotMedium, DISABLED_StartWifiHotspot) {
EXPECT_TRUE(hotspot_medium.StartWifiHotspot(&hotspot_credentials));
while (true) {
NEARBY_LOGS(INFO) << "Enter \"s\" to stop test:";
LOG(INFO) << "Enter \"s\" to stop test:";
std::string stop;
std::cin >> stop;
if (stop == "s") {
NEARBY_LOGS(INFO) << "Exit WiFi Hotspot";
LOG(INFO) << "Exit WiFi Hotspot";
EXPECT_TRUE(hotspot_medium.StopWifiHotspot());
break;
}
}
} else {
NEARBY_LOGS(INFO) << "Skip the test";
LOG(INFO) << "Skip the test";
}
}
TEST(WifiHotspotMedium, DISABLED_WifiHotspotServerStartListen) {
int run_test;
NEARBY_LOGS(INFO) << "Run WifiHotspotServerStartListen test? input 0 or 1:";
LOG(INFO) << "Run WifiHotspotServerStartListen test? input 0 or 1:";
std::cin >> run_test;
if (run_test) {
@@ -78,37 +80,36 @@ TEST(WifiHotspotMedium, DISABLED_WifiHotspotServerStartListen) {
server_socket->Accept();
while (true) {
NEARBY_LOGS(INFO) << "Enter \"s\" to stop test:";
LOG(INFO) << "Enter \"s\" to stop test:";
std::string stop;
std::cin >> stop;
if (stop == "s") {
NEARBY_LOGS(INFO) << "Close server socket and stop WiFi Hotspot";
LOG(INFO) << "Close server socket and stop WiFi Hotspot";
server_socket->Close();
EXPECT_TRUE(hotspot_medium.StopWifiHotspot());
break;
}
}
} else {
NEARBY_LOGS(INFO) << "Skip the test";
LOG(INFO) << "Skip the test";
}
}
TEST(WifiHotspotMedium, DISABLED_ConnectWifiHotspot) {
int run_test;
NEARBY_LOGS(INFO) << "Run ConnectWifiHotspot test case? input 0 or 1:";
LOG(INFO) << "Run ConnectWifiHotspot test case? input 0 or 1:";
std::cin >> run_test;
if (run_test) {
HotspotCredentials hotspot_credentials;
WifiHotspotMedium hotspot_medium;
NEARBY_LOGS(INFO) << "Enter Network SSID to be connected: ";
LOG(INFO) << "Enter Network SSID to be connected: ";
std::string ssid;
std::cin >> ssid;
NEARBY_LOGS(INFO) << "Enter password: ";
LOG(INFO) << "Enter password: ";
std::string password;
std::cin >> password;
NEARBY_LOGS(INFO) << "Enter frequency(input 0 if unknown): ";
LOG(INFO) << "Enter frequency(input 0 if unknown): ";
int frequency;
std::cin >> frequency;
@@ -124,17 +125,17 @@ TEST(WifiHotspotMedium, DISABLED_ConnectWifiHotspot) {
EXPECT_TRUE(hotspot_medium.ConnectWifiHotspot(&hotspot_credentials));
absl::SleepFor(absl::Seconds(1));
while (true) {
NEARBY_LOGS(INFO) << "Enter \"s\" to stop test:";
LOG(INFO) << "Enter \"s\" to stop test:";
std::string stop;
std::cin >> stop;
if (stop == "s") {
NEARBY_LOGS(INFO) << "Disconnect WiFi";
LOG(INFO) << "Disconnect WiFi";
EXPECT_TRUE(hotspot_medium.DisconnectWifiHotspot());
break;
}
}
} else {
NEARBY_LOGS(INFO) << "Skip the test";
LOG(INFO) << "Skip the test";
}
}
@@ -46,43 +46,43 @@ namespace nearby {
namespace windows {
namespace {
#define SAFEDELETE(x) \
{ \
try { \
if (x) { \
delete x; \
x = nullptr; \
} \
} catch (...) { \
NEARBY_LOGS(INFO) << absl::StrFormat( \
"Exception while delete memory at 0x%p ", (void*)x); \
} \
#define SAFEDELETE(x) \
{ \
try { \
if (x) { \
delete x; \
x = nullptr; \
} \
} catch (...) { \
LOG(INFO) << absl::StrFormat("Exception while delete memory at 0x%p ", \
(void*)x); \
} \
}
#define SAFEDELETEARRAY(x) \
{ \
try { \
if (x) { \
delete[] x; \
x = nullptr; \
} \
} catch (...) { \
NEARBY_LOGS(INFO) << absl::StrFormat( \
"Exception while delete memory at 0x%p ", (void*)x); \
} \
#define SAFEDELETEARRAY(x) \
{ \
try { \
if (x) { \
delete[] x; \
x = nullptr; \
} \
} catch (...) { \
LOG(INFO) << absl::StrFormat("Exception while delete memory at 0x%p ", \
(void*)x); \
} \
}
#define SAFEFREELIBRARY(x) \
{ \
try { \
if (x) { \
FreeLibrary(x); \
x = nullptr; \
} \
} catch (...) { \
NEARBY_LOGS(INFO) << absl::StrFormat( \
"Exception while freeing library at 0x%p ", (void*)x); \
} \
#define SAFEFREELIBRARY(x) \
{ \
try { \
if (x) { \
FreeLibrary(x); \
x = nullptr; \
} \
} catch (...) { \
LOG(INFO) << absl::StrFormat("Exception while freeing library at 0x%p ", \
(void*)x); \
} \
}
#ifndef NO_INTEL_PIE
@@ -143,11 +143,11 @@ WifiIntel& WifiIntel::GetInstance() {
}
bool WifiIntel::Start() {
NEARBY_LOGS(INFO) << "WifiIntel::Start()";
LOG(INFO) << "WifiIntel::Start()";
#ifndef NO_INTEL_PIE
muroc_api_dll_handle_ = PIEDllLoader();
if ((muroc_api_dll_handle_ != nullptr)) {
NEARBY_LOGS(INFO) << "Load PIE_API_DLL completed successfully";
LOG(INFO) << "Load PIE_API_DLL completed successfully";
wifi_adapter_handle_ =
WifiGetAdapterList(muroc_api_dll_handle_, &p_all_adapters_);
@@ -159,23 +159,23 @@ bool WifiIntel::Start() {
}
}
#else
NEARBY_LOGS(INFO) << "NO_INTEL_PIE found, skip";
LOG(INFO) << "NO_INTEL_PIE found, skip";
#endif
return intel_wifi_valid_;
}
void WifiIntel::Stop() {
NEARBY_LOGS(INFO) << "WifiIntel::Stop()";
LOG(INFO) << "WifiIntel::Stop()";
#ifndef NO_INTEL_PIE
if (intel_wifi_valid_) {
NEARBY_LOGS(INFO) << "Deregister Intel Callback, free Adapters Memory "
"List, free Muroc Api Dll handler.";
LOG(INFO) << "Deregister Intel Callback, free Adapters Memory "
"List, free Muroc Api Dll handler.";
DeregisterIntelCallback(muroc_api_dll_handle_, IntelEventHandler);
FreeMemoryList(muroc_api_dll_handle_, p_all_adapters_);
SAFEFREELIBRARY(muroc_api_dll_handle_);
}
#else
NEARBY_LOGS(INFO) << "NO_INTEL_PIE found, skip";
LOG(INFO) << "NO_INTEL_PIE found, skip";
#endif
}
@@ -198,12 +198,11 @@ int WifiIntel::GetGOChannel() {
if (WifiPanQueryPreferredChannelSettingFunc == nullptr) {
dwError = GetLastError(); // NOLINT
NEARBY_LOGS(INFO)
<< "GetProcAddress WifiPanQueryPreferredChannelSetting error: "
<< dwError;
LOG(INFO) << "GetProcAddress WifiPanQueryPreferredChannelSetting error: "
<< dwError;
return channel;
}
NEARBY_VLOG(1)
VLOG(1)
<< "Load WifiPanQueryPreferredChannelSetting API completed successfully";
intelWifiHeader.dwSize =
@@ -213,22 +212,21 @@ int WifiIntel::GetGOChannel() {
wifi_adapter_handle_, &intelWifiHeader, (void*)&intelGOChan);
if (murocApiRetVal == IWLAN_E_SUCCESS) { // NOLINT
NEARBY_LOGS(INFO)
<< "Calling WifiPanQueryPreferredChannelSetting API succeeded";
LOG(INFO) << "Calling WifiPanQueryPreferredChannelSetting API succeeded";
if (intelGOChan.goState == MurocDefs::INTEL_GO_CURRENT_CHANNEL_ACTIVE) {
channel = intelGOChan.channel;
} else {
NEARBY_LOGS(INFO) << "No active GO found, return -1";
LOG(INFO) << "No active GO found, return -1";
}
} else {
NEARBY_LOGS(INFO) << "Calling WifiPanQueryPreferredChannelSetting API "
"failed with error: "
<< murocApiRetVal;
LOG(INFO) << "Calling WifiPanQueryPreferredChannelSetting API "
"failed with error: "
<< murocApiRetVal;
}
return channel;
#else
NEARBY_LOGS(INFO) << "NO_INTEL_PIE found, return -1";
LOG(INFO) << "NO_INTEL_PIE found, return -1";
return -1;
#endif
}
@@ -244,19 +242,18 @@ bool WifiIntel::SetScanFilter(int channel) {
if (channel <= 0) return false;
if (!intel_wifi_valid_) return false;
NEARBY_LOGS(INFO) << "Set scan channel:" << channel;
LOG(INFO) << "Set scan channel:" << channel;
WifiLegacyGoSetScanFilterFunc =
(WIFILEGACYGOSETSCANFILTER)GetProcAddress( // NOLINT
muroc_api_dll_handle_, "WifiLegacyGoSetScanFilter");
if (WifiLegacyGoSetScanFilterFunc == nullptr) {
dwError = GetLastError(); // NOLINT
NEARBY_LOGS(INFO) << "GetProcAddress WifiLegacyGoSetScanFilterFunc error: "
<< dwError;
LOG(INFO) << "GetProcAddress WifiLegacyGoSetScanFilterFunc error: "
<< dwError;
return false;
}
NEARBY_VLOG(1)
<< "Load WifiLegacyGoSetScanFilterFunc API completed successfully";
VLOG(1) << "Load WifiLegacyGoSetScanFilterFunc API completed successfully";
intelWifiHeader.dwSize = sizeof(MurocDefs::WIFI_LEGACY_GO_SCAN_FILTER);
memset(&scanFilter, 0, sizeof(scanFilter));
@@ -265,18 +262,18 @@ bool WifiIntel::SetScanFilter(int channel) {
wifi_adapter_handle_, &intelWifiHeader, (void*)&scanFilter);
if (murocApiRetVal == IWLAN_E_SUCCESS) { // NOLINT
NEARBY_LOGS(INFO) << "Calling WifiLegacyGoSetScanFilter API "
"succeeded, set scan channel to "
<< channel;
LOG(INFO) << "Calling WifiLegacyGoSetScanFilter API "
"succeeded, set scan channel to "
<< channel;
return true;
}
NEARBY_LOGS(INFO) << "Calling WifiLegacyGoSetScanFilter API "
"failed with error: "
<< murocApiRetVal;
LOG(INFO) << "Calling WifiLegacyGoSetScanFilter API "
"failed with error: "
<< murocApiRetVal;
return false;
#else
NEARBY_LOGS(INFO) << "NO_INTEL_PIE found, return -1";
LOG(INFO) << "NO_INTEL_PIE found, return -1";
return false;
#endif
}
@@ -296,28 +293,27 @@ bool WifiIntel::ResetScanFilter() {
if (WifiPanReSetLegacyGoScanFilterFunc == nullptr) {
dwError = GetLastError(); // NOLINT
NEARBY_LOGS(INFO)
<< "GetProcAddress WifiPanReSetLegacyGoScanFilterFunc error: "
<< dwError;
LOG(INFO) << "GetProcAddress WifiPanReSetLegacyGoScanFilterFunc error: "
<< dwError;
return false;
}
NEARBY_VLOG(1)
VLOG(1)
<< "Load WifiPanReSetLegacyGoScanFilterFunc API completed successfully";
intelWifiHeader.dwSize = 0;
murocApiRetVal = WifiPanReSetLegacyGoScanFilterFunc(wifi_adapter_handle_,
&intelWifiHeader);
if (murocApiRetVal == IWLAN_E_SUCCESS) { // NOLINT
NEARBY_LOGS(INFO) << "Calling WifiPanReSetLegacyGoScanFilter API succeeded";
LOG(INFO) << "Calling WifiPanReSetLegacyGoScanFilter API succeeded";
return true;
}
NEARBY_LOGS(INFO) << "Calling WifiPanQueryPreferredChannelSetting API "
"failed with error: "
<< murocApiRetVal;
LOG(INFO) << "Calling WifiPanQueryPreferredChannelSetting API "
"failed with error: "
<< murocApiRetVal;
return false;
#else
NEARBY_LOGS(INFO) << "NO_INTEL_PIE found, return -1";
LOG(INFO) << "NO_INTEL_PIE found, return -1";
return false;
#endif
}
@@ -343,20 +339,18 @@ wchar_t* GetEntireRegistryDeviceList() {
configRet = CM_Get_Device_ID_ListW(nullptr, pDeviceList, deviceListLength,
CM_GETIDLIST_FILTER_PRESENT);
if (configRet != CR_SUCCESS) {
NEARBY_LOGS(INFO)
<< "Unexpected error! CM_Get_Device_ID_List return Value of "
<< configRet;
LOG(INFO) << "Unexpected error! CM_Get_Device_ID_List return Value of "
<< configRet;
SAFEDELETEARRAY(pDeviceList);
}
} else {
configRet = CR_OUT_OF_MEMORY;
NEARBY_LOGS(INFO)
LOG(INFO)
<< "Unexpected error! failed to allocate memory to the device list";
}
} else {
NEARBY_LOGS(INFO)
<< "Unexpected error! CM_Get_Device_ID_List_Size return Value of "
<< configRet;
LOG(INFO) << "Unexpected error! CM_Get_Device_ID_List_Size return Value of "
<< configRet;
}
return pDeviceList;
@@ -404,15 +398,14 @@ DEVINST SearchForDeviceInstance(wchar_t* pEntireDeviceList) {
configRet =
CM_Locate_DevNodeW(&devInst, currentDevice, CM_LOCATE_DEVNODE_NORMAL);
if (configRet != CR_SUCCESS) {
NEARBY_LOGS(INFO)
<< "Unexpected error! CM_Locate_DevNode return Value of "
<< configRet;
LOG(INFO) << "Unexpected error! CM_Locate_DevNode return Value of "
<< configRet;
devInst = NULL;
break;
}
isMatchingDeviceFound = IsHwIdMatching(devInst, PIE_HW_ID_);
if (isMatchingDeviceFound) {
NEARBY_LOGS(INFO) << "Intel WIFI Device is found!";
LOG(INFO) << "Intel WIFI Device is found!";
break;
} else {
devInst = NULL;
@@ -437,15 +430,14 @@ void OpenRegKeyHandle(DEVINST devInst, HKEY& softwareKey) {
RegDisposition_OpenExisting, &softwareKey,
CM_REGISTRY_SOFTWARE);
NEARBY_VLOG(1) << absl::StrFormat("softwareKey %p ", softwareKey);
VLOG(1) << absl::StrFormat("softwareKey %p ", softwareKey);
if (configRet != CR_SUCCESS) {
NEARBY_LOGS(INFO)
<< "Unexpected error! CM_Open_DevNode_Key return Value of "
<< configRet;
LOG(INFO) << "Unexpected error! CM_Open_DevNode_Key return Value of "
<< configRet;
}
} else {
NEARBY_LOGS(INFO) << "devInst is NULL";
LOG(INFO) << "devInst is NULL";
}
}
@@ -462,7 +454,7 @@ DWORD GetRegKeyWCHARValue(DEVINST deviceInstance, LPCWSTR keyName,
CloseRegKeyHandle(softwareKey);
} else {
NEARBY_LOGS(INFO) << "Couldn't find dev instacne for device :-( ";
LOG(INFO) << "Couldn't find dev instacne for device :-( ";
ret = ERROR_NOT_FOUND; // NOLINT
}
return ret;
@@ -481,15 +473,15 @@ DWORD GetFullDllLoadPathFromPieRegistry(DEVINST pieDeviceInstance,
status = GetRegKeyWCHARValue(pieDeviceInstance, PIE_DLL_PATH_HINT, nullptr,
&dllPathBufferLen, &regKeyDataType);
if (status != ERROR_SUCCESS) {
NEARBY_LOGS(INFO)
<< "Unexpected error! GetRegKeyWCHARValue return Value of " << status;
LOG(INFO) << "Unexpected error! GetRegKeyWCHARValue return Value of "
<< status;
return status;
} else {
NEARBY_VLOG(1) << "Queried key length successfully!";
VLOG(1) << "Queried key length successfully!";
}
dllFullPathLen = (dllPathBufferLen + sizeof(PIE_API_DLL));
NEARBY_VLOG(1) << "dll Full Path Length = " << dllFullPathLen;
VLOG(1) << "dll Full Path Length = " << dllFullPathLen;
pLoadPathString = new wchar_t[dllFullPathLen];
SecureZeroMemory(pLoadPathString, dllFullPathLen); // NOLINT
@@ -499,13 +491,13 @@ DWORD GetFullDllLoadPathFromPieRegistry(DEVINST pieDeviceInstance,
GetRegKeyWCHARValue(pieDeviceInstance, PIE_DLL_PATH_HINT, pLoadPathString,
&dllPathBufferLen, &regKeyDataType);
if (status != ERROR_SUCCESS) {
NEARBY_LOGS(INFO)
<< "Unexpected error! GetRegKeyWCHARValue return Value of " << status;
LOG(INFO) << "Unexpected error! GetRegKeyWCHARValue return Value of "
<< status;
SAFEDELETEARRAY(pLoadPathString);
return status;
} else {
pathString = pLoadPathString;
NEARBY_VLOG(1) << "Queried key successfully!";
VLOG(1) << "Queried key successfully!";
}
std::wstring fullString = pathString + PIE_API_DLL;
@@ -537,16 +529,15 @@ HINSTANCE WifiIntel::PIEDllLoader() {
ret = GetFullDllLoadPathFromPieRegistry(pieRegDeviceInstance, &pDllPathValue);
if (ret == ERROR_SUCCESS) {
NEARBY_LOGS(INFO) << "Found and trying to load MurocApi.dll";
LOG(INFO) << "Found and trying to load MurocApi.dll";
// load the library and get the handle
murocApiDllHandle = LoadLibraryW(pDllPathValue); // NOLINT
NEARBY_VLOG(1) << absl::StrFormat("Muroc Api Dll Handle is 0x%p ",
murocApiDllHandle);
VLOG(1) << absl::StrFormat("Muroc Api Dll Handle is 0x%p ",
murocApiDllHandle);
} else {
NEARBY_LOGS(INFO) << "GetFullDllLoadPathFromPieRegistry fails eith error: "
<< ret;
LOG(INFO) << "GetFullDllLoadPathFromPieRegistry fails eith error: " << ret;
}
SAFEDELETEARRAY(pDllPathValue);
@@ -566,14 +557,14 @@ HADAPTER WifiGetAdapterList(HINSTANCE murocApiDllHandle,
if (WifiGetAdapterListFunction == nullptr) {
dwError = GetLastError();
NEARBY_LOGS(INFO) << "GetProcAddress for WifiGetAdapterListFunction API "
"fails with error: "
<< dwError;
LOG(INFO) << "GetProcAddress for WifiGetAdapterListFunction API "
"fails with error: "
<< dwError;
return INVALID_HADAPTER;
}
NEARBY_VLOG(1) << "GetProcAddress for WifiGetAdapterListFunction API "
"completed successfully";
VLOG(1) << "GetProcAddress for WifiGetAdapterListFunction API "
"completed successfully";
INTEL_WIFI_HEADER intelHeader = {INTEL_STRUCT_VERSION_V156, // NOLINT
sizeof(MurocDefs::INTEL_ADAPTER_LIST_V120)};
MUROC_RET murocApiRetVal = IWLAN_E_FAILURE;
@@ -582,14 +573,13 @@ HADAPTER WifiGetAdapterList(HINSTANCE murocApiDllHandle,
WifiGetAdapterListFunction(&intelHeader, (void**)ppAllAdapters);
if (murocApiRetVal != IWLAN_E_SUCCESS) {
NEARBY_LOGS(INFO)
<< "Calling WifiGetAdapterListFunction API fails with error:"
<< murocApiRetVal;
LOG(INFO) << "Calling WifiGetAdapterListFunction API fails with error:"
<< murocApiRetVal;
return INVALID_HADAPTER;
}
firstAdapterOnTheList = (*ppAllAdapters)->adapter[0].hAdapter;
NEARBY_LOGS(INFO) << "WIFI Adapter on the list: " << firstAdapterOnTheList;
LOG(INFO) << "WIFI Adapter on the list: " << firstAdapterOnTheList;
return firstAdapterOnTheList;
}
@@ -604,22 +594,21 @@ void RegisterIntelCallback(
murocApiDllHandle, "RegisterIntelCallback");
if (registerIntelCBFunc == nullptr) {
dwError = GetLastError();
NEARBY_LOGS(INFO)
<< "GetProcAddress of RegisterIntelCallback API fails with error:"
<< dwError;
LOG(INFO) << "GetProcAddress of RegisterIntelCallback API fails with error:"
<< dwError;
return;
}
NEARBY_VLOG(1) << "Load RegisterIntelCallback API successfully";
VLOG(1) << "Load RegisterIntelCallback API successfully";
MUROC_RET murocApiRetVal = IWLAN_E_FAILURE;
murocApiRetVal = registerIntelCBFunc(pIntelEventCbHandle);
if (murocApiRetVal == IWLAN_E_SUCCESS) {
NEARBY_LOGS(INFO) << "Calling RegisterIntelCallback API succeeded.";
LOG(INFO) << "Calling RegisterIntelCallback API succeeded.";
} else {
NEARBY_LOGS(INFO) << "Calling RegisterIntelCallback API fails with error:"
<< murocApiRetVal;
LOG(INFO) << "Calling RegisterIntelCallback API fails with error:"
<< murocApiRetVal;
}
}
@@ -633,30 +622,29 @@ void DeregisterIntelCallback(HINSTANCE murocApiDllHandle,
if (deregisterIntelCBFunc == nullptr) {
dwError = GetLastError();
NEARBY_LOGS(INFO)
LOG(INFO)
<< "GetProcAddress of DeregisterIntelCallback API failed with error: ",
dwError;
return;
}
{
NEARBY_VLOG(1) << "Load DeregisterIntelCallback API successfully";
VLOG(1) << "Load DeregisterIntelCallback API successfully";
MUROC_RET murocApiRetVal = IWLAN_E_FAILURE;
murocApiRetVal = deregisterIntelCBFunc(fnCallback);
if (murocApiRetVal == IWLAN_E_SUCCESS) {
NEARBY_VLOG(1) << "Calling DeregisterIntelCallback API succeeded.";
VLOG(1) << "Calling DeregisterIntelCallback API succeeded.";
} else {
NEARBY_LOGS(INFO)
<< "Calling DeregisterIntelCallback API fails with error:"
<< murocApiRetVal;
LOG(INFO) << "Calling DeregisterIntelCallback API fails with error:"
<< murocApiRetVal;
}
}
}
void WINAPI IntelEventHandler(MurocDefs::INTEL_EVENT iEvent, void* pContext) {
NEARBY_LOGS(INFO) << "Received Intel Event id: %d" << iEvent.eType;
LOG(INFO) << "Received Intel Event id: %d" << iEvent.eType;
}
void FreeMemoryList(HINSTANCE murocApiDllHandle, void* ptr) {
@@ -668,22 +656,21 @@ void FreeMemoryList(HINSTANCE murocApiDllHandle, void* ptr) {
if (freeMemoryListFunction == nullptr) {
dwError = GetLastError();
NEARBY_LOGS(INFO)
<< "GetProcAddress of FreeListMemory API failed with error: "
<< dwError;
LOG(INFO) << "GetProcAddress of FreeListMemory API failed with error: "
<< dwError;
}
if ((freeMemoryListFunction != nullptr)) {
NEARBY_VLOG(1) << "Load FreeListMemory API successfully";
VLOG(1) << "Load FreeListMemory API successfully";
MUROC_RET murocApiRetVal = IWLAN_E_FAILURE;
murocApiRetVal = freeMemoryListFunction(ptr);
if (murocApiRetVal == IWLAN_E_SUCCESS) {
NEARBY_VLOG(1) << "Calling FreeListMemory API succeeded.";
VLOG(1) << "Calling FreeListMemory API succeeded.";
} else {
NEARBY_LOGS(INFO) << "Calling FreeListMemory API failed with error: "
<< murocApiRetVal;
LOG(INFO) << "Calling FreeListMemory API failed with error: "
<< murocApiRetVal;
}
}
}
@@ -34,13 +34,16 @@
// Nearby connections headers
#include "absl/synchronization/mutex.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
// Nearby connections headers
#include "internal/platform/cancellation_flag.h"
#include "internal/platform/cancellation_flag_listener.h"
#include "internal/platform/exception.h"
#include "internal/platform/feature_flags.h"
#include "internal/platform/implementation/windows/utils.h"
#include "internal/platform/logging.h"
#include "internal/platform/nsd_service_info.h"
#include "internal/platform/runnable.h"
namespace nearby {
@@ -79,35 +82,32 @@ bool WifiLanMedium::StartAdvertising(const NsdServiceInfo& nsd_service_info) {
if ((server_socket.second->GetIPAddress() ==
nsd_service_info.GetIPAddress()) &&
(server_socket.second->GetPort() == nsd_service_info.GetPort())) {
NEARBY_LOGS(INFO) << "Found the server socket."
<< " IP: "
<< ipaddr_4bytes_to_dotdecimal_string(
nsd_service_info.GetIPAddress())
<< "; port: " << nsd_service_info.GetPort();
LOG(INFO) << "Found the server socket." << " IP: "
<< ipaddr_4bytes_to_dotdecimal_string(
nsd_service_info.GetIPAddress())
<< "; port: " << nsd_service_info.GetPort();
server_socket_ptr = server_socket.second;
socket_found = true;
break;
}
}
if (!socket_found) {
NEARBY_LOGS(WARNING)
<< "cannot start advertising without accepting connetions.";
LOG(WARNING) << "cannot start advertising without accepting connetions.";
return false;
}
if (IsAdvertising()) {
NEARBY_LOGS(WARNING)
<< "cannot start advertising again when it is running.";
LOG(WARNING) << "cannot start advertising again when it is running.";
return false;
}
if (nsd_service_info.GetTxtRecord(kDeviceEndpointInfo.data()).empty()) {
NEARBY_LOGS(ERROR) << "cannot start advertising without endpoint info.";
LOG(ERROR) << "cannot start advertising without endpoint info.";
return false;
}
if (nsd_service_info.GetServiceName().empty()) {
NEARBY_LOGS(ERROR) << "cannot start advertising without service name.";
LOG(ERROR) << "cannot start advertising without service name.";
return false;
}
@@ -117,7 +117,7 @@ bool WifiLanMedium::StartAdvertising(const NsdServiceInfo& nsd_service_info) {
absl::StrFormat(kMdnsInstanceNameFormat.data(), service_name_,
nsd_service_info.GetServiceType());
NEARBY_LOGS(INFO) << "mDNS instance name is " << instance_name;
LOG(INFO) << "mDNS instance name is " << instance_name;
dnssd_service_instance_ = DnssdServiceInstance{
string_to_wstring(instance_name),
@@ -140,7 +140,7 @@ bool WifiLanMedium::StartAdvertising(const NsdServiceInfo& nsd_service_info) {
std::vector<std::string> ipv4_addresses = GetIpv4Addresses();
if (!ipv4_addresses.empty()) {
if (ipv4_addresses.size() > 1) {
NEARBY_LOGS(WARNING) << "The device has multiple IPv4 addresses.";
LOG(WARNING) << "The device has multiple IPv4 addresses.";
}
text_attributes.Insert(winrt::to_hstring(std::string(kDeviceIpv4)),
winrt::to_hstring(ipv4_addresses[0]));
@@ -152,22 +152,21 @@ bool WifiLanMedium::StartAdvertising(const NsdServiceInfo& nsd_service_info) {
.get();
if (dnssd_regirstraion_result_.HasInstanceNameChanged()) {
NEARBY_LOGS(WARNING) << "advertising instance name was changed due to have "
"same name instance was running.";
LOG(WARNING) << "advertising instance name was changed due to have "
"same name instance was running.";
// stop the service and return false
StopAdvertising(nsd_service_info);
return false;
}
if (dnssd_regirstraion_result_.Status() == DnssdRegistrationStatus::Success) {
NEARBY_LOGS(INFO) << "started to advertising.";
LOG(INFO) << "started to advertising.";
medium_status_ |= kMediumStatusAdvertising;
return true;
}
// Clean up
NEARBY_LOGS(ERROR)
<< "failed to start advertising due to registration failure.";
LOG(ERROR) << "failed to start advertising due to registration failure.";
dnssd_service_instance_ = nullptr;
dnssd_regirstraion_result_ = nullptr;
return false;
@@ -176,13 +175,13 @@ bool WifiLanMedium::StartAdvertising(const NsdServiceInfo& nsd_service_info) {
// Win32 call only can use globel function or static method in class
void WifiLanMedium::Advertising_StopCompleted(DWORD Status, PVOID pQueryContext,
PDNS_SERVICE_INSTANCE pInstance) {
NEARBY_LOGS(INFO) << "unregister with status=" << Status;
LOG(INFO) << "unregister with status=" << Status;
try {
WifiLanMedium* medium = static_cast<WifiLanMedium*>(pQueryContext);
medium->NotifyDnsServiceUnregistered(Status);
} catch (...) {
NEARBY_LOGS(ERROR) << "failed to notify the stop of DNS service instance."
<< Status;
LOG(ERROR) << "failed to notify the stop of DNS service instance."
<< Status;
}
}
@@ -196,7 +195,7 @@ void WifiLanMedium::NotifyDnsServiceUnregistered(DWORD status) {
bool WifiLanMedium::StopAdvertising(const NsdServiceInfo& nsd_service_info) {
// Need to use Win32 API to deregister the Dnssd instance
if (!IsAdvertising()) {
NEARBY_LOGS(WARNING)
LOG(WARNING)
<< "Cannot stop advertising because no advertising is running.";
return false;
}
@@ -219,7 +218,7 @@ bool WifiLanMedium::StopAdvertising(const NsdServiceInfo& nsd_service_info) {
dns_service_register_request_.InterfaceIndex =
0; // all interfaces will be considered
dns_service_register_request_.unicastEnabled = false;
dns_service_register_request_.hCredentials = NULL;
dns_service_register_request_.hCredentials = nullptr;
dns_service_register_request_.pServiceInstance = &dns_service_instance_;
dns_service_register_request_.pQueryContext = this; // callback use it
dns_service_register_request_.pRegisterCompletionCallback =
@@ -229,8 +228,8 @@ bool WifiLanMedium::StopAdvertising(const NsdServiceInfo& nsd_service_info) {
DWORD status = DnsServiceDeRegister(&dns_service_register_request_, nullptr);
if (status != DNS_REQUEST_PENDING) {
NEARBY_LOGS(ERROR) << "failed to stop mDNS advertising for service type ="
<< nsd_service_info.GetServiceType();
LOG(ERROR) << "failed to stop mDNS advertising for service type ="
<< nsd_service_info.GetServiceType();
return false;
}
@@ -238,13 +237,13 @@ bool WifiLanMedium::StopAdvertising(const NsdServiceInfo& nsd_service_info) {
dns_service_stop_latch_.get()->Await();
dns_service_stop_latch_ = nullptr;
if (dns_service_stop_status_ != 0) {
NEARBY_LOGS(INFO) << "failed to stop mDNS advertising for service type ="
<< nsd_service_info.GetServiceType();
LOG(INFO) << "failed to stop mDNS advertising for service type ="
<< nsd_service_info.GetServiceType();
return false;
}
NEARBY_LOGS(INFO) << "succeeded to stop mDNS advertising for service type ="
<< nsd_service_info.GetServiceType();
LOG(INFO) << "succeeded to stop mDNS advertising for service type ="
<< nsd_service_info.GetServiceType();
medium_status_ &= (~kMediumStatusAdvertising);
return true;
}
@@ -253,8 +252,8 @@ bool WifiLanMedium::StopAdvertising(const NsdServiceInfo& nsd_service_info) {
bool WifiLanMedium::StartDiscovery(const std::string& service_type,
DiscoveredServiceCallback callback) {
if (IsDiscovering()) {
NEARBY_LOGS(WARNING) << "discovery already running for service type ="
<< service_type;
LOG(WARNING) << "discovery already running for service type ="
<< service_type;
return false;
}
@@ -296,7 +295,7 @@ bool WifiLanMedium::StartDiscovery(const std::string& service_type,
discovered_service_callback_ = std::move(callback);
medium_status_ |= kMediumStatusDiscovering;
NEARBY_LOGS(INFO) << "started to discovery.";
LOG(INFO) << "started to discovery.";
return true;
}
@@ -306,7 +305,7 @@ bool WifiLanMedium::StartDiscovery(const std::string& service_type,
// DiscoveredServiceCallback passed in to StartDiscovery() for service_id.
bool WifiLanMedium::StopDiscovery(const std::string& service_type) {
if (!IsDiscovering()) {
NEARBY_LOGS(WARNING) << "no discovering service to stop.";
LOG(WARNING) << "no discovering service to stop.";
return false;
}
device_watcher_.Stop();
@@ -321,9 +320,8 @@ bool WifiLanMedium::StopDiscovery(const std::string& service_type) {
std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
const NsdServiceInfo& remote_service_info,
CancellationFlag* cancellation_flag) {
NEARBY_LOGS(ERROR)
<< "connect to service by NSD service info. service type is "
<< remote_service_info.GetServiceType();
LOG(ERROR) << "connect to service by NSD service info. service type is "
<< remote_service_info.GetServiceType();
return ConnectToService(remote_service_info.GetIPAddress(),
remote_service_info.GetPort(), cancellation_flag);
@@ -332,9 +330,9 @@ std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
const std::string& ip_address, int port,
CancellationFlag* cancellation_flag) {
NEARBY_LOGS(INFO) << "ConnectToService is called.";
LOG(INFO) << "ConnectToService is called.";
if (ip_address.empty() || ip_address.length() != 4 || port == 0) {
NEARBY_LOGS(ERROR) << "no valid service address and port to connect.";
LOG(ERROR) << "no valid service address and port to connect.";
return nullptr;
}
@@ -346,7 +344,7 @@ std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
address.S_un.S_un_b.s_b4 = ip_address[3];
char* ipv4_address = inet_ntoa(address);
if (ipv4_address == nullptr) {
NEARBY_LOGS(ERROR) << "Invalid IP address parameter.";
LOG(ERROR) << "Invalid IP address parameter.";
return nullptr;
}
@@ -361,16 +359,15 @@ std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
// setup cancel listener
if (cancellation_flag != nullptr) {
if (cancellation_flag->Cancelled()) {
NEARBY_LOGS(INFO) << "connect has been cancelled to service "
<< ipv4_address << ":" << port;
LOG(INFO) << "connect has been cancelled to service " << ipv4_address
<< ":" << port;
return nullptr;
}
connection_cancellation_listener =
std::make_unique<nearby::CancellationFlagListener>(
cancellation_flag, [socket]() {
NEARBY_LOGS(WARNING)
<< "connect is closed due to it is cancelled.";
LOG(WARNING) << "connect is closed due to it is cancelled.";
socket.Close();
});
}
@@ -380,7 +377,7 @@ std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
if (FeatureFlags::GetInstance().GetFlags().enable_connection_timeout) {
connection_timeout_ = scheduled_executor_.Schedule(
[socket]() {
NEARBY_LOGS(WARNING) << "connect is closed due to timeout.";
LOG(WARNING) << "connect is closed due to timeout.";
socket.Close();
},
kConnectServiceTimeout);
@@ -400,13 +397,12 @@ std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
winrt::to_string(socket.Information().LocalAddress().DisplayName());
std::string local_port = winrt::to_string(socket.Information().LocalPort());
NEARBY_LOGS(INFO) << "connected to remote service " << ipv4_address << ":"
<< port << " with local address " << local_address << ":"
<< local_port;
LOG(INFO) << "connected to remote service " << ipv4_address << ":" << port
<< " with local address " << local_address << ":" << local_port;
return wifi_lan_socket;
} catch (...) {
NEARBY_LOGS(ERROR) << "failed to connect remote service " << ipv4_address
<< ":" << port;
LOG(ERROR) << "failed to connect remote service " << ipv4_address << ":"
<< port;
}
if (connection_timeout_ != nullptr) {
@@ -422,8 +418,8 @@ std::unique_ptr<api::WifiLanServerSocket> WifiLanMedium::ListenForService(
// check current status
const auto& it = port_to_server_socket_map_.find(port);
if (it != port_to_server_socket_map_.end()) {
NEARBY_LOGS(WARNING) << "accepting connections already started on port "
<< it->second->GetPort();
LOG(WARNING) << "accepting connections already started on port "
<< it->second->GetPort();
return nullptr;
}
std::unique_ptr<WifiLanServerSocket> server_socket =
@@ -432,29 +428,29 @@ std::unique_ptr<api::WifiLanServerSocket> WifiLanMedium::ListenForService(
if (server_socket->listen()) {
int port = server_socket_ptr->GetPort();
NEARBY_LOGS(INFO) << "started to listen serive on IP:port "
<< ipaddr_4bytes_to_dotdecimal_string(
server_socket_ptr->GetIPAddress())
<< ":" << port;
LOG(INFO) << "started to listen serive on IP:port "
<< ipaddr_4bytes_to_dotdecimal_string(
server_socket_ptr->GetIPAddress())
<< ":" << port;
port_to_server_socket_map_.insert({port, server_socket_ptr});
server_socket->SetCloseNotifier([this, server_socket_ptr, port]() {
if (port_to_server_socket_map_.contains(port) &&
port_to_server_socket_map_[port] == server_socket_ptr) {
NEARBY_LOGS(INFO) << "Server socket was closed on port " << port;
LOG(INFO) << "Server socket was closed on port " << port;
port_to_server_socket_map_[port] = nullptr;
port_to_server_socket_map_.erase(port);
} else {
NEARBY_LOGS(INFO) << " The closing port doesn't match with the record "
"in port_to_server_socket_map_ map for port: "
<< port;
LOG(INFO) << " The closing port doesn't match with the record "
"in port_to_server_socket_map_ map for port: "
<< port;
}
});
return server_socket;
}
NEARBY_LOGS(ERROR) << "Failed to listen service on port " << port;
LOG(ERROR) << "Failed to listen service on port " << port;
return nullptr;
}
@@ -467,8 +463,7 @@ ExceptionOr<NsdServiceInfo> WifiLanMedium::GetNsdServiceInformation(
IInspectable inspectable =
properties.TryLookup(L"System.Devices.Dnssd.InstanceName");
if (inspectable == nullptr) {
NEARBY_LOGS(WARNING)
<< "no service name information in device information.";
LOG(WARNING) << "no service name information in device information.";
return Exception{Exception::kFailed};
}
nsd_service_info.SetServiceName(InspectableReader::ReadString(inspectable));
@@ -476,8 +471,7 @@ ExceptionOr<NsdServiceInfo> WifiLanMedium::GetNsdServiceInformation(
// Read service type information
inspectable = properties.TryLookup(L"System.Devices.Dnssd.ServiceName");
if (inspectable == nullptr) {
NEARBY_LOGS(WARNING)
<< "no service type information in device information.";
LOG(WARNING) << "no service type information in device information.";
return Exception{Exception::kFailed};
}
@@ -491,8 +485,7 @@ ExceptionOr<NsdServiceInfo> WifiLanMedium::GetNsdServiceInformation(
// Read text records
inspectable = properties.TryLookup(L"System.Devices.Dnssd.TextAttributes");
if (inspectable == nullptr) {
NEARBY_LOGS(WARNING)
<< "No text attributes information in device information.";
LOG(WARNING) << "No text attributes information in device information.";
return Exception{Exception::kFailed};
}
@@ -501,7 +494,7 @@ ExceptionOr<NsdServiceInfo> WifiLanMedium::GetNsdServiceInformation(
// text attribute in format key=value
int pos = text_attribute.find("=");
if (pos <= 0 || pos == text_attribute.size() - 1) {
NEARBY_LOGS(WARNING) << "found invalid text attribute " << text_attribute;
LOG(WARNING) << "found invalid text attribute " << text_attribute;
continue;
}
@@ -528,14 +521,14 @@ ExceptionOr<NsdServiceInfo> WifiLanMedium::GetNsdServiceInformation(
} else {
inspectable = properties.TryLookup(L"System.Devices.IPAddress");
if (inspectable == nullptr) {
NEARBY_LOGS(WARNING) << "No IP address property in device information.";
LOG(WARNING) << "No IP address property in device information.";
return Exception{Exception::kFailed};
}
ip_address_candidates = InspectableReader::ReadStringArray(inspectable);
}
if (ip_address_candidates.empty()) {
NEARBY_LOGS(WARNING) << "No IP address information in device information.";
LOG(WARNING) << "No IP address information in device information.";
return Exception{Exception::kFailed};
}
@@ -560,7 +553,7 @@ ExceptionOr<NsdServiceInfo> WifiLanMedium::GetNsdServiceInformation(
// Read IP port
inspectable = properties.TryLookup(L"System.Devices.Dnssd.PortNumber");
if (inspectable == nullptr) {
NEARBY_LOGS(WARNING) << "no IP port property in device information.";
LOG(WARNING) << "no IP port property in device information.";
return Exception{Exception::kFailed};
}
@@ -578,8 +571,8 @@ fire_and_forget WifiLanMedium::Watcher_DeviceAdded(
/*is_device_found*/ true);
if (!nsd_service_info_except.ok()) {
NEARBY_LOGS(WARNING) << "NSD information is incompleted or has error! "
"Don't add WIFI_LAN device.";
LOG(WARNING) << "NSD information is incompleted or has error! "
"Don't add WIFI_LAN device.";
return fire_and_forget{};
}
@@ -587,28 +580,27 @@ fire_and_forget WifiLanMedium::Watcher_DeviceAdded(
std::string endpoint =
nsd_service_info.GetTxtRecord(kDeviceEndpointInfo.data());
if (endpoint.empty()) {
NEARBY_LOGS(WARNING) << "No endpoint information! "
"Don't add WIFI_LAN device.";
LOG(WARNING) << "No endpoint information! "
"Don't add WIFI_LAN device.";
return fire_and_forget{};
}
// Don't discover itself
if (nsd_service_info.GetServiceName() == service_name_) {
NEARBY_LOGS(WARNING) << "Don't add WIFI_LAN device for itself";
LOG(WARNING) << "Don't add WIFI_LAN device for itself";
return fire_and_forget{};
}
NEARBY_LOGS(INFO) << "device added for service name "
<< nsd_service_info.GetServiceName() << ", address: "
<< ipaddr_4bytes_to_dotdecimal_string(
nsd_service_info.GetIPAddress())
<< ":" << nsd_service_info.GetPort();
LOG(INFO) << "device added for service name "
<< nsd_service_info.GetServiceName() << ", address: "
<< ipaddr_4bytes_to_dotdecimal_string(
nsd_service_info.GetIPAddress())
<< ":" << nsd_service_info.GetPort();
if (!IsConnectableIpAddress(
ipaddr_4bytes_to_dotdecimal_string(nsd_service_info.GetIPAddress()),
nsd_service_info.GetPort(), kConnectTimeout)) {
NEARBY_LOGS(WARNING)
<< "Don't add WIFI_LAN device due to it is not reachable.";
LOG(WARNING) << "Don't add WIFI_LAN device due to it is not reachable.";
return fire_and_forget{};
}
@@ -625,7 +617,7 @@ fire_and_forget WifiLanMedium::Watcher_DeviceUpdated(
/*is_device_found*/ true);
if (!nsd_service_info_except.ok()) {
NEARBY_LOGS(WARNING) << "NSD information is incompleted or has error!";
LOG(WARNING) << "NSD information is incompleted or has error!";
return fire_and_forget{};
}
@@ -633,7 +625,7 @@ fire_and_forget WifiLanMedium::Watcher_DeviceUpdated(
// Don't discover itself
if (nsd_service_info.GetServiceName() == service_name_) {
NEARBY_LOGS(WARNING) << "Don't update WIFI_LAN device for itself.";
LOG(WARNING) << "Don't update WIFI_LAN device for itself.";
return fire_and_forget{};
}
@@ -641,7 +633,7 @@ fire_and_forget WifiLanMedium::Watcher_DeviceUpdated(
std::optional<NsdServiceInfo> last_nsd_service_info =
GetDiscoveredService(winrt::to_string(deviceInfoUpdate.Id()));
if (!last_nsd_service_info.has_value()) {
NEARBY_LOGS(WARNING)
LOG(WARNING)
<< "Don't update WIFI_LAN device due to it is not in device list.";
return fire_and_forget{};
}
@@ -653,11 +645,11 @@ fire_and_forget WifiLanMedium::Watcher_DeviceUpdated(
(last_nsd_service_info->GetIPAddress() ==
nsd_service_info.GetIPAddress()) &&
(last_nsd_service_info->GetPort() == nsd_service_info.GetPort())) {
NEARBY_LOGS(INFO) << "Don't update WIFI_LAN device due to no change.";
LOG(INFO) << "Don't update WIFI_LAN device due to no change.";
return fire_and_forget{};
}
NEARBY_LOGS(INFO)
LOG(INFO)
<< "Device is changed from (service name:"
<< last_nsd_service_info->GetServiceName() << ", endpoint info:"
<< last_nsd_service_info->GetTxtRecord(std::string(kDeviceEndpointInfo))
@@ -689,14 +681,13 @@ fire_and_forget WifiLanMedium::Watcher_DeviceRemoved(
/*is_device_found*/ false);
if (!nsd_service_info_except.ok()) {
NEARBY_LOGS(WARNING)
<< "NSD information is incompleted or has error! Ignore";
LOG(WARNING) << "NSD information is incompleted or has error! Ignore";
return fire_and_forget{};
}
NsdServiceInfo nsd_service_info = nsd_service_info_except.GetResult();
NEARBY_LOGS(INFO) << "device removed for service name "
<< nsd_service_info.GetServiceName();
LOG(INFO) << "device removed for service name "
<< nsd_service_info.GetServiceName();
std::string endpoint =
nsd_service_info.GetTxtRecord(kDeviceEndpointInfo.data());
@@ -19,6 +19,10 @@
#include <string>
#include <vector>
#include "absl/functional/any_invocable.h"
#include "absl/synchronization/mutex.h"
#include "internal/platform/exception.h"
#include "internal/platform/implementation/wifi_lan.h"
#include "internal/platform/implementation/windows/generated/winrt/Windows.Networking.Sockets.h"
#include "internal/platform/implementation/windows/utils.h"
#include "internal/platform/implementation/windows/wifi_lan.h"
@@ -39,13 +43,12 @@ WifiLanServerSocket::~WifiLanServerSocket() { Close(); }
// Returns the first IP address.
std::string WifiLanServerSocket::GetIPAddress() const {
if (stream_socket_listener_ == nullptr) {
NEARBY_LOGS(ERROR) << "Failed to get IP address due to no server socket.";
LOG(ERROR) << "Failed to get IP address due to no server socket.";
return "";
}
if (ip_addresses_.empty()) {
NEARBY_LOGS(ERROR)
<< "Failed to get IP address due to no avaible IP addresses.";
LOG(ERROR) << "Failed to get IP address due to no avaible IP addresses.";
return "";
}
@@ -69,7 +72,7 @@ int WifiLanServerSocket::GetPort() const {
// Once error is reported, it is permanent, and ServerSocket has to be closed.
std::unique_ptr<api::WifiLanSocket> WifiLanServerSocket::Accept() {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__ << ": Accept is called.";
LOG(INFO) << __func__ << ": Accept is called.";
while (!closed_ && pending_sockets_.empty()) {
cond_.Wait(&mutex_);
@@ -79,7 +82,7 @@ std::unique_ptr<api::WifiLanSocket> WifiLanServerSocket::Accept() {
StreamSocket wifi_lan_socket = pending_sockets_.front();
pending_sockets_.pop_front();
NEARBY_LOGS(INFO) << __func__ << ": Accepted a remote connection.";
LOG(INFO) << __func__ << ": Accepted a remote connection.";
return std::make_unique<WifiLanSocket>(wifi_lan_socket);
}
@@ -92,7 +95,7 @@ void WifiLanServerSocket::SetCloseNotifier(
Exception WifiLanServerSocket::Close() {
try {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__ << ": Close is called.";
LOG(INFO) << __func__ << ": Close is called.";
if (closed_) {
return {Exception::kSuccess};
@@ -116,23 +119,23 @@ Exception WifiLanServerSocket::Close() {
close_notifier_();
}
NEARBY_LOGS(INFO) << __func__ << ": Close completed succesfully.";
LOG(INFO) << __func__ << ": Close completed succesfully.";
return {Exception::kSuccess};
} catch (std::exception exception) {
closed_ = true;
cond_.SignalAll();
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
closed_ = true;
cond_.SignalAll();
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
closed_ = true;
cond_.SignalAll();
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -142,8 +145,8 @@ bool WifiLanServerSocket::listen() {
ip_addresses_ = Get4BytesIpv4Addresses();
if (ip_addresses_.empty()) {
NEARBY_LOGS(WARNING) << "failed to start accepting connection without IP "
"addresses configured on computer.";
LOG(WARNING) << "failed to start accepting connection without IP "
"addresses configured on computer.";
return false;
}
@@ -169,17 +172,16 @@ bool WifiLanServerSocket::listen() {
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR)
<< __func__
<< ": Cannot accept connection on preferred port. Exception: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Cannot accept connection on preferred port. Exception: "
<< exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR)
LOG(ERROR)
<< __func__
<< ": Cannot accept connection on preferred port. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
}
try {
@@ -190,15 +192,14 @@ bool WifiLanServerSocket::listen() {
std::stoi(stream_socket_listener_.Information().LocalPort().c_str());
return true;
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Cannot bind to any port. Exception: "
<< exception.what();
LOG(ERROR) << __func__
<< ": Cannot bind to any port. Exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__
<< ": Cannot bind to any port. WinRT exception: "
<< error.code() << ": "
<< winrt::to_string(error.message());
LOG(ERROR) << __func__
<< ": Cannot bind to any port. WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
}
return false;
@@ -208,7 +209,7 @@ fire_and_forget WifiLanServerSocket::Listener_ConnectionReceived(
StreamSocketListener listener,
StreamSocketListenerConnectionReceivedEventArgs const& args) {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << __func__ << ": Received connection.";
LOG(INFO) << __func__ << ": Received connection.";
if (closed_) {
return fire_and_forget{};
@@ -16,8 +16,12 @@
#include <cstring>
#include <exception>
#include "internal/platform/byte_array.h"
#include "internal/platform/exception.h"
#include "internal/platform/implementation/windows/wifi_lan.h"
#include "internal/platform/input_stream.h"
#include "internal/platform/logging.h"
#include "internal/platform/output_stream.h"
namespace nearby {
namespace windows {
@@ -34,12 +38,12 @@ WifiLanSocket::~WifiLanSocket() {
Close();
}
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
}
}
@@ -54,14 +58,14 @@ Exception WifiLanSocket::Close() {
}
return {Exception::kSuccess};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -80,22 +84,22 @@ ExceptionOr<ByteArray> WifiLanSocket::SocketInputStream::Read(
input_stream_.ReadAsync(buffer, size, InputStreamOptions::None).get();
if (ibuffer.Length() != size) {
NEARBY_LOGS(WARNING) << "Only read partial of data: [" << ibuffer.Length()
<< "/" << size << "].";
LOG(WARNING) << "Only read partial of data: [" << ibuffer.Length() << "/"
<< size << "].";
}
ByteArray data((char*)ibuffer.data(), ibuffer.Length());
return ExceptionOr(data);
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -108,14 +112,14 @@ ExceptionOr<size_t> WifiLanSocket::SocketInputStream::Skip(size_t offset) {
input_stream_.ReadAsync(buffer, offset, InputStreamOptions::None).get();
return ExceptionOr((size_t)ibuffer.Length());
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -125,14 +129,14 @@ Exception WifiLanSocket::SocketInputStream::Close() {
input_stream_.Close();
return {Exception::kSuccess};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -150,20 +154,20 @@ Exception WifiLanSocket::SocketOutputStream::Write(const ByteArray& data) {
buffer.Length(data.size());
uint32_t wrote_bytes = output_stream_.WriteAsync(buffer).get();
if (wrote_bytes != data.size()) {
NEARBY_LOGS(WARNING) << "Only wrote partial of data:[" << wrote_bytes
<< "/" << data.size() << "].";
LOG(WARNING) << "Only wrote partial of data:[" << wrote_bytes << "/"
<< data.size() << "].";
}
return {Exception::kSuccess};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -173,14 +177,14 @@ Exception WifiLanSocket::SocketOutputStream::Flush() {
output_stream_.FlushAsync().get();
return {Exception::kSuccess};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -190,14 +194,14 @@ Exception WifiLanSocket::SocketOutputStream::Close() {
output_stream_.Close();
return {Exception::kSuccess};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {Exception::kIo};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {Exception::kIo};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {Exception::kIo};
}
}
@@ -12,13 +12,17 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include <cstring>
#include <exception>
#include <string>
// #include <cstddef>
#include "absl/strings/str_format.h"
#include "internal/platform/implementation/wifi.h"
#include "internal/platform/implementation/windows/utils.h"
#include "internal/platform/implementation/windows/wifi.h"
#include "internal/platform/logging.h"
#include "internal/platform/wifi_utils.h"
namespace nearby {
namespace windows {
@@ -39,16 +43,16 @@ PWLAN_INTERFACE_INFO_LIST EnumInterface(PHANDLE client_handle) {
/* variables used for WlanEnumInterfaces */
PWLAN_INTERFACE_INFO_LIST p_intf_list = nullptr;
result =
WlanOpenHandle(client_version, NULL, &negotiated_version, client_handle);
result = WlanOpenHandle(client_version, nullptr, &negotiated_version,
client_handle);
if (result != ERROR_SUCCESS) {
NEARBY_LOGS(INFO) << "WlanOpenHandle failed with error: " << result;
LOG(INFO) << "WlanOpenHandle failed with error: " << result;
return p_intf_list;
}
result = WlanEnumInterfaces(*client_handle, NULL, &p_intf_list);
result = WlanEnumInterfaces(*client_handle, nullptr, &p_intf_list);
if (result != ERROR_SUCCESS) {
NEARBY_LOGS(INFO) << "WlanEnumInterfaces failed with error: " << result;
LOG(INFO) << "WlanEnumInterfaces failed with error: " << result;
}
return p_intf_list;
}
@@ -69,12 +73,12 @@ void WifiMedium::InitCapability() {
p_intf_list = EnumInterface(&client_handle);
if (!client_handle) {
NEARBY_LOGS(INFO)
LOG(INFO)
<< "Client Handle is null, wifi maybe not supported on this device.";
return;
}
if (!p_intf_list) {
WlanCloseHandle(client_handle, NULL);
WlanCloseHandle(client_handle, nullptr);
return;
}
wifi_interface_valid_ = true;
@@ -82,11 +86,12 @@ void WifiMedium::InitCapability() {
for (int i = 0; i < (int)p_intf_list->dwNumberOfItems; i++) {
p_intf_info = (WLAN_INTERFACE_INFO*)&p_intf_list->InterfaceInfo[i];
if (WlanGetInterfaceCapability(client_handle, &p_intf_info->InterfaceGuid,
NULL, &p_intf_capability) != ERROR_SUCCESS) {
NEARBY_LOGS(INFO) << "Get Capability failed";
nullptr,
&p_intf_capability) != ERROR_SUCCESS) {
LOG(INFO) << "Get Capability failed";
WlanFreeMemory(p_intf_list);
p_intf_list = nullptr;
WlanCloseHandle(client_handle, NULL);
WlanCloseHandle(client_handle, nullptr);
return;
}
@@ -100,7 +105,7 @@ void WifiMedium::InitCapability() {
p_intf_capability = nullptr;
WlanFreeMemory(p_intf_list);
p_intf_list = nullptr;
WlanCloseHandle(client_handle, NULL);
WlanCloseHandle(client_handle, nullptr);
}
// TODO(b/259414512): the return type should be optional.
@@ -126,13 +131,13 @@ api::WifiInformation& WifiMedium::GetInformation() {
p_intf_list = EnumInterface(&client_handle);
if (!client_handle) {
NEARBY_LOGS(INFO) << "Client Handle is NULL";
LOG(INFO) << "Client Handle is nullptr";
FillupEthernetParams();
return wifi_information_;
}
if (!p_intf_list) {
NEARBY_LOGS(INFO) << "WlanEnumInterfaces failed with error: ";
WlanCloseHandle(client_handle, NULL);
LOG(INFO) << "WlanEnumInterfaces failed with error: ";
WlanCloseHandle(client_handle, nullptr);
FillupEthernetParams();
return wifi_information_;
}
@@ -140,16 +145,16 @@ api::WifiInformation& WifiMedium::GetInformation() {
for (int i = 0; i < (int)p_intf_list->dwNumberOfItems; i++) {
p_intf_info = (WLAN_INTERFACE_INFO*)&p_intf_list->InterfaceInfo[i];
if (p_intf_info->isState == wlan_interface_state_connected) {
NEARBY_LOGS(INFO) << "Found connected WiFi interface No: " << i;
LOG(INFO) << "Found connected WiFi interface No: " << i;
wifi_information_.is_connected = true;
DWORD channel_size;
result = WlanQueryInterface(client_handle, &p_intf_info->InterfaceGuid,
wlan_intf_opcode_channel_number, NULL,
wlan_intf_opcode_channel_number, nullptr,
&channel_size, (PVOID*)&channel,
&op_code_value_type);
if (result != ERROR_SUCCESS) {
NEARBY_LOGS(INFO) << "WlanQueryInterface channel error = " << result;
LOG(INFO) << "WlanQueryInterface channel error = " << result;
WlanFreeMemory(p_intf_list);
p_intf_list = nullptr;
WlanCloseHandle(client_handle, nullptr);
@@ -158,20 +163,20 @@ api::WifiInformation& WifiMedium::GetInformation() {
}
wifi_information_.ap_frequency = WifiUtils::ConvertChannelToFrequencyMhz(
*channel, api::WifiBandType::kUnknown);
NEARBY_LOGS(INFO) << "Channel: " << *channel
<< "; ap_frequency: " << wifi_information_.ap_frequency;
LOG(INFO) << "Channel: " << (channel == nullptr ? 0 : *channel)
<< "; ap_frequency: " << wifi_information_.ap_frequency;
WlanFreeMemory(channel);
channel = nullptr;
result = WlanQueryInterface(client_handle, &p_intf_info->InterfaceGuid,
wlan_intf_opcode_current_connection, NULL,
wlan_intf_opcode_current_connection, nullptr,
&connect_info_size, (PVOID*)&p_connect_info,
&op_code_value_type);
if (result != ERROR_SUCCESS) {
NEARBY_LOGS(INFO) << "WlanQueryInterface current AP error = " << result;
LOG(INFO) << "WlanQueryInterface current AP error = " << result;
WlanFreeMemory(p_intf_list);
p_intf_list = nullptr;
WlanCloseHandle(client_handle, NULL);
WlanCloseHandle(client_handle, nullptr);
FillupEthernetParams();
return wifi_information_;
}
@@ -183,8 +188,8 @@ api::WifiInformation& WifiMedium::GetInformation() {
reinterpret_cast<const char*>(
p_connect_info->wlanAssociationAttributes.dot11Ssid.ucSSID),
wifi_information_.ssid.size());
NEARBY_LOGS(INFO) << "wifi ssid is: " << wifi_information_.ssid
<< "; length is:" << wifi_information_.ssid.length();
LOG(INFO) << "wifi ssid is: " << wifi_information_.ssid
<< "; length is:" << wifi_information_.ssid.length();
char str_tmp[kMacAddrLen];
strncpy(str_tmp,
@@ -194,7 +199,7 @@ api::WifiInformation& WifiMedium::GetInformation() {
wifi_information_.bssid = absl::StrFormat(
"%02llx:%02llx:%02llx:%02llx:%02llx:%02llx", str_tmp[0], str_tmp[1],
str_tmp[2], str_tmp[3], str_tmp[4], str_tmp[5]);
NEARBY_LOGS(INFO) << "wifi bssid is: " << wifi_information_.bssid;
LOG(INFO) << "wifi bssid is: " << wifi_information_.bssid;
}
}
@@ -202,7 +207,7 @@ api::WifiInformation& WifiMedium::GetInformation() {
p_connect_info = nullptr;
WlanFreeMemory(p_intf_list);
p_intf_list = nullptr;
WlanCloseHandle(client_handle, NULL);
WlanCloseHandle(client_handle, nullptr);
if (wifi_information_.is_connected) {
wifi_information_.ip_address_dot_decimal = InternalGetWifiIpAddress();
@@ -228,7 +233,7 @@ std::string WifiMedium::InternalGetWifiIpAddress() {
host_name.IPInformation().NetworkAdapter() != nullptr &&
host_name.Type() == HostNameType::Ipv4) {
std::string ipv4_s = winrt::to_string(host_name.ToString());
NEARBY_LOGS(INFO) << "Found IP: " << ipv4_s;
LOG(INFO) << "Found IP: " << ipv4_s;
auto profile = host_name.IPInformation()
.NetworkAdapter()
@@ -239,7 +244,7 @@ std::string WifiMedium::InternalGetWifiIpAddress() {
if (profile_details != nullptr &&
wifi_information_.ssid ==
winrt::to_string(profile_details.GetConnectedSsid())) {
NEARBY_LOGS(INFO)
LOG(INFO)
<< "SSID of this IP matches with this WiFi interface's SSID:"
<< wifi_information_.ssid << ", return this IP: " << ipv4_s;
return ipv4_s;
@@ -249,14 +254,14 @@ std::string WifiMedium::InternalGetWifiIpAddress() {
}
return {};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {};
}
}
@@ -271,21 +276,21 @@ std::string WifiMedium::InternalGetEthernetIpAddress() {
std::string ipv4_s = winrt::to_string(host_name.ToString());
if (host_name.IPInformation().NetworkAdapter().IanaInterfaceType() ==
Constants::kInterfaceTypeEthernet) {
NEARBY_LOGS(INFO) << "Found IP: " << ipv4_s;
LOG(INFO) << "Found IP: " << ipv4_s;
return ipv4_s;
}
}
}
return {};
} catch (std::exception exception) {
NEARBY_LOGS(ERROR) << __func__ << ": Exception: " << exception.what();
LOG(ERROR) << __func__ << ": Exception: " << exception.what();
return {};
} catch (const winrt::hresult_error& error) {
NEARBY_LOGS(ERROR) << __func__ << ": WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
LOG(ERROR) << __func__ << ": WinRT exception: " << error.code() << ": "
<< winrt::to_string(error.message());
return {};
} catch (...) {
NEARBY_LOGS(ERROR) << __func__ << ": Unknown exeption.";
LOG(ERROR) << __func__ << ": Unknown exeption.";
return {};
}
}
@@ -293,7 +298,7 @@ std::string WifiMedium::InternalGetEthernetIpAddress() {
void WifiMedium::FillupEthernetParams() {
wifi_information_.ip_address_dot_decimal = InternalGetEthernetIpAddress();
if (wifi_information_.ip_address_dot_decimal.empty()) {
NEARBY_LOGS(INFO) << "No Etherent IP Addr found.";
LOG(INFO) << "No Etherent IP Addr found.";
return;
}
wifi_information_.ip_address_4_bytes = ipaddr_dotdecimal_to_4bytes_string(
@@ -12,11 +12,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal/platform/implementation/windows/wifi.h"
#include <iostream>
#include "gtest/gtest.h"
#include "internal/platform/implementation/windows/wifi.h"
#include "internal/platform/logging.h"
namespace nearby {
@@ -25,27 +24,25 @@ namespace {
TEST(WifiMedium, DISABLED_GetCapabilityAndInformation) {
int run_test;
NEARBY_LOGS(INFO)
<< "Run GetCapabilityAndInformation test case? input 0 or 1:";
LOG(INFO) << "Run GetCapabilityAndInformation test case? input 0 or 1:";
std::cin >> run_test;
if (run_test) {
WifiMedium wifi_medium;
auto& capability = wifi_medium.GetCapability();
NEARBY_LOGS(INFO) << "Support 5G? " << capability.supports_5_ghz;
LOG(INFO) << "Support 5G? " << capability.supports_5_ghz;
auto& information = wifi_medium.GetInformation();
NEARBY_LOGS(INFO) << "Is Connected? " << information.is_connected
<< "; ssid = " << information.ssid
<< "; bssid = " << information.bssid
<< "; ap_frequency: " << information.ap_frequency
<< "; ip_address_dot_decimal: "
<< information.ip_address_dot_decimal
<< "; ip_address_4_bytes: "
<< information.ip_address_4_bytes;
LOG(INFO) << "Is Connected? " << information.is_connected
<< "; ssid = " << information.ssid
<< "; bssid = " << information.bssid
<< "; ap_frequency: " << information.ap_frequency
<< "; ip_address_dot_decimal: "
<< information.ip_address_dot_decimal
<< "; ip_address_4_bytes: " << information.ip_address_4_bytes;
} else {
NEARBY_LOGS(INFO) << "Skip the test";
LOG(INFO) << "Skip the test";
}
}