Cleanup enable_wifi_hotspot_native flag

PiperOrigin-RevId: 747546014
This commit is contained in:
Guogang Li
2025-04-14 13:30:38 -07:00
committed by Copybara-Service
parent 380154d0ba
commit 681284c576
2 changed files with 12 additions and 351 deletions
@@ -304,11 +304,11 @@ class WifiHotspotMedium : public api::WifiHotspotMedium {
int port) override;
// Advertiser start WiFi Hotspot with specific Credentials.
bool StartWifiHotspot(HotspotCredentials* hotspot_credentials_) override;
bool StartWifiHotspot(HotspotCredentials* hotspot_credentials) override;
// Advertiser stop the current WiFi Hotspot
bool StopWifiHotspot() override;
// Discoverer connects to the Hotspot
bool ConnectWifiHotspot(HotspotCredentials* hotspot_credentials_) override;
bool ConnectWifiHotspot(HotspotCredentials* hotspot_credentials) override;
// Discoverer disconnects from the Hotspot
bool DisconnectWifiHotspot() override;
@@ -325,12 +325,6 @@ class WifiHotspotMedium : public api::WifiHotspotMedium {
kMediumStatusConnected = (1 << 2),
};
// Implemented the disconnection to WiFi hotspot, and used to avoid deadlock.
bool InternalDisconnectWifiHotspot();
// Restore the WiFi connection after disconnect from the Hotspot
void RestoreWifiConnection();
// Delete the network profile of the WiFi hotspot
bool DeleteNetworkProfile(winrt::hstring ssid);
// Store the Hotspot SSID to local storage
void StoreHotspotSsid(std::string ssid);
// Get the Hotspot SSID from local storage
@@ -344,11 +338,6 @@ class WifiHotspotMedium : public api::WifiHotspotMedium {
// Discoverer is connected with the Hotspot
bool IsConnected() { return (medium_status_ & kMediumStatusConnected) != 0; }
bool ConnectWifiHotspotWithWinRt(HotspotCredentials* hotspot_credentials);
bool ConnectWifiHotspotWithNative(HotspotCredentials* hotspot_credentials);
bool DisconnectWifiHotspotWithWinRt();
bool DisconnectWifiHotspotWithNative();
WiFiDirectAdvertisementPublisher publisher_{nullptr};
WiFiDirectConnectionListener listener_{nullptr};
@@ -365,10 +354,6 @@ class WifiHotspotMedium : public api::WifiHotspotMedium {
WiFiDirectConnectionRequestedEventArgs const& event);
winrt::event_token connection_requested_token_;
WiFiAdapter wifi_adapter_{nullptr};
WiFiAvailableNetwork wifi_original_network_{nullptr};
winrt::hstring wifi_connected_hotspot_ssid_ = winrt::hstring(L"");
// Gets error message from exception pointer
std::string GetErrorMessage(std::exception_ptr eptr);
@@ -49,7 +49,7 @@ WifiHotspotMedium::WifiHotspotMedium() {
std::string ssid = GetStoredHotspotSsid();
if (!ssid.empty()) {
LOG(INFO) << "Get stored Hotspot SSID: " << ssid << " from previous run";
DeleteNetworkProfile(winrt::to_hstring(ssid));
wifi_hotspot_native_.DeleteWifiProfile(winrt::to_hstring(ssid).c_str());
StoreHotspotSsid({});
}
}
@@ -271,7 +271,7 @@ WifiHotspotMedium::ListenForService(int port) {
}
bool WifiHotspotMedium::StartWifiHotspot(
HotspotCredentials* hotspot_credentials_) {
HotspotCredentials* hotspot_credentials) {
absl::MutexLock lock(&mutex_);
LOG(INFO) << __func__ << ": Start to create WiFi Hotspot.";
@@ -295,13 +295,13 @@ bool WifiHotspotMedium::StartWifiHotspot(
Prng prng;
publisher_.Advertisement().LegacySettings().IsEnabled(true);
std::string password = absl::StrFormat("%08x", prng.NextUint32());
hotspot_credentials_->SetPassword(password);
hotspot_credentials->SetPassword(password);
PasswordCredential creds;
creds.Password(winrt::to_hstring(password));
publisher_.Advertisement().LegacySettings().Passphrase(creds);
std::string ssid = "DIRECT-" + std::to_string(prng.NextUint32());
hotspot_credentials_->SetSSID(ssid);
hotspot_credentials->SetSSID(ssid);
publisher_.Advertisement().LegacySettings().Ssid(winrt::to_hstring(ssid));
publisher_.Start();
@@ -318,13 +318,13 @@ bool WifiHotspotMedium::StartWifiHotspot(
LOG(INFO) << "Intel PIE enabled, Hotspot is running on channel: "
<< GO_channel;
intel_wifi.Stop();
hotspot_credentials_->SetFrequency(
hotspot_credentials->SetFrequency(
WifiUtils::ConvertChannelToFrequencyMhz(GO_channel,
WifiBandType::kUnknown));
}
} else {
LOG(INFO) << "Intel PIE disabled, Can't extract Hotspot channel info!";
hotspot_credentials_->SetFrequency(-1);
hotspot_credentials->SetFrequency(-1);
}
return true;
}
@@ -460,197 +460,16 @@ fire_and_forget WifiHotspotMedium::OnConnectionRequested(
}
bool WifiHotspotMedium::ConnectWifiHotspot(
HotspotCredentials* hotspot_credentials_) {
if (NearbyFlags::GetInstance().GetBoolFlag(
platform::config_package_nearby::nearby_platform_feature::
kEnableWifiHotspotNative)) {
return ConnectWifiHotspotWithNative(hotspot_credentials_);
} else {
return ConnectWifiHotspotWithWinRt(hotspot_credentials_);
}
}
bool WifiHotspotMedium::ConnectWifiHotspotWithWinRt(
HotspotCredentials* hotspot_credentials) {
absl::MutexLock lock(&mutex_);
try {
if (!wifi_connected_hotspot_ssid_.empty()) {
std::string ssid = GetStoredHotspotSsid();
if (!ssid.empty()) {
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"");
StoreHotspotSsid({});
}
if (IsConnected()) {
LOG(WARNING) << "Already connected to Hotspot, disconnect first.";
InternalDisconnectWifiHotspot();
}
auto access = WiFiAdapter::RequestAccessAsync().get();
if (access != WiFiAccessStatus::Allowed) {
LOG(WARNING) << "Access Denied with reason: " << static_cast<int>(access);
return false;
}
auto adapters = WiFiAdapter::FindAllAdaptersAsync().get();
if (adapters.Size() < 1) {
LOG(WARNING) << "No WiFi Adapter found.";
return false;
}
wifi_adapter_ = adapters.GetAt(0);
// Retrieve the current connected network's profile
ConnectionProfile profile =
wifi_adapter_.NetworkAdapter().GetConnectedProfileAsync().get();
std::string ssid;
if (profile != nullptr && profile.IsWlanConnectionProfile()) {
ssid = winrt::to_string(
profile.WlanConnectionProfileDetails().GetConnectedSsid());
}
// SoftAP is an abbreviation for "software enabled access point".
WiFiAvailableNetwork nearby_softap{nullptr};
bool intel_wifi_started = false;
if (NearbyFlags::GetInstance().GetBoolFlag(
platform::config_package_nearby::nearby_platform_feature::
kEnableIntelPieSdk)) {
auto channel = WifiUtils::ConvertFrequencyMhzToChannel(
hotspot_credentials->GetFrequency());
WifiIntel& intel_wifi{WifiIntel::GetInstance()};
intel_wifi_started = intel_wifi.Start();
if (intel_wifi_started) {
intel_wifi.SetScanFilter(channel);
}
}
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();
wifi_original_network_ = nullptr;
int64_t wifi_hotspot_max_scans = NearbyFlags::GetInstance().GetInt64Flag(
platform::config_package_nearby::nearby_platform_feature::
kWifiHotspotScanMaxRetries);
int i;
for (i = 0; i < wifi_hotspot_max_scans; i++) {
for (const auto& network :
wifi_adapter_.NetworkReport().AvailableNetworks()) {
if (!wifi_original_network_ && !ssid.empty() &&
(winrt::to_string(network.Ssid()) == ssid)) {
wifi_original_network_ = network;
LOG(INFO) << "Save the current connected network: " << ssid;
} else if (!nearby_softap && winrt::to_string(network.Ssid()) ==
hotspot_credentials->GetSSID()) {
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) break;
LOG(INFO) << "Scan ... ";
wifi_adapter_.ScanAsync().get();
}
LOG(INFO) << "Finish scanning "
<< (nearby_softap ? "successfully" : "failed") << " with "
<< i + 1 << " times trying.";
if (intel_wifi_started) {
WifiIntel& intel_wifi{WifiIntel::GetInstance()};
intel_wifi.ResetScanFilter();
intel_wifi.Stop();
}
if (!nearby_softap) {
LOG(INFO) << "Hotspot is not found";
return false;
}
PasswordCredential creds;
creds.Password(winrt::to_hstring(hotspot_credentials->GetPassword()));
auto connect_result =
wifi_adapter_
.ConnectAsync(nearby_softap, WiFiReconnectionKind::Manual, creds)
.get();
if (connect_result == nullptr ||
connect_result.ConnectionStatus() != WiFiConnectionStatus::Success) {
LOG(INFO) << "Connecting failed with reason: "
<< static_cast<int>(connect_result.ConnectionStatus());
RestoreWifiConnection();
return false;
}
// Make sure IP address is ready.
std::string ip_address;
int64_t ip_address_max_retries = NearbyFlags::GetInstance().GetInt64Flag(
platform::config_package_nearby::nearby_platform_feature::
kWifiHotspotCheckIpMaxRetries);
int64_t ip_address_retry_interval_millis =
NearbyFlags::GetInstance().GetInt64Flag(
platform::config_package_nearby::nearby_platform_feature::
kWifiHotspotCheckIpIntervalMillis);
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++) {
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);
continue;
}
ip_address = ip_addresses[0];
break;
}
if (ip_address.empty()) {
LOG(INFO) << "Failed to get IP address from hotspot.";
RestoreWifiConnection();
DeleteNetworkProfile(nearby_softap.Ssid());
return false;
}
LOG(INFO) << "Got IP address " << ip_address << " from hotspot.";
std::string last_ssid = hotspot_credentials->GetSSID();
wifi_connected_hotspot_ssid_ = nearby_softap.Ssid();
StoreHotspotSsid(winrt::to_string(wifi_connected_hotspot_ssid_));
medium_status_ |= kMediumStatusConnected;
LOG(INFO) << "Connected to hotspot: " << last_ssid;
return true;
} catch (std::exception exception) {
LOG(ERROR) << __func__
<< ": Cannot connet to Hotspot. Exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
LOG(ERROR) << __func__ << ": Cannot connet to Hotspot. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
} catch (...) {
LOG(ERROR) << __func__ << ": Unknown exeption.";
}
return false;
}
bool WifiHotspotMedium::ConnectWifiHotspotWithNative(
HotspotCredentials* hotspot_credentials) {
absl::MutexLock lock(&mutex_);
try {
if (!wifi_connected_hotspot_ssid_.empty()) {
LOG(INFO) << "Before connecting to Hotspot, Delete the previous "
"Hotspot profile with SSID: "
<< winrt::to_string(wifi_connected_hotspot_ssid_);
wifi_hotspot_native_.DeleteWifiProfile(
wifi_connected_hotspot_ssid_.c_str());
wifi_connected_hotspot_ssid_ = winrt::hstring(L"");
<< ssid;
wifi_hotspot_native_.DeleteWifiProfile(winrt::to_hstring(ssid).c_str());
StoreHotspotSsid({});
}
if (IsConnected()) {
@@ -776,75 +595,7 @@ bool WifiHotspotMedium::ConnectWifiHotspotWithNative(
return false;
}
void WifiHotspotMedium::RestoreWifiConnection() {
if (!wifi_original_network_ && wifi_adapter_) {
wifi_adapter_.Disconnect();
return;
}
if (wifi_adapter_) {
ConnectionProfile profile =
wifi_adapter_.NetworkAdapter().GetConnectedProfileAsync().get();
std::string ssid;
if (profile != nullptr && profile.IsWlanConnectionProfile()) {
ssid = winrt::to_string(
profile.WlanConnectionProfileDetails().GetConnectedSsid());
if (!ssid.empty() &&
(winrt::to_string(wifi_original_network_.Ssid()) == ssid)) {
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();
LOG(INFO) << "Disconnected to current network.";
auto connect_result = wifi_adapter_
.ConnectAsync(wifi_original_network_,
WiFiReconnectionKind::Automatic)
.get();
if (connect_result == nullptr ||
connect_result.ConnectionStatus() != WiFiConnectionStatus::Success) {
LOG(INFO) << "Connecting to previous network failed with reason: "
<< static_cast<int>(connect_result.ConnectionStatus());
} else {
LOG(INFO) << "Restored the previous WIFI connection: "
<< winrt::to_string(wifi_original_network_.Ssid());
}
wifi_original_network_ = nullptr;
}
}
bool WifiHotspotMedium::DisconnectWifiHotspot() {
if (NearbyFlags::GetInstance().GetBoolFlag(
platform::config_package_nearby::nearby_platform_feature::
kEnableWifiHotspotNative)) {
return DisconnectWifiHotspotWithNative();
} else {
return DisconnectWifiHotspotWithWinRt();
}
}
bool WifiHotspotMedium::DisconnectWifiHotspotWithWinRt() {
absl::MutexLock lock(&mutex_);
try {
return InternalDisconnectWifiHotspot();
} catch (std::exception exception) {
LOG(ERROR) << __func__
<< ": Stop Hotspot failed. Exception: " << exception.what();
} catch (const winrt::hresult_error& error) {
LOG(ERROR) << __func__
<< ": Stop Hotspot failed. WinRT exception: " << error.code()
<< ": " << winrt::to_string(error.message());
} catch (...) {
LOG(ERROR) << __func__ << ": Unknown exeption.";
}
return false;
}
bool WifiHotspotMedium::DisconnectWifiHotspotWithNative() {
absl::MutexLock lock(&mutex_);
if (!IsConnected()) {
@@ -863,7 +614,6 @@ bool WifiHotspotMedium::DisconnectWifiHotspotWithNative() {
}
}
wifi_connected_hotspot_ssid_ = winrt::hstring(L"");
StoreHotspotSsid({});
medium_status_ &= (~kMediumStatusConnected);
@@ -871,80 +621,6 @@ bool WifiHotspotMedium::DisconnectWifiHotspotWithNative() {
return true;
}
bool WifiHotspotMedium::InternalDisconnectWifiHotspot() {
if (!IsConnected()) {
LOG(WARNING) << "Cannot disconnect SoftAP because it is not connected.";
return true;
}
if (wifi_adapter_) {
// Disconnect to the WiFi connection through the WiFi adapter.
RestoreWifiConnection();
wifi_adapter_ = nullptr;
if (!wifi_connected_hotspot_ssid_.empty()) {
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"");
StoreHotspotSsid({});
}
}
medium_status_ &= (~kMediumStatusConnected);
return true;
}
bool WifiHotspotMedium::DeleteNetworkProfile(winrt::hstring ssid) {
bool result = false;
ConnectionProfile profile{nullptr};
auto connections = NetworkInformation::GetConnectionProfiles();
auto ssid_string = winrt::to_string(ssid);
if (ssid_string.empty()) {
LOG(INFO) << "SSID is empty. No need to delete the network profile";
return true;
}
LOG(INFO) << "Search profile with SSID: " << ssid_string;
for (const auto& connection_profile : connections) {
if (connection_profile.ProfileName() == ssid) {
LOG(INFO) << "Found the network profile with SSID: " << ssid_string;
profile = connection_profile;
break;
}
}
if (profile == nullptr) {
LOG(INFO) << "No network profile found with SSID: " << ssid_string;
return result;
}
if (profile != nullptr && profile.CanDelete() &&
profile.IsWlanConnectionProfile()) {
auto profile_delete_status = profile.TryDeleteAsync().get();
switch (profile_delete_status) {
case ConnectionProfileDeleteStatus::Success:
LOG(INFO) << "WiFi profile with SSID:" << ssid_string << " is deleted.";
result = true;
break;
case ConnectionProfileDeleteStatus::DeniedBySystem:
LOG(ERROR) << "Failed to delete WiFi profile with SSID:" << ssid_string
<< " due to denied by system.";
break;
case ConnectionProfileDeleteStatus::DeniedByUser:
LOG(ERROR) << "Failed to delete WiFi profile with SSID:" << ssid_string
<< " due to denied by user.";
break;
case ConnectionProfileDeleteStatus::UnknownError:
LOG(ERROR) << "Failed to delete WiFi profile with SSID:" << ssid_string
<< " due to unknonw error.";
break;
default:
break;
}
}
return result;
}
void WifiHotspotMedium::StoreHotspotSsid(std::string ssid) {
std::unique_ptr<api::OutputFile> ssid_file;
try {