nearbyconnections : Replace WifiLanV2 to WifiLan.

PiperOrigin-RevId: 406033177
This commit is contained in:
edwinwu
2021-10-27 18:59:43 -07:00
committed by Copybara-Service
parent 94ef1b532b
commit acf516189b
43 changed files with 1353 additions and 4555 deletions
-2
View File
@@ -57,7 +57,6 @@ cc_library(
"bluetooth_classic.cc",
"webrtc.cc",
"wifi_lan.cc",
"wifi_lan_v2.cc",
],
hdrs = [
"ble.h",
@@ -65,7 +64,6 @@ cc_library(
"bluetooth_classic.h",
"webrtc.h",
"wifi_lan.h",
"wifi_lan_v2.h",
],
visibility = ["//visibility:private"],
deps = [
-6
View File
@@ -49,7 +49,6 @@
#include "platform/impl/g3/single_thread_executor.h"
#include "platform/impl/g3/webrtc.h"
#include "platform/impl/g3/wifi_lan.h"
#include "platform/impl/g3/wifi_lan_v2.h"
#include "platform/impl/shared/file.h"
namespace location {
@@ -147,11 +146,6 @@ std::unique_ptr<WifiLanMedium> ImplementationPlatform::CreateWifiLanMedium() {
return absl::make_unique<g3::WifiLanMedium>();
}
std::unique_ptr<WifiLanMediumV2>
ImplementationPlatform::CreateWifiLanMediumV2() {
return absl::make_unique<g3::WifiLanMediumV2>();
}
std::unique_ptr<WebRtcMedium> ImplementationPlatform::CreateWebRtcMedium() {
if (MediumEnvironment::Instance().GetEnvironmentConfig().webrtc_enabled) {
return absl::make_unique<g3::WebRtcMedium>();
+157 -207
View File
@@ -19,13 +19,14 @@
#include <string>
#include <utility>
#include "absl/strings/escaping.h"
#include "absl/strings/str_format.h"
#include "absl/synchronization/mutex.h"
#include "platform/api/wifi_lan.h"
#include "platform/base/cancellation_flag_listener.h"
#include "platform/base/logging.h"
#include "platform/base/medium_environment.h"
#include "platform/base/nsd_service_info.h"
#include "platform/base/prng.h"
namespace location {
namespace nearby {
@@ -73,20 +74,13 @@ Exception WifiLanSocket::Close() {
return {Exception::kSuccess};
}
WifiLanService* WifiLanSocket::GetRemoteWifiLanService() {
absl::MutexLock lock(&mutex_);
return wifi_lan_service_;
}
void WifiLanSocket::DoClose() {
if (!closed_) {
remote_socket_ = nullptr;
output_->GetOutputStream().Close();
output_->GetInputStream().Close();
if (IsConnectedLocked()) {
input_->GetOutputStream().Close();
input_->GetInputStream().Close();
}
input_->GetOutputStream().Close();
input_->GetInputStream().Close();
closed_ = true;
}
}
@@ -103,19 +97,32 @@ OutputStream& WifiLanSocket::GetLocalOutputStream() {
return output_->GetOutputStream();
}
std::unique_ptr<api::WifiLanSocket> WifiLanServerSocket::Accept(
WifiLanService* wifi_lan_service) {
absl::MutexLock lock(&mutex_);
if (closed_) return {};
while (pending_sockets_.empty()) {
cond_.Wait(&mutex_);
if (closed_) break;
std::string WifiLanServerSocket::GetName(const std::string& ip_address,
int port) {
std::string dot_delimited_string;
if (!ip_address.empty()) {
for (auto byte : ip_address) {
if (!dot_delimited_string.empty())
absl::StrAppend(&dot_delimited_string, ".");
absl::StrAppend(&dot_delimited_string, absl::StrFormat("%d", byte));
}
}
std::string out = absl::StrCat(dot_delimited_string, ":", port);
return out;
}
std::unique_ptr<api::WifiLanSocket> WifiLanServerSocket::Accept() {
absl::MutexLock lock(&mutex_);
while (!closed_ && pending_sockets_.empty()) {
cond_.Wait(&mutex_);
}
// whether or not we were running in the wait loop, return early if closed.
if (closed_) return {};
auto* remote_socket =
pending_sockets_.extract(pending_sockets_.begin()).value();
CHECK(remote_socket);
auto local_socket = std::make_unique<WifiLanSocket>(wifi_lan_service);
auto local_socket = std::make_unique<WifiLanSocket>();
local_socket->Connect(*remote_socket);
remote_socket->Connect(*local_socket);
cond_.SignalAll();
@@ -126,12 +133,12 @@ bool WifiLanServerSocket::Connect(WifiLanSocket& socket) {
absl::MutexLock lock(&mutex_);
if (closed_) return false;
if (socket.IsConnected()) {
NEARBY_LOG(ERROR,
"Failed to connect to WifiLan server socket: already connected");
NEARBY_LOGS(ERROR)
<< "Failed to connect to WifiLan server socket: already connected";
return true; // already connected.
}
// add client socket to the pending list
pending_sockets_.emplace(&socket);
pending_sockets_.insert(&socket);
cond_.SignalAll();
while (!socket.IsConnected()) {
cond_.Wait(&mutex_);
@@ -173,247 +180,190 @@ Exception WifiLanServerSocket::DoClose() {
}
WifiLanMedium::WifiLanMedium() {
wifi_lan_service_.SetMedium(this);
auto& env = MediumEnvironment::Instance();
env.RegisterWifiLanMedium(*this);
}
WifiLanMedium::~WifiLanMedium() {
wifi_lan_service_.SetMedium(nullptr);
auto& env = MediumEnvironment::Instance();
env.UnregisterWifiLanMedium(*this);
StopAdvertising(advertising_info_.service_id);
StopDiscovery(discovering_info_.service_id);
NEARBY_LOG(INFO, "WifiLanMedium dtor advertising_accept_thread_running_ = %d",
acceptance_thread_running_.load());
// If acceptance thread is still running, wait to finish.
if (acceptance_thread_running_) {
while (acceptance_thread_running_) {
shared::CountDownLatch latch(1);
close_accept_loops_runner_.Execute([&latch]() { latch.CountDown(); });
latch.Await();
}
}
}
bool WifiLanMedium::StartAdvertising(const std::string& service_id,
const NsdServiceInfo& nsd_service_info) {
NEARBY_LOG(INFO,
"G3 WifiLan StartAdvertising: service_id=%s, nsd_service_info=%p, "
"service_info_name=%s",
service_id.c_str(), &nsd_service_info,
nsd_service_info.GetServiceName().c_str());
auto& env = MediumEnvironment::Instance();
NsdServiceInfo local_nsd_service_info{nsd_service_info};
SetWifiLanService(nsd_service_info);
env.UpdateWifiLanMediumForAdvertising(*this, wifi_lan_service_, service_id,
true);
absl::MutexLock lock(&mutex_);
if (server_socket_ != nullptr) server_socket_.release();
server_socket_ = std::make_unique<WifiLanServerSocket>();
acceptance_thread_running_.exchange(true);
accept_loops_runner_.Execute([&env, this, service_id]() mutable {
if (!accept_loops_runner_.InShutdown()) {
while (true) {
auto client_socket = server_socket_->Accept(&wifi_lan_service_);
if (client_socket == nullptr) break;
env.CallWifiLanAcceptedConnectionCallback(
*this, *(client_socket.release()), service_id);
}
}
acceptance_thread_running_.exchange(false);
});
advertising_info_.service_id = service_id;
return true;
}
bool WifiLanMedium::StopAdvertising(const std::string& service_id) {
NEARBY_LOG(INFO, "G3 WifiLan StopAdvertising: service_id=%s",
service_id.c_str());
bool WifiLanMedium::StartAdvertising(const NsdServiceInfo& nsd_service_info) {
std::string service_type = nsd_service_info.GetServiceType();
NEARBY_LOGS(INFO) << "G3 WifiLan StartAdvertising: nsd_service_info="
<< &nsd_service_info
<< ", service_name=" << nsd_service_info.GetServiceName()
<< ", service_type=" << service_type;
{
absl::MutexLock lock(&mutex_);
if (advertising_info_.Empty()) {
NEARBY_LOG(INFO,
"G3 WifiLan StopAdvertising: Can't stop advertising because "
"we never started advertising.");
if (advertising_info_.Existed(service_type)) {
NEARBY_LOGS(INFO)
<< "G3 WifiLan StartAdvertising: Can't start advertising because "
"service_type="
<< service_type << ", has started already.";
return false;
}
advertising_info_.Clear();
}
auto& env = MediumEnvironment::Instance();
env.UpdateWifiLanMediumForAdvertising(*this, wifi_lan_service_, service_id,
false);
accept_loops_runner_.Shutdown();
if (server_socket_ == nullptr) {
NEARBY_LOGS(ERROR) << "G3 WifiLan StopAdvertising: failed to find WifiLan "
"Server socket: service_id="
<< service_id;
// Fall through for server socket not found.
return true;
env.UpdateWifiLanMediumForAdvertising(*this, nsd_service_info,
/*enabled=*/true);
{
absl::MutexLock lock(&mutex_);
advertising_info_.Add(service_type);
}
if (!server_socket_->Close().Ok()) {
NEARBY_LOG(INFO,
"G3 WifiLan StopAdvertising: Failed to close WifiLan server "
"socket for %s.",
service_id.c_str());
return false;
}
return true;
}
bool WifiLanMedium::StartDiscovery(const std::string& service_id,
DiscoveredServiceCallback callback) {
NEARBY_LOG(INFO, "G3 WifiLan StartDiscovery: service_id=%s",
service_id.c_str());
bool WifiLanMedium::StopAdvertising(const NsdServiceInfo& nsd_service_info) {
std::string service_type = nsd_service_info.GetServiceType();
NEARBY_LOGS(INFO) << "G3 WifiLan StopAdvertising: nsd_service_info="
<< &nsd_service_info
<< ", service_name=" << nsd_service_info.GetServiceName()
<< ", service_type=" << service_type;
{
absl::MutexLock lock(&mutex_);
if (!advertising_info_.Existed(service_type)) {
NEARBY_LOGS(INFO)
<< "G3 WifiLan StopAdvertising: Can't stop advertising because "
"we never started advertising for service_type="
<< service_type;
return false;
}
advertising_info_.Remove(service_type);
}
auto& env = MediumEnvironment::Instance();
env.UpdateWifiLanMediumForDiscovery(*this, service_id, std::move(callback),
env.UpdateWifiLanMediumForAdvertising(*this, nsd_service_info,
/*enabled=*/false);
return true;
}
bool WifiLanMedium::StartDiscovery(const std::string& service_type,
DiscoveredServiceCallback callback) {
NEARBY_LOGS(INFO) << "G3 WifiLan StartDiscovery: service_type="
<< service_type;
{
absl::MutexLock lock(&mutex_);
if (discovering_info_.Existed(service_type)) {
NEARBY_LOGS(INFO)
<< "G3 WifiLan StartDiscovery: Can't start discovery because "
"service_type="
<< service_type << " has started already.";
return false;
}
}
auto& env = MediumEnvironment::Instance();
env.UpdateWifiLanMediumForDiscovery(*this, std::move(callback), service_type,
true);
{
absl::MutexLock lock(&mutex_);
discovering_info_.service_id = service_id;
discovering_info_.Add(service_type);
}
return true;
}
bool WifiLanMedium::StopDiscovery(const std::string& service_id) {
NEARBY_LOG(INFO, "G3 WifiLan StopDiscovery: service_id=%s",
service_id.c_str());
bool WifiLanMedium::StopDiscovery(const std::string& service_type) {
NEARBY_LOGS(INFO) << "G3 WifiLan StopDiscovery: service_type="
<< service_type;
{
absl::MutexLock lock(&mutex_);
if (discovering_info_.Empty()) {
NEARBY_LOG(INFO,
"G3 WifiLan StopDiscovery: Can't stop discovering because we "
"never started discovering.");
if (!discovering_info_.Existed(service_type)) {
NEARBY_LOGS(INFO)
<< "G3 WifiLan StopDiscovery: Can't stop discovering because we "
"never started discovering.";
return false;
}
discovering_info_.Clear();
discovering_info_.Remove(service_type);
}
auto& env = MediumEnvironment::Instance();
env.UpdateWifiLanMediumForDiscovery(*this, {}, service_type, false);
return true;
}
std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
const NsdServiceInfo& remote_service_info,
CancellationFlag* cancellation_flag) {
std::string service_type = remote_service_info.GetServiceType();
NEARBY_LOGS(INFO) << "G3 WifiLan ConnectToService [self]: medium=" << this
<< ", service_type=" << service_type;
return ConnectToService(remote_service_info.GetIPAddress(),
remote_service_info.GetPort(), cancellation_flag);
}
std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
const std::string& ip_address, int port,
CancellationFlag* cancellation_flag) {
std::string socket_name = WifiLanServerSocket::GetName(ip_address, port);
NEARBY_LOGS(INFO) << "G3 WifiLan ConnectToService [self]: medium=" << this
<< ", ip address + port=" << socket_name;
// First, find an instance of remote medium, that exposed this service.
auto& env = MediumEnvironment::Instance();
auto* remote_medium =
static_cast<WifiLanMedium*>(env.GetWifiLanMedium(ip_address, port));
if (!remote_medium) {
return {};
}
auto& env = MediumEnvironment::Instance();
env.UpdateWifiLanMediumForDiscovery(*this, service_id, {}, false);
return true;
}
bool WifiLanMedium::StartAcceptingConnections(
const std::string& service_id, AcceptedConnectionCallback callback) {
NEARBY_LOG(INFO, "G3 WifiLan StartAcceptingConnections: service_id=%s",
service_id.c_str());
auto& env = MediumEnvironment::Instance();
env.UpdateWifiLanMediumForAcceptedConnection(*this, service_id, callback);
return true;
}
bool WifiLanMedium::StopAcceptingConnections(const std::string& service_id) {
NEARBY_LOG(INFO, "G3 WifiLan StopAcceptingConnections: service_id=%s",
service_id.c_str());
auto& env = MediumEnvironment::Instance();
env.UpdateWifiLanMediumForAcceptedConnection(*this, service_id, {});
return true;
}
std::unique_ptr<api::WifiLanSocket> WifiLanMedium::Connect(
api::WifiLanService& remote_wifi_lan_service, const std::string& service_id,
CancellationFlag* cancellation_flag) {
NEARBY_LOG(INFO,
"G3 WifiLan Connect: medium=%p, wifi_lan_service=%p, "
"service_info_name=%s, service_id=%s",
this, &wifi_lan_service_,
remote_wifi_lan_service.GetServiceInfo().GetServiceName().c_str(),
service_id.c_str());
// First, find an instance of remote medium, that exposed this service.
auto* remote_medium =
static_cast<WifiLanService&>(remote_wifi_lan_service).GetMedium();
if (!remote_medium) return {}; // Can't find medium. Bail out.
WifiLanServerSocket* remote_server_socket = nullptr;
NEARBY_LOG(INFO,
"G3 WifiLan Connect [peer]: remote_wifi_lan_service=%p, "
"remote_service_info_name=%s, service_id=%s",
&remote_wifi_lan_service,
remote_wifi_lan_service.GetServiceInfo().GetServiceName().c_str(),
service_id.c_str());
WifiLanServerSocket* server_socket = nullptr;
NEARBY_LOGS(INFO) << "G3 WifiLan ConnectToService [peer]: medium="
<< remote_medium
<< ", remote ip address + port=" << socket_name;
// Then, find our server socket context in this medium.
{
absl::MutexLock medium_lock(&remote_medium->mutex_);
remote_server_socket = remote_medium->server_socket_.get();
if (remote_server_socket == nullptr) {
auto item = remote_medium->server_sockets_.find(socket_name);
server_socket = item != server_sockets_.end() ? item->second : nullptr;
if (server_socket == nullptr) {
NEARBY_LOGS(ERROR)
<< "G3 WifiLan Connect: Failed to find remote WifiLan Server socket: "
"service_id="
<< service_id;
// Fall through for server socket not found.
<< "G3 WifiLan Failed to find WifiLan Server socket: socket_name="
<< socket_name;
return {};
}
}
if (cancellation_flag->Cancelled()) {
NEARBY_LOGS(INFO) << "G3 WifiLan Connect: Has been cancelled: "
"service_id="
<< service_id;
NEARBY_LOGS(ERROR) << "G3 WifiLan Connect: Has been cancelled: socket_name="
<< socket_name;
return {};
}
CancellationFlagListener listener(cancellation_flag, [this]() {
CancellationFlagListener listener(cancellation_flag, [&server_socket]() {
NEARBY_LOGS(INFO) << "G3 WifiLan Cancel Connect.";
if (server_socket_ != nullptr) server_socket_->Close();
if (server_socket != nullptr) {
server_socket->Close();
}
});
WifiLanService wifi_lan_service =
static_cast<WifiLanService&>(remote_wifi_lan_service);
auto socket = std::make_unique<WifiLanSocket>(&wifi_lan_service);
auto socket = std::make_unique<WifiLanSocket>();
// Finally, Request to connect to this socket.
if (!remote_server_socket->Connect(*socket)) {
NEARBY_LOG(ERROR,
"G3 WifiLan Connect: Failed to connect to existing WifiLan "
"Server socket: service_id=%s",
service_id.c_str());
if (!server_socket->Connect(*socket)) {
NEARBY_LOGS(ERROR) << "G3 WifiLan Failed to connect to existing WifiLan "
"Server socket: name="
<< socket_name;
return {};
}
NEARBY_LOG(INFO, "G3 WifiLan Connect: connected: socket=%p", socket.get());
NEARBY_LOGS(INFO) << "G3 WifiLan ConnectToService: connected: socket="
<< socket.get();
return socket;
}
api::WifiLanService* WifiLanMedium::GetRemoteService(
const std::string& ip_address, int port) {
std::unique_ptr<api::WifiLanServerSocket> WifiLanMedium::ListenForService(
int port) {
auto& env = MediumEnvironment::Instance();
return env.GetWifiLanService(ip_address, port);
}
std::pair<std::string, int> WifiLanMedium::GetCredentials(
const std::string& service_id) {
NEARBY_LOGS(INFO) << "G3 WifiLan GetCredential: service_id=" << service_id;
return std::make_pair(wifi_lan_service_.GetServiceInfo().GetIPAddress(),
wifi_lan_service_.GetServiceInfo().GetPort());
}
void WifiLanMedium::SetWifiLanService(const NsdServiceInfo& nsd_service_info) {
NsdServiceInfo local_nsd_service_info{nsd_service_info};
auto credential = GetFakeCredentials();
local_nsd_service_info.SetIPAddress(credential.first);
local_nsd_service_info.SetPort(credential.second);
wifi_lan_service_.SetServiceInfo(local_nsd_service_info);
}
std::pair<std::string, int> WifiLanMedium::GetFakeCredentials() const {
std::string ip_address;
ip_address.resize(4);
uint32_t raw_ip_addr = Prng().NextUint32();
uint16_t port = Prng().NextUint32();
ip_address[0] = static_cast<char>(raw_ip_addr >> 24);
ip_address[1] = static_cast<char>(raw_ip_addr >> 16);
ip_address[2] = static_cast<char>(raw_ip_addr >> 8);
ip_address[3] = static_cast<char>(raw_ip_addr >> 0);
return std::make_pair(ip_address, port);
auto server_socket = std::make_unique<WifiLanServerSocket>();
server_socket->SetIPAddress(env.GetFakeIPAddress());
server_socket->SetPort(port == 0 ? env.GetFakePort() : port);
std::string socket_name = WifiLanServerSocket::GetName(
server_socket->GetIPAddress(), server_socket->GetPort());
server_socket->SetCloseNotifier([this, socket_name]() {
absl::MutexLock lock(&mutex_);
server_sockets_.erase(socket_name);
});
NEARBY_LOGS(INFO) << "G3 WifiLan Adding server socket: medium=" << this
<< ", socket_name=" << socket_name;
absl::MutexLock lock(&mutex_);
server_sockets_.insert({socket_name, server_socket.get()});
return server_socket;
}
} // namespace g3
+111 -89
View File
@@ -36,34 +36,9 @@ namespace g3 {
class WifiLanMedium;
// Opaque wrapper over a WifiLan service which contains |NsdServiceInfo|.
class WifiLanService : public api::WifiLanService {
public:
WifiLanService() = default;
explicit WifiLanService(NsdServiceInfo nsd_service_info)
: nsd_service_info_(std::move(nsd_service_info)) {}
~WifiLanService() override = default;
NsdServiceInfo GetServiceInfo() const override { return nsd_service_info_; }
void SetServiceInfo(NsdServiceInfo nsd_service_info) {
nsd_service_info_ = std::move(nsd_service_info);
}
WifiLanMedium* GetMedium() { return medium_; }
void SetMedium(WifiLanMedium* medium) { medium_ = medium; }
private:
NsdServiceInfo nsd_service_info_;
WifiLanMedium* medium_ = nullptr;
};
class WifiLanSocket : public api::WifiLanSocket {
public:
WifiLanSocket() = default;
explicit WifiLanSocket(WifiLanService* wifi_lan_service)
: wifi_lan_service_(wifi_lan_service) {}
~WifiLanSocket() override;
// Connect to another WifiLanSocket, to form a functional low-level channel.
@@ -89,11 +64,6 @@ class WifiLanSocket : public api::WifiLanSocket {
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
Exception Close() override ABSL_LOCKS_EXCLUDED(mutex_);
// Returns valid WifiLanService pointer if there is a connection, and
// nullptr otherwise.
WifiLanService* GetRemoteWifiLanService() override
ABSL_LOCKS_EXCLUDED(mutex_);
private:
void DoClose() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
@@ -116,14 +86,39 @@ class WifiLanSocket : public api::WifiLanSocket {
std::shared_ptr<Pipe> output_{new Pipe};
std::shared_ptr<Pipe> input_;
mutable absl::Mutex mutex_;
WifiLanService* wifi_lan_service_;
WifiLanSocket* remote_socket_ ABSL_GUARDED_BY(mutex_) = nullptr;
bool closed_ ABSL_GUARDED_BY(mutex_) = false;
};
class WifiLanServerSocket {
class WifiLanServerSocket : public api::WifiLanServerSocket {
public:
~WifiLanServerSocket();
static std::string GetName(const std::string& ip_address, int port);
~WifiLanServerSocket() override;
// Gets ip address.
std::string GetIPAddress() const override ABSL_LOCKS_EXCLUDED(mutex_) {
absl::MutexLock lock(&mutex_);
return ip_address_;
}
// Sets the ip address.
void SetIPAddress(const std::string& ip_address) ABSL_LOCKS_EXCLUDED(mutex_) {
absl::MutexLock lock(&mutex_);
ip_address_ = ip_address;
}
// Gets the port.
int GetPort() const override ABSL_LOCKS_EXCLUDED(mutex_) {
absl::MutexLock lock(&mutex_);
return port_;
}
// Sets the port.
void SetPort(int port) ABSL_LOCKS_EXCLUDED(mutex_) {
absl::MutexLock lock(&mutex_);
port_ = port;
}
// Blocks until either:
// - at least one incoming connection request is available, or
@@ -135,7 +130,7 @@ class WifiLanServerSocket {
// Called by the server side of a connection.
// Returns WifiLanSocket to the server side.
// If not null, returned socket is connected to its remote (client-side) peer.
std::unique_ptr<api::WifiLanSocket> Accept(WifiLanService* service)
std::unique_ptr<api::WifiLanSocket> Accept() override
ABSL_LOCKS_EXCLUDED(mutex_);
// Blocks until either:
@@ -149,18 +144,20 @@ class WifiLanServerSocket {
// Called by the server side of a connection before passing ownership of
// WifiLanServerSocker to user, to track validity of a pointer to this
// server socket,
// server socket.
void SetCloseNotifier(std::function<void()> notifier)
ABSL_LOCKS_EXCLUDED(mutex_);
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
// Calls close_notifier if it was previously set, and marks socket as closed.
Exception Close() ABSL_LOCKS_EXCLUDED(mutex_);
Exception Close() override ABSL_LOCKS_EXCLUDED(mutex_);
private:
Exception DoClose() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
absl::Mutex mutex_;
mutable absl::Mutex mutex_;
std::string ip_address_ ABSL_GUARDED_BY(mutex_);
int port_ ABSL_GUARDED_BY(mutex_);
absl::CondVar cond_;
absl::flat_hash_set<WifiLanSocket*> pending_sockets_ ABSL_GUARDED_BY(mutex_);
std::function<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
@@ -173,81 +170,106 @@ class WifiLanMedium : public api::WifiLanMedium {
WifiLanMedium();
~WifiLanMedium() override;
bool StartAdvertising(const std::string& service_id,
const NsdServiceInfo& nsd_service_info) override
ABSL_LOCKS_EXCLUDED(mutex_);
bool StopAdvertising(const std::string& service_id) override
// Starts WifiLan advertising.
//
// nsd_service_info - NsdServiceInfo data that's advertised through mDNS
// service.
// On success if the service is now advertising.
// On error if the service cannot start to advertise or the service type in
// NsdServiceInfo has been passed previously which StopAdvertising is not
// been called.
bool StartAdvertising(const NsdServiceInfo& nsd_service_info) override
ABSL_LOCKS_EXCLUDED(mutex_);
// Returns true once the WifiLan discovery has been initiated.
bool StartDiscovery(const std::string& service_id,
// Stops WifiLan advertising.
//
// nsd_service_info - NsdServiceInfo data that's advertised through mDNS
// service.
// On success if the service stops advertising.
// On error if the service cannot stop advertising or the service type in
// NsdServiceInfo cannot be found.
bool StopAdvertising(const NsdServiceInfo& nsd_service_info) override
ABSL_LOCKS_EXCLUDED(mutex_);
// Starts the discovery of nearby WifiLan services.
//
// Returns true once the WifiLan discovery has been initiated. The
// service_type is associated with callback.
bool StartDiscovery(const std::string& service_type,
DiscoveredServiceCallback callback) override
ABSL_LOCKS_EXCLUDED(mutex_);
// Returns true once WifiLan discovery for service_id is well and truly
// stopped; after this returns, there must be no more invocations of the
// DiscoveredServiceCallback passed in to StartDiscovery() for service_id.
bool StopDiscovery(const std::string& service_id) override
ABSL_LOCKS_EXCLUDED(mutex_);
// Returns true once WifiLan socket connection requests to service_id can be
// accepted.
bool StartAcceptingConnections(const std::string& service_id,
AcceptedConnectionCallback callback) override
ABSL_LOCKS_EXCLUDED(mutex_);
bool StopAcceptingConnections(const std::string& service_id) override
ABSL_LOCKS_EXCLUDED(mutex_);
// Connects to existing remote WifiLan service.
// Stops the discovery of nearby WifiLan services.
//
// service_type - The one assigend in StartDiscovery.
// On success if service_type is matched to the callback and will be removed
// from the list. If list is empty then stops the WifiLan discovery
// service.
// On error if the service_type is not existed, then return immediately.
bool StopDiscovery(const std::string& service_type) override
ABSL_LOCKS_EXCLUDED(mutex_);
// Connects to a WifiLan service.
// On success, returns a new WifiLanSocket.
// On error, returns nullptr.
std::unique_ptr<api::WifiLanSocket> Connect(
api::WifiLanService& remote_wifi_lan_service,
const std::string& service_id,
std::unique_ptr<api::WifiLanSocket> ConnectToService(
const NsdServiceInfo& remote_service_info,
CancellationFlag* cancellation_flag) override ABSL_LOCKS_EXCLUDED(mutex_);
api::WifiLanService* GetRemoteService(const std::string& ip_address,
int port) override;
// Connects to a WifiLan service by ip address and port.
// On success, returns a new WifiLanSocket.
// On error, returns nullptr.
std::unique_ptr<api::WifiLanSocket> ConnectToService(
const std::string& ip_address, int port,
CancellationFlag* cancellation_flag) override ABSL_LOCKS_EXCLUDED(mutex_);
std::pair<std::string, int> GetCredentials(
const std::string& service_id) override ABSL_LOCKS_EXCLUDED(mutex_);
// Listens for incoming connection.
//
// port - A port number.
// 0 : use a random port.
// 1~65536 : open a server socket on that exact port.
// On success, returns a new WifiLanServerSocket.
// On error, returns nullptr.
std::unique_ptr<api::WifiLanServerSocket> ListenForService(int port) override
ABSL_LOCKS_EXCLUDED(mutex_);
private:
static constexpr int kMaxConcurrentAcceptLoops = 5;
struct AdvertisingInfo {
bool Empty() const { return service_id.empty(); }
void Clear() { service_id.clear(); }
bool Empty() const { return service_types.empty(); }
void Clear() { service_types.clear(); }
void Add(const std::string& service_type) {
service_types.insert(service_type);
}
void Remove(const std::string& service_type) {
service_types.erase(service_type);
}
bool Existed(const std::string& service_type) const {
return service_types.contains(service_type);
}
std::string service_id;
absl::flat_hash_set<std::string> service_types;
};
struct DiscoveringInfo {
bool Empty() const { return service_id.empty(); }
void Clear() { service_id.clear(); }
bool Empty() const { return service_types.empty(); }
void Clear() { service_types.clear(); }
void Add(const std::string& service_type) {
service_types.insert(service_type);
}
void Remove(const std::string& service_type) {
service_types.erase(service_type);
}
bool Existed(const std::string& service_type) const {
return service_types.contains(service_type);
}
std::string service_id;
absl::flat_hash_set<std::string> service_types;
};
void SetWifiLanService(const NsdServiceInfo& nsd_service_info);
std::pair<std::string, int> GetFakeCredentials() const;
absl::Mutex mutex_;
WifiLanService wifi_lan_service_;
// A thread pool dedicated to running all the accept loops from
// StartAdvertising().
MultiThreadExecutor accept_loops_runner_{kMaxConcurrentAcceptLoops};
std::atomic_bool acceptance_thread_running_ = false;
// A thread pool dedicated to wait to complete the accept_loops_runner_.
MultiThreadExecutor close_accept_loops_runner_{kMaxConcurrentAcceptLoops};
// A server socket is established when start advertising.
std::unique_ptr<WifiLanServerSocket> server_socket_;
AdvertisingInfo advertising_info_ ABSL_GUARDED_BY(mutex_);
DiscoveringInfo discovering_info_ ABSL_GUARDED_BY(mutex_);
absl::flat_hash_map<std::string, WifiLanServerSocket*> server_sockets_
ABSL_GUARDED_BY(mutex_);
};
} // namespace g3
-371
View File
@@ -1,371 +0,0 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "platform/impl/g3/wifi_lan_v2.h"
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include "absl/strings/escaping.h"
#include "absl/strings/str_format.h"
#include "absl/synchronization/mutex.h"
#include "platform/api/wifi_lan_v2.h"
#include "platform/base/cancellation_flag_listener.h"
#include "platform/base/logging.h"
#include "platform/base/medium_environment.h"
#include "platform/base/nsd_service_info.h"
namespace location {
namespace nearby {
namespace g3 {
WifiLanSocketV2::~WifiLanSocketV2() {
absl::MutexLock lock(&mutex_);
DoClose();
}
void WifiLanSocketV2::Connect(WifiLanSocketV2& other) {
absl::MutexLock lock(&mutex_);
remote_socket_ = &other;
input_ = other.output_;
}
InputStream& WifiLanSocketV2::GetInputStream() {
auto* remote_socket = GetRemoteSocket();
CHECK(remote_socket != nullptr);
return remote_socket->GetLocalInputStream();
}
OutputStream& WifiLanSocketV2::GetOutputStream() {
return GetLocalOutputStream();
}
WifiLanSocketV2* WifiLanSocketV2::GetRemoteSocket() {
absl::MutexLock lock(&mutex_);
return remote_socket_;
}
bool WifiLanSocketV2::IsConnected() const {
absl::MutexLock lock(&mutex_);
return IsConnectedLocked();
}
bool WifiLanSocketV2::IsClosed() const {
absl::MutexLock lock(&mutex_);
return closed_;
}
Exception WifiLanSocketV2::Close() {
absl::MutexLock lock(&mutex_);
DoClose();
return {Exception::kSuccess};
}
void WifiLanSocketV2::DoClose() {
if (!closed_) {
remote_socket_ = nullptr;
output_->GetOutputStream().Close();
output_->GetInputStream().Close();
input_->GetOutputStream().Close();
input_->GetInputStream().Close();
closed_ = true;
}
}
bool WifiLanSocketV2::IsConnectedLocked() const { return input_ != nullptr; }
InputStream& WifiLanSocketV2::GetLocalInputStream() {
absl::MutexLock lock(&mutex_);
return output_->GetInputStream();
}
OutputStream& WifiLanSocketV2::GetLocalOutputStream() {
absl::MutexLock lock(&mutex_);
return output_->GetOutputStream();
}
std::string WifiLanServerSocketV2::GetName(const std::string& ip_address,
int port) {
std::string dot_delimited_string;
if (!ip_address.empty()) {
for (auto byte : ip_address) {
if (!dot_delimited_string.empty())
absl::StrAppend(&dot_delimited_string, ".");
absl::StrAppend(&dot_delimited_string, absl::StrFormat("%d", byte));
}
}
std::string out = absl::StrCat(dot_delimited_string, ":", port);
return out;
}
std::unique_ptr<api::WifiLanSocketV2> WifiLanServerSocketV2::Accept() {
absl::MutexLock lock(&mutex_);
while (!closed_ && pending_sockets_.empty()) {
cond_.Wait(&mutex_);
}
// whether or not we were running in the wait loop, return early if closed.
if (closed_) return {};
auto* remote_socket =
pending_sockets_.extract(pending_sockets_.begin()).value();
CHECK(remote_socket);
auto local_socket = std::make_unique<WifiLanSocketV2>();
local_socket->Connect(*remote_socket);
remote_socket->Connect(*local_socket);
cond_.SignalAll();
return local_socket;
}
bool WifiLanServerSocketV2::Connect(WifiLanSocketV2& socket) {
absl::MutexLock lock(&mutex_);
if (closed_) return false;
if (socket.IsConnected()) {
NEARBY_LOGS(ERROR)
<< "Failed to connect to WifiLan server socket: already connected";
return true; // already connected.
}
// add client socket to the pending list
pending_sockets_.insert(&socket);
cond_.SignalAll();
while (!socket.IsConnected()) {
cond_.Wait(&mutex_);
if (closed_) return false;
}
return true;
}
void WifiLanServerSocketV2::SetCloseNotifier(std::function<void()> notifier) {
absl::MutexLock lock(&mutex_);
close_notifier_ = std::move(notifier);
}
WifiLanServerSocketV2::~WifiLanServerSocketV2() {
absl::MutexLock lock(&mutex_);
DoClose();
}
Exception WifiLanServerSocketV2::Close() {
absl::MutexLock lock(&mutex_);
return DoClose();
}
Exception WifiLanServerSocketV2::DoClose() {
bool should_notify = !closed_;
closed_ = true;
if (should_notify) {
cond_.SignalAll();
if (close_notifier_) {
auto notifier = std::move(close_notifier_);
mutex_.Unlock();
// Notifier may contain calls to public API, and may cause deadlock, if
// mutex_ is held during the call.
notifier();
mutex_.Lock();
}
}
return {Exception::kSuccess};
}
WifiLanMediumV2::WifiLanMediumV2() {
auto& env = MediumEnvironment::Instance();
env.RegisterWifiLanMediumV2(*this);
}
WifiLanMediumV2::~WifiLanMediumV2() {
auto& env = MediumEnvironment::Instance();
env.UnregisterWifiLanMediumV2(*this);
}
bool WifiLanMediumV2::StartAdvertising(const NsdServiceInfo& nsd_service_info) {
std::string service_type = nsd_service_info.GetServiceType();
NEARBY_LOGS(INFO) << "G3 WifiLan StartAdvertising: nsd_service_info="
<< &nsd_service_info
<< ", service_name=" << nsd_service_info.GetServiceName()
<< ", service_type=" << service_type;
{
absl::MutexLock lock(&mutex_);
if (advertising_info_.Existed(service_type)) {
NEARBY_LOGS(INFO)
<< "G3 WifiLan StartAdvertising: Can't start advertising because "
"service_type="
<< service_type << ", has started already.";
return false;
}
}
auto& env = MediumEnvironment::Instance();
env.UpdateWifiLanMediumV2ForAdvertising(*this, nsd_service_info,
/*enabled=*/true);
{
absl::MutexLock lock(&mutex_);
advertising_info_.Add(service_type);
}
return true;
}
bool WifiLanMediumV2::StopAdvertising(const NsdServiceInfo& nsd_service_info) {
std::string service_type = nsd_service_info.GetServiceType();
NEARBY_LOGS(INFO) << "G3 WifiLan StopAdvertising: nsd_service_info="
<< &nsd_service_info
<< ", service_name=" << nsd_service_info.GetServiceName()
<< ", service_type=" << service_type;
{
absl::MutexLock lock(&mutex_);
if (!advertising_info_.Existed(service_type)) {
NEARBY_LOGS(INFO)
<< "G3 WifiLan StopAdvertising: Can't stop advertising because "
"we never started advertising for service_type="
<< service_type;
return false;
}
advertising_info_.Remove(service_type);
}
auto& env = MediumEnvironment::Instance();
env.UpdateWifiLanMediumV2ForAdvertising(*this, nsd_service_info,
/*enabled=*/false);
return true;
}
bool WifiLanMediumV2::StartDiscovery(const std::string& service_type,
DiscoveredServiceCallback callback) {
NEARBY_LOGS(INFO) << "G3 WifiLan StartDiscovery: service_type="
<< service_type;
{
absl::MutexLock lock(&mutex_);
if (discovering_info_.Existed(service_type)) {
NEARBY_LOGS(INFO)
<< "G3 WifiLan StartDiscovery: Can't start discovery because "
"service_type="
<< service_type << " has started already.";
return false;
}
}
auto& env = MediumEnvironment::Instance();
env.UpdateWifiLanMediumV2ForDiscovery(*this, std::move(callback),
service_type, true);
{
absl::MutexLock lock(&mutex_);
discovering_info_.Add(service_type);
}
return true;
}
bool WifiLanMediumV2::StopDiscovery(const std::string& service_type) {
NEARBY_LOGS(INFO) << "G3 WifiLan StopDiscovery: service_type="
<< service_type;
{
absl::MutexLock lock(&mutex_);
if (!discovering_info_.Existed(service_type)) {
NEARBY_LOGS(INFO)
<< "G3 WifiLan StopDiscovery: Can't stop discovering because we "
"never started discovering.";
return false;
}
discovering_info_.Remove(service_type);
}
auto& env = MediumEnvironment::Instance();
env.UpdateWifiLanMediumV2ForDiscovery(*this, {}, service_type, false);
return true;
}
std::unique_ptr<api::WifiLanSocketV2> WifiLanMediumV2::ConnectToService(
const NsdServiceInfo& remote_service_info,
CancellationFlag* cancellation_flag) {
std::string service_type = remote_service_info.GetServiceType();
NEARBY_LOGS(INFO) << "G3 WifiLan ConnectToService [self]: medium=" << this
<< ", service_type=" << service_type;
return ConnectToService(remote_service_info.GetIPAddress(),
remote_service_info.GetPort(), cancellation_flag);
}
std::unique_ptr<api::WifiLanSocketV2> WifiLanMediumV2::ConnectToService(
const std::string& ip_address, int port,
CancellationFlag* cancellation_flag) {
std::string socket_name = WifiLanServerSocketV2::GetName(ip_address, port);
NEARBY_LOGS(INFO) << "G3 WifiLan ConnectToService [self]: medium=" << this
<< ", ip address + port=" << socket_name;
// First, find an instance of remote medium, that exposed this service.
auto& env = MediumEnvironment::Instance();
auto* remote_medium =
static_cast<WifiLanMediumV2*>(env.GetWifiLanV2Medium(ip_address, port));
if (!remote_medium) {
return {};
}
WifiLanServerSocketV2* server_socket = nullptr;
NEARBY_LOGS(INFO) << "G3 WifiLan ConnectToService [peer]: medium="
<< remote_medium
<< ", remote ip address + port=" << socket_name;
// Then, find our server socket context in this medium.
{
absl::MutexLock medium_lock(&remote_medium->mutex_);
auto item = remote_medium->server_sockets_.find(socket_name);
server_socket = item != server_sockets_.end() ? item->second : nullptr;
if (server_socket == nullptr) {
NEARBY_LOGS(ERROR)
<< "G3 WifiLan Failed to find WifiLan Server socket: socket_name="
<< socket_name;
return {};
}
}
if (cancellation_flag->Cancelled()) {
NEARBY_LOGS(ERROR) << "G3 WifiLan Connect: Has been cancelled: socket_name="
<< socket_name;
return {};
}
CancellationFlagListener listener(cancellation_flag, [&server_socket]() {
NEARBY_LOGS(INFO) << "G3 WifiLan Cancel Connect.";
if (server_socket != nullptr) {
server_socket->Close();
}
});
auto socket = std::make_unique<WifiLanSocketV2>();
// Finally, Request to connect to this socket.
if (!server_socket->Connect(*socket)) {
NEARBY_LOGS(ERROR) << "G3 WifiLan Failed to connect to existing WifiLan "
"Server socket: name="
<< socket_name;
return {};
}
NEARBY_LOGS(INFO) << "G3 WifiLan ConnectToService: connected: socket="
<< socket.get();
return socket;
}
std::unique_ptr<api::WifiLanServerSocketV2> WifiLanMediumV2::ListenForService(
int port) {
auto& env = MediumEnvironment::Instance();
auto server_socket = std::make_unique<WifiLanServerSocketV2>();
server_socket->SetIPAddress(env.GetFakeIPAddress());
server_socket->SetPort(port == 0 ? env.GetFakePort() : port);
std::string socket_name = WifiLanServerSocketV2::GetName(
server_socket->GetIPAddress(), server_socket->GetPort());
server_socket->SetCloseNotifier([this, socket_name]() {
absl::MutexLock lock(&mutex_);
server_sockets_.erase(socket_name);
});
NEARBY_LOGS(INFO) << "G3 WifiLan Adding server socket: medium=" << this
<< ", socket_name=" << socket_name;
absl::MutexLock lock(&mutex_);
server_sockets_.insert({socket_name, server_socket.get()});
return server_socket;
}
} // namespace g3
} // namespace nearby
} // namespace location
-280
View File
@@ -1,280 +0,0 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef PLATFORM_IMPL_G3_WIFI_LAN_V2_H_
#define PLATFORM_IMPL_G3_WIFI_LAN_V2_H_
#include <memory>
#include <string>
#include <utility>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/synchronization/mutex.h"
#include "platform/api/wifi_lan_v2.h"
#include "platform/base/byte_array.h"
#include "platform/base/input_stream.h"
#include "platform/base/nsd_service_info.h"
#include "platform/base/output_stream.h"
#include "platform/impl/g3/multi_thread_executor.h"
#include "platform/impl/g3/pipe.h"
namespace location {
namespace nearby {
namespace g3 {
class WifiLanMediumV2;
class WifiLanSocketV2 : public api::WifiLanSocketV2 {
public:
WifiLanSocketV2() = default;
~WifiLanSocketV2() override;
// Connect to another WifiLanSocket, to form a functional low-level channel.
// from this point on, and until Close is called, connection exists.
void Connect(WifiLanSocketV2& other) ABSL_LOCKS_EXCLUDED(mutex_);
// Returns the InputStream of this connected WifiLanSocket.
InputStream& GetInputStream() override ABSL_LOCKS_EXCLUDED(mutex_);
// Returns the OutputStream of this connected WifiLanSocket.
// This stream is for local side to write.
OutputStream& GetOutputStream() override ABSL_LOCKS_EXCLUDED(mutex_);
// Returns address of a remote WifiLanSocket or nullptr.
WifiLanSocketV2* GetRemoteSocket() ABSL_LOCKS_EXCLUDED(mutex_);
// Returns true if connection exists to the (possibly closed) remote socket.
bool IsConnected() const ABSL_LOCKS_EXCLUDED(mutex_);
// Returns true if socket is closed.
bool IsClosed() const ABSL_LOCKS_EXCLUDED(mutex_);
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
Exception Close() override ABSL_LOCKS_EXCLUDED(mutex_);
private:
void DoClose() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
// Returns true if connection exists to the (possibly closed) remote socket.
bool IsConnectedLocked() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
// Returns InputStream of our side of a connection.
// This is what the remote side is supposed to read from.
// This is a helper for GetInputStream() method.
InputStream& GetLocalInputStream() ABSL_LOCKS_EXCLUDED(mutex_);
// Returns OutputStream of our side of a connection.
// This is what the local size is supposed to write to.
// This is a helper for GetOutputStream() method.
OutputStream& GetLocalOutputStream() ABSL_LOCKS_EXCLUDED(mutex_);
// Output pipe is initialized by constructor, it remains always valid, until
// it is closed. it represents output part of a local socket. Input part of a
// local socket comes from the peer socket, after connection.
std::shared_ptr<Pipe> output_{new Pipe};
std::shared_ptr<Pipe> input_;
mutable absl::Mutex mutex_;
WifiLanSocketV2* remote_socket_ ABSL_GUARDED_BY(mutex_) = nullptr;
bool closed_ ABSL_GUARDED_BY(mutex_) = false;
};
class WifiLanServerSocketV2 : public api::WifiLanServerSocketV2 {
public:
static std::string GetName(const std::string& ip_address, int port);
~WifiLanServerSocketV2() override;
// Gets ip address.
std::string GetIPAddress() const override ABSL_LOCKS_EXCLUDED(mutex_) {
absl::MutexLock lock(&mutex_);
return ip_address_;
}
// Sets the ip address.
void SetIPAddress(const std::string& ip_address) ABSL_LOCKS_EXCLUDED(mutex_) {
absl::MutexLock lock(&mutex_);
ip_address_ = ip_address;
}
// Gets the port.
int GetPort() const override ABSL_LOCKS_EXCLUDED(mutex_) {
absl::MutexLock lock(&mutex_);
return port_;
}
// Sets the port.
void SetPort(int port) ABSL_LOCKS_EXCLUDED(mutex_) {
absl::MutexLock lock(&mutex_);
port_ = port;
}
// Blocks until either:
// - at least one incoming connection request is available, or
// - ServerSocket is closed.
// On success, returns connected socket, ready to exchange data.
// Returns nullptr on error.
// Once error is reported, it is permanent, and ServerSocket has to be closed.
//
// Called by the server side of a connection.
// Returns WifiLanSocket to the server side.
// If not null, returned socket is connected to its remote (client-side) peer.
std::unique_ptr<api::WifiLanSocketV2> Accept() override
ABSL_LOCKS_EXCLUDED(mutex_);
// Blocks until either:
// - connection is available, or
// - server socket is closed, or
// - error happens.
//
// Called by the client side of a connection.
// Returns true, if socket is successfully connected.
bool Connect(WifiLanSocketV2& socket) ABSL_LOCKS_EXCLUDED(mutex_);
// Called by the server side of a connection before passing ownership of
// WifiLanServerSocker to user, to track validity of a pointer to this
// server socket.
void SetCloseNotifier(std::function<void()> notifier)
ABSL_LOCKS_EXCLUDED(mutex_);
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
// Calls close_notifier if it was previously set, and marks socket as closed.
Exception Close() override ABSL_LOCKS_EXCLUDED(mutex_);
private:
Exception DoClose() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
mutable absl::Mutex mutex_;
std::string ip_address_ ABSL_GUARDED_BY(mutex_);
int port_ ABSL_GUARDED_BY(mutex_);
absl::CondVar cond_;
absl::flat_hash_set<WifiLanSocketV2*> pending_sockets_
ABSL_GUARDED_BY(mutex_);
std::function<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
bool closed_ ABSL_GUARDED_BY(mutex_) = false;
};
// Container of operations that can be performed over the WifiLan medium.
class WifiLanMediumV2 : public api::WifiLanMediumV2 {
public:
WifiLanMediumV2();
~WifiLanMediumV2() override;
// Starts WifiLan advertising.
//
// nsd_service_info - NsdServiceInfo data that's advertised through mDNS
// service.
// On success if the service is now advertising.
// On error if the service cannot start to advertise or the service type in
// NsdServiceInfo has been passed previously which StopAdvertising is not
// been called.
bool StartAdvertising(const NsdServiceInfo& nsd_service_info) override
ABSL_LOCKS_EXCLUDED(mutex_);
// Stops WifiLan advertising.
//
// nsd_service_info - NsdServiceInfo data that's advertised through mDNS
// service.
// On success if the service stops advertising.
// On error if the service cannot stop advertising or the service type in
// NsdServiceInfo cannot be found.
bool StopAdvertising(const NsdServiceInfo& nsd_service_info) override
ABSL_LOCKS_EXCLUDED(mutex_);
// Starts the discovery of nearby WifiLan services.
//
// Returns true once the WifiLan discovery has been initiated. The
// service_type is associated with callback.
bool StartDiscovery(const std::string& service_type,
DiscoveredServiceCallback callback) override
ABSL_LOCKS_EXCLUDED(mutex_);
// Stops the discovery of nearby WifiLan services.
//
// service_type - The one assigend in StartDiscovery.
// On success if service_type is matched to the callback and will be removed
// from the list. If list is empty then stops the WifiLan discovery
// service.
// On error if the service_type is not existed, then return immediately.
bool StopDiscovery(const std::string& service_type) override
ABSL_LOCKS_EXCLUDED(mutex_);
// Connects to a WifiLan service.
// On success, returns a new WifiLanSocket.
// On error, returns nullptr.
std::unique_ptr<api::WifiLanSocketV2> ConnectToService(
const NsdServiceInfo& remote_service_info,
CancellationFlag* cancellation_flag) override;
// Connects to a WifiLan service by ip address and port.
// On success, returns a new WifiLanSocket.
// On error, returns nullptr.
std::unique_ptr<api::WifiLanSocketV2> ConnectToService(
const std::string& ip_address, int port,
CancellationFlag* cancellation_flag) override;
// Listens for incoming connection.
//
// port - A port number.
// 0 : use a random port.
// 1~65536 : open a server socket on that exact port.
// On success, returns a new WifiLanServerSocket.
// On error, returns nullptr.
std::unique_ptr<api::WifiLanServerSocketV2> ListenForService(
int port = 0) override;
private:
struct AdvertisingInfo {
bool Empty() const { return service_types.empty(); }
void Clear() { service_types.clear(); }
void Add(const std::string& service_type) {
service_types.insert(service_type);
}
void Remove(const std::string& service_type) {
service_types.erase(service_type);
}
bool Existed(const std::string& service_type) const {
return service_types.contains(service_type);
}
absl::flat_hash_set<std::string> service_types;
};
struct DiscoveringInfo {
bool Empty() const { return service_types.empty(); }
void Clear() { service_types.clear(); }
void Add(const std::string& service_type) {
service_types.insert(service_type);
}
void Remove(const std::string& service_type) {
service_types.erase(service_type);
}
bool Existed(const std::string& service_type) const {
return service_types.contains(service_type);
}
absl::flat_hash_set<std::string> service_types;
};
absl::Mutex mutex_;
AdvertisingInfo advertising_info_ ABSL_GUARDED_BY(mutex_);
DiscoveringInfo discovering_info_ ABSL_GUARDED_BY(mutex_);
absl::flat_hash_map<std::string, WifiLanServerSocketV2*> server_sockets_
ABSL_GUARDED_BY(mutex_);
};
} // namespace g3
} // namespace nearby
} // namespace location
#endif // PLATFORM_IMPL_G3_WIFI_LAN_V2_H_
-4
View File
@@ -64,7 +64,6 @@ cc_library(
"thread_pool.h",
"webrtc.h",
"wifi.h",
"wifi_lan.h",
],
compatible_with = ["//buildenv/target:non_prod"],
visibility = ["//visibility:private"],
@@ -105,9 +104,6 @@ cc_library(
"system_clock.cc",
"thread_pool.cc",
"utils.cc",
"wifi_lan_medium.cc",
"wifi_lan_nsd.cc",
"wifi_lan_socket.cc",
],
compatible_with = ["//buildenv/target:non_prod"],
copts = ["-Ithird_party/nearby_connections/cpp/platform/impl/windows/generated"],
+1 -8
View File
@@ -34,7 +34,6 @@
#include "platform/impl/windows/submittable_executor.h"
#include "platform/impl/windows/webrtc.h"
#include "platform/impl/windows/wifi.h"
#include "platform/impl/windows/wifi_lan.h"
namespace location {
namespace nearby {
@@ -141,13 +140,7 @@ std::unique_ptr<WifiMedium> ImplementationPlatform::CreateWifiMedium() {
// TODO(b/184975123): replace with real implementation.
std::unique_ptr<WifiLanMedium> ImplementationPlatform::CreateWifiLanMedium() {
return absl::make_unique<windows::WifiLanMedium>();
}
// TODO(b/184975123): replace with real implementation.
std::unique_ptr<WifiLanMediumV2>
ImplementationPlatform::CreateWifiLanMediumV2() {
return std::unique_ptr<WifiLanMediumV2>();
return std::unique_ptr<WifiLanMedium>();
}
// TODO(b/184975123): replace with real implementation.