[wlan][rustfmt] Format garnet/bin/wlan
Garnet has a new default rustfmt.toml which we should use in WLAN
Test=not applicable
Change-Id: I226057384b9573bcb197969ae6b7f451a29e1e08
diff --git a/bin/wlan/wlan-ap-smoke-test/BUILD.gn b/bin/wlan/wlan-ap-smoke-test/BUILD.gn
index 2c1c1ee..44434f3 100644
--- a/bin/wlan/wlan-ap-smoke-test/BUILD.gn
+++ b/bin/wlan/wlan-ap-smoke-test/BUILD.gn
@@ -2,8 +2,8 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-import("//build/rust/rustc_binary.gni")
import("//build/package.gni")
+import("//build/rust/rustc_binary.gni")
rustc_binary("bin") {
name = "wlan_ap_smoke_test"
diff --git a/bin/wlan/wlan-ap-smoke-test/src/main.rs b/bin/wlan/wlan-ap-smoke-test/src/main.rs
index 6480763..d667126 100644
--- a/bin/wlan/wlan-ap-smoke-test/src/main.rs
+++ b/bin/wlan/wlan-ap-smoke-test/src/main.rs
@@ -11,9 +11,9 @@
mod opts;
+use crate::opts::Opt;
use connectivity_testing::wlan_ap_service_util;
use connectivity_testing::wlan_service_util;
-use crate::opts::Opt;
use failure::{bail, Error, ResultExt};
use fidl_fuchsia_wlan_device_service::{DeviceServiceMarker, DeviceServiceProxy};
use fidl_fuchsia_wlan_sme as fidl_sme;
@@ -110,9 +110,7 @@
}
if query_iface_response.role == fidl_fuchsia_wlan_device::MacRole::Ap {
- match await!(wlan_ap_service_util::get_iface_ap_sme_proxy(
- &wlan_svc, iface
- )) {
+ match await!(wlan_ap_service_util::get_iface_ap_sme_proxy(&wlan_svc, iface)) {
Ok(ap_sme_proxy) => {
let mut wlan_ap_iface = WlanApIface::new(ap_sme_proxy);
wlan_ap_iface.ap_interface_status = true;
@@ -166,9 +164,8 @@
let mut wlan_client_results = WlanClientResultsPerAP::new();
- let scan_results_return = await!(wlan_service_util::perform_scan(
- &wlan_client_iface.sme_proxy
- ));
+ let scan_results_return =
+ await!(wlan_service_util::perform_scan(&wlan_client_iface.sme_proxy));
let scan_results = match scan_results_return {
Ok(scan_results) => scan_results,
@@ -179,10 +176,7 @@
}
};
- if scan_results
- .iter()
- .find(|&ap| ap.best_bss.ssid == target_ssid.to_vec())
- != None
+ if scan_results.iter().find(|&ap| ap.best_bss.ssid == target_ssid.to_vec()) != None
{
wlan_client_results.found_ap_in_scan = true;
}
@@ -226,9 +220,7 @@
test_pass = false;
}
- wlan_ap_iface
- .iface_client_results
- .insert(*client_iface_id, wlan_client_results);
+ wlan_ap_iface.iface_client_results.insert(*client_iface_id, wlan_client_results);
}
if wlan_ap_iface.ap_start_success == true {
@@ -287,10 +279,7 @@
impl WlanClientIface {
pub fn new(sme_proxy: fidl_sme::ClientSmeProxy) -> WlanClientIface {
- WlanClientIface {
- sme_proxy: sme_proxy,
- client_interface_status: false,
- }
+ WlanClientIface { sme_proxy: sme_proxy, client_interface_status: false }
}
}
diff --git a/bin/wlan/wlan-hw-sim/meta/wlan_hw_sim_bin_test.cmx b/bin/wlan/wlan-hw-sim/meta/wlan_hw_sim_bin_test.cmx
index a40a4cd..c773cdd 100644
--- a/bin/wlan/wlan-hw-sim/meta/wlan_hw_sim_bin_test.cmx
+++ b/bin/wlan/wlan-hw-sim/meta/wlan_hw_sim_bin_test.cmx
@@ -12,4 +12,4 @@
"fuchsia.wlan.device.service.DeviceService"
]
}
-}
\ No newline at end of file
+}
diff --git a/bin/wlan/wlan-hw-sim/src/ap.rs b/bin/wlan/wlan-hw-sim/src/ap.rs
index bb94d00..9cc59fb 100644
--- a/bin/wlan/wlan-hw-sim/src/ap.rs
+++ b/bin/wlan/wlan-hw-sim/src/ap.rs
@@ -6,10 +6,9 @@
pub mod tests {
use crate::{config, mac_frames, test_utils};
use {
- fidl_fuchsia_wlan_common as wlan_common,
- fidl, fidl_fuchsia_wlan_device as wlan_device,
- fidl_fuchsia_wlan_device_service as fidl_wlan_service,
- fidl_fuchsia_wlan_sme as fidl_sme, fidl_fuchsia_wlan_tap as wlantap, fuchsia_app as app,
+ fidl, fidl_fuchsia_wlan_common as wlan_common, fidl_fuchsia_wlan_device as wlan_device,
+ fidl_fuchsia_wlan_device_service as fidl_wlan_service, fidl_fuchsia_wlan_sme as fidl_sme,
+ fidl_fuchsia_wlan_tap as wlantap, fuchsia_app as app,
fuchsia_async::{self as fasync, temp::TempStreamExt, TimeoutExt},
fuchsia_zircon::{self as zx, prelude::*},
futures::channel::mpsc,
@@ -41,9 +40,7 @@
.expect("Failed to connect to wlan service");
let (watcher_proxy, watcher_server_end) =
fidl::endpoints::create_proxy().expect("fail to create fidl endpoints");
- wlan_service
- .watch_devices(watcher_server_end)
- .expect("wlan watch_devices call fails");
+ wlan_service.watch_devices(watcher_server_end).expect("wlan watch_devices call fails");
// Create wlantap PHY
let mut helper =
@@ -57,9 +54,7 @@
);
let sme_fut = get_ap_sme(&wlan_service, iface_id)
- .on_timeout(5.seconds().after_now(), || {
- panic!("timeout retrieving ap sme")
- });
+ .on_timeout(5.seconds().after_now(), || panic!("timeout retrieving ap sme"));
let sme = exec.run_singlethreaded(sme_fut);
// Stop AP in case it was already started
@@ -71,9 +66,8 @@
password: vec![],
channel: 11,
};
- let result_code = exec
- .run_singlethreaded(sme.start(&mut config))
- .expect("expect start ap result code");
+ let result_code =
+ exec.run_singlethreaded(sme.start(&mut config)).expect("expect start ap result code");
assert_eq!(result_code, fidl_sme::StartApResultCode::Success);
// (client->ap) send a mock auth req
@@ -108,10 +102,7 @@
let mut reader = Cursor::new(&args.packet.data);
let header = mac_frames::MgmtHeader::from_reader(&mut reader)
.expect("frame does not have valid mgmt header");
- assert_eq!(
- header.frame_control.typ(),
- mac_frames::FrameControlType::Mgmt as u16
- );
+ assert_eq!(header.frame_control.typ(), mac_frames::FrameControlType::Mgmt as u16);
assert_eq!(
header.frame_control.subtype(),
mac_frames::MgmtSubtype::Authentication as u16
@@ -147,10 +138,7 @@
let mut reader = Cursor::new(&args.packet.data);
let header = mac_frames::MgmtHeader::from_reader(&mut reader)
.expect("frame does not have valid mgmt header");
- assert_eq!(
- header.frame_control.typ(),
- mac_frames::FrameControlType::Mgmt as u16
- );
+ assert_eq!(header.frame_control.typ(), mac_frames::FrameControlType::Mgmt as u16);
if header.frame_control.subtype() == mac_frames::MgmtSubtype::Action as u16 {
return;
}
@@ -193,7 +181,8 @@
}
async fn get_ap_sme(
- wlan_service: &fidl_wlan_service::DeviceServiceProxy, iface_id: u16,
+ wlan_service: &fidl_wlan_service::DeviceServiceProxy,
+ iface_id: u16,
) -> fidl_sme::ApSmeProxy {
let (proxy, remote) =
fidl::endpoints::create_proxy().expect("fail to create fidl endpoints");
diff --git a/bin/wlan/wlan-hw-sim/src/config.rs b/bin/wlan/wlan-hw-sim/src/config.rs
index e0390d8..519e3ba 100644
--- a/bin/wlan/wlan-hw-sim/src/config.rs
+++ b/bin/wlan/wlan-hw-sim/src/config.rs
@@ -11,7 +11,8 @@
};
pub fn create_wlantap_config(
- hw_mac_address: [u8; 6], mac_role: wlan_device::MacRole,
+ hw_mac_address: [u8; 6],
+ mac_role: wlan_device::MacRole,
) -> wlantap::WlantapPhyConfig {
use fidl_fuchsia_wlan_device::{DriverFeature, SupportedPhy};
wlantap::WlantapPhyConfig {
diff --git a/bin/wlan/wlan-hw-sim/src/mac_frames.rs b/bin/wlan/wlan-hw-sim/src/mac_frames.rs
index 471dfa4..a3278b7 100644
--- a/bin/wlan/wlan-hw-sim/src/mac_frames.rs
+++ b/bin/wlan/wlan-hw-sim/src/mac_frames.rs
@@ -92,10 +92,7 @@
impl SeqControl {
#[cfg(test)]
fn decode(num: u16) -> Self {
- Self {
- frag_num: num & 0x0F,
- seq_num: num >> 4,
- }
+ Self { frag_num: num & 0x0F, seq_num: num >> 4 }
}
fn encode(&self) -> u16 {
self.frag_num | (self.seq_num << 4)
@@ -142,11 +139,8 @@
} else {
None
};
- let ht_control = if frame_control.htc_order() {
- Some(reader.read_u32::<LittleEndian>()?)
- } else {
- None
- };
+ let ht_control =
+ if frame_control.htc_order() { Some(reader.read_u32::<LittleEndian>()?) } else { None };
Ok(Self {
frame_control,
duration,
@@ -181,13 +175,7 @@
let mut oui = [0u8; 3];
reader.read(&mut oui)?;
let protocol_id = reader.read_u16::<LittleEndian>()?;
- Ok(Self {
- dsap,
- ssap,
- control,
- oui,
- protocol_id,
- })
+ Ok(Self { dsap, ssap, control, oui, protocol_id })
}
}
// IEEE Std 802.11-2016, 9.3.3.2
@@ -214,20 +202,9 @@
let mut addr3 = [0u8; 6];
reader.read(&mut addr3)?;
let seq_control = SeqControl::decode(reader.read_u16::<LittleEndian>()?);
- let ht_control = if frame_control.htc_order() {
- Some(reader.read_u32::<LittleEndian>()?)
- } else {
- None
- };
- Ok(Self {
- frame_control,
- duration,
- addr1,
- addr2,
- addr3,
- seq_control,
- ht_control,
- })
+ let ht_control =
+ if frame_control.htc_order() { Some(reader.read_u32::<LittleEndian>()?) } else { None };
+ Ok(Self { frame_control, duration, addr1, addr2, addr3, seq_control, ht_control })
}
}
@@ -252,11 +229,7 @@
let auth_algorithm_number = reader.read_u16::<LittleEndian>()?;
let auth_txn_seq_number = reader.read_u16::<LittleEndian>()?;
let status_code = reader.read_u16::<LittleEndian>()?;
- Ok(Self {
- auth_algorithm_number,
- auth_txn_seq_number,
- status_code,
- })
+ Ok(Self { auth_algorithm_number, auth_txn_seq_number, status_code })
}
}
@@ -273,11 +246,7 @@
let capability_info = CapabilityInfo(reader.read_u16::<LittleEndian>()?);
let status_code = reader.read_u16::<LittleEndian>()?;
let association_id = reader.read_u16::<LittleEndian>()?;
- Ok(Self {
- capability_info,
- status_code,
- association_id,
- })
+ Ok(Self { capability_info, status_code, association_id })
}
}
@@ -301,33 +270,36 @@
}
pub fn beacon(
- mut self, header: &MgmtHeader, beacon: &BeaconFields,
+ mut self,
+ header: &MgmtHeader,
+ beacon: &BeaconFields,
) -> io::Result<ElementWriter<W>> {
self.write_mgmt_header(header, MgmtSubtype::Beacon)?;
self.w.write_u64::<LittleEndian>(beacon.timestamp)?;
self.w.write_u16::<LittleEndian>(beacon.beacon_interval)?;
- self.w
- .write_u16::<LittleEndian>(beacon.capability_info.0 as u16)?;
+ self.w.write_u16::<LittleEndian>(beacon.capability_info.0 as u16)?;
Ok(ElementWriter { w: self.w })
}
pub fn authentication(
- mut self, header: &MgmtHeader, auth: &AuthenticationFields,
+ mut self,
+ header: &MgmtHeader,
+ auth: &AuthenticationFields,
) -> io::Result<ElementWriter<W>> {
self.write_mgmt_header(header, MgmtSubtype::Authentication)?;
- self.w
- .write_u16::<LittleEndian>(auth.auth_algorithm_number)?;
+ self.w.write_u16::<LittleEndian>(auth.auth_algorithm_number)?;
self.w.write_u16::<LittleEndian>(auth.auth_txn_seq_number)?;
self.w.write_u16::<LittleEndian>(auth.status_code)?;
Ok(ElementWriter { w: self.w })
}
pub fn association_response(
- mut self, header: &MgmtHeader, assoc: &AssociationResponseFields,
+ mut self,
+ header: &MgmtHeader,
+ assoc: &AssociationResponseFields,
) -> io::Result<ElementWriter<W>> {
self.write_mgmt_header(header, MgmtSubtype::AssociationResponse)?;
- self.w
- .write_u16::<LittleEndian>(assoc.capability_info.0 as u16)?;
+ self.w.write_u16::<LittleEndian>(assoc.capability_info.0 as u16)?;
self.w.write_u16::<LittleEndian>(assoc.status_code)?;
self.w.write_u16::<LittleEndian>(assoc.association_id)?;
Ok(ElementWriter { w: self.w })
@@ -343,8 +315,7 @@
self.w.write_all(&header.addr1)?;
self.w.write_all(&header.addr2)?;
self.w.write_all(&header.addr3)?;
- self.w
- .write_u16::<LittleEndian>(header.seq_control.encode())?;
+ self.w.write_u16::<LittleEndian>(header.seq_control.encode())?;
if let Some(ht_control) = header.ht_control {
self.w.write_u32::<LittleEndian>(ht_control)?;
}
@@ -353,7 +324,10 @@
#[cfg(test)]
pub fn data(
- mut self, data_header: &DataHeader, llc_header: &LlcHeader, payload: &[u8],
+ mut self,
+ data_header: &DataHeader,
+ llc_header: &LlcHeader,
+ payload: &[u8],
) -> io::Result<Self> {
self.write_data_header(data_header, DataSubtype::Data)?;
self.write_llc_header(llc_header)?;
@@ -372,8 +346,7 @@
self.w.write_all(&header.addr1)?;
self.w.write_all(&header.addr2)?;
self.w.write_all(&header.addr3)?;
- self.w
- .write_u16::<LittleEndian>(header.seq_control.encode())?;
+ self.w.write_u16::<LittleEndian>(header.seq_control.encode())?;
if let Some(addr4) = header.addr4 {
self.w.write_all(&addr4)?;
}
@@ -456,10 +429,7 @@
addr1: [0x01, 0x02, 0x03, 0x04, 0x05, 0x06],
addr2: [0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C],
addr3: [0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12],
- seq_control: SeqControl {
- frag_num: 5,
- seq_num: 0xABC,
- },
+ seq_control: SeqControl { frag_num: 5, seq_num: 0xABC },
ht_control: None,
},
&BeaconFields {
@@ -499,21 +469,12 @@
];
let hdr = MgmtHeader::from_reader(&mut bytes).expect("reading mgmt header");
assert_eq!(hdr.frame_control.typ(), FrameControlType::Mgmt as u16);
- assert_eq!(
- hdr.frame_control.subtype(),
- MgmtSubtype::Authentication as u16
- );
+ assert_eq!(hdr.frame_control.subtype(), MgmtSubtype::Authentication as u16);
assert_eq!(hdr.duration, 0x9876);
assert_eq!(hdr.addr1, [0x01, 0x02, 0x03, 0x04, 0x05, 0x06]);
assert_eq!(hdr.addr2, [0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C]);
assert_eq!(hdr.addr3, [0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12]);
- assert_eq!(
- hdr.seq_control,
- SeqControl {
- frag_num: 5,
- seq_num: 0xABC
- }
- );
+ assert_eq!(hdr.seq_control, SeqControl { frag_num: 5, seq_num: 0xABC });
assert_eq!(hdr.ht_control, None);
let body = AuthenticationFields::from_reader(&mut bytes).expect("reading auth fields");
@@ -532,10 +493,7 @@
addr1: [0x01, 0x02, 0x03, 0x04, 0x05, 0x06],
addr2: [0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C],
addr3: [0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12],
- seq_control: SeqControl {
- frag_num: 5,
- seq_num: 0xABC,
- },
+ seq_control: SeqControl { frag_num: 5, seq_num: 0xABC },
ht_control: None,
},
&AuthenticationFields {
@@ -570,21 +528,12 @@
];
let hdr = MgmtHeader::from_reader(&mut bytes).expect("reading mgmt header");
assert_eq!(hdr.frame_control.typ(), FrameControlType::Mgmt as u16);
- assert_eq!(
- hdr.frame_control.subtype(),
- MgmtSubtype::AssociationResponse as u16
- );
+ assert_eq!(hdr.frame_control.subtype(), MgmtSubtype::AssociationResponse as u16);
assert_eq!(hdr.duration, 0x8765);
assert_eq!(hdr.addr1, [0x01, 0x02, 0x03, 0x04, 0x05, 0x06]);
assert_eq!(hdr.addr2, [0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C]);
assert_eq!(hdr.addr3, [0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12]);
- assert_eq!(
- hdr.seq_control,
- SeqControl {
- frag_num: 6,
- seq_num: 0xDEF
- }
- );
+ assert_eq!(hdr.seq_control, SeqControl { frag_num: 6, seq_num: 0xDEF });
assert_eq!(hdr.ht_control, None);
let body = AssociationResponseFields::from_reader(&mut bytes).expect("reading assoc resp");
@@ -603,10 +552,7 @@
addr1: [0x01, 0x02, 0x03, 0x04, 0x05, 0x06],
addr2: [0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C],
addr3: [0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12],
- seq_control: SeqControl {
- frag_num: 6,
- seq_num: 0xDEF,
- },
+ seq_control: SeqControl { frag_num: 6, seq_num: 0xDEF },
ht_control: None,
},
&AssociationResponseFields {
@@ -645,14 +591,8 @@
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, // payload
] as &[u8];
let data_header = DataHeader::from_reader(&mut bytes).expect("reading data header");
- assert_eq!(
- data_header.frame_control.typ(),
- FrameControlType::Data as u16
- );
- assert_eq!(
- data_header.frame_control.subtype(),
- DataSubtype::Data as u16
- );
+ assert_eq!(data_header.frame_control.typ(), FrameControlType::Data as u16);
+ assert_eq!(data_header.frame_control.subtype(), DataSubtype::Data as u16);
assert_eq!(data_header.addr1, [0x65, 0x74, 0x68, 0x6e, 0x65, 0x74]);
assert_eq!(data_header.addr2, [0x67, 0x62, 0x6f, 0x6e, 0x69, 0x6b]);
assert_eq!(data_header.addr3, [0x62, 0x73, 0x73, 0x62, 0x73, 0x73]);
@@ -667,10 +607,7 @@
let mut payload = vec![];
let bytes_read = io::Read::read_to_end(&mut bytes, &mut payload).expect("reading payload");
assert_eq!(bytes_read, 15);
- assert_eq!(
- &payload[..],
- &[1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
- );
+ assert_eq!(&payload[..], &[1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
}
#[test]
@@ -683,10 +620,7 @@
addr1: [0x01, 0x02, 0x03, 0x04, 0x05, 0x06],
addr2: [0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C],
addr3: [0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12],
- seq_control: SeqControl {
- frag_num: 6,
- seq_num: 0xDEF,
- },
+ seq_control: SeqControl { frag_num: 6, seq_num: 0xDEF },
addr4: None,
qos_control: None,
ht_control: None,
diff --git a/bin/wlan/wlan-hw-sim/src/main.rs b/bin/wlan/wlan-hw-sim/src/main.rs
index 12f9c9a..3e4666e 100644
--- a/bin/wlan/wlan-hw-sim/src/main.rs
+++ b/bin/wlan/wlan-hw-sim/src/main.rs
@@ -8,8 +8,7 @@
use {
byteorder::{LittleEndian, ReadBytesExt},
- fidl_fuchsia_wlan_common as wlan_common,
- fidl_fuchsia_wlan_device as wlan_device,
+ fidl_fuchsia_wlan_common as wlan_common, fidl_fuchsia_wlan_device as wlan_device,
fidl_fuchsia_wlan_tap as wlantap, fuchsia_async as fasync,
fuchsia_zircon::prelude::*,
futures::prelude::*,
@@ -60,7 +59,10 @@
}
fn send_beacon(
- frame_buf: &mut Vec<u8>, channel: &wlan_common::WlanChan, bss_id: &[u8; 6], ssid: &[u8],
+ frame_buf: &mut Vec<u8>,
+ channel: &wlan_common::WlanChan,
+ bss_id: &[u8; 6],
+ ssid: &[u8],
proxy: &wlantap::WlantapPhyProxy,
) -> Result<(), failure::Error> {
frame_buf.clear();
@@ -72,10 +74,7 @@
addr1: mac_frames::BROADCAST_ADDR.clone(),
addr2: bss_id.clone(),
addr3: bss_id.clone(),
- seq_control: mac_frames::SeqControl {
- frag_num: 0,
- seq_num: 123,
- },
+ seq_control: mac_frames::SeqControl { frag_num: 0, seq_num: 123 },
ht_control: None,
},
&mac_frames::BeaconFields {
@@ -94,7 +93,9 @@
}
fn send_authentication(
- frame_buf: &mut Vec<u8>, channel: &wlan_common::WlanChan, bss_id: &[u8; 6],
+ frame_buf: &mut Vec<u8>,
+ channel: &wlan_common::WlanChan,
+ bss_id: &[u8; 6],
proxy: &wlantap::WlantapPhyProxy,
) -> Result<(), failure::Error> {
frame_buf.clear();
@@ -105,10 +106,7 @@
addr1: HW_MAC_ADDR,
addr2: bss_id.clone(),
addr3: bss_id.clone(),
- seq_control: mac_frames::SeqControl {
- frag_num: 0,
- seq_num: 123,
- },
+ seq_control: mac_frames::SeqControl { frag_num: 0, seq_num: 123 },
ht_control: None,
},
&mac_frames::AuthenticationFields {
@@ -124,37 +122,37 @@
}
fn send_association_response(
- frame_buf: &mut Vec<u8>, channel: &wlan_common::WlanChan, bss_id: &[u8; 6],
+ frame_buf: &mut Vec<u8>,
+ channel: &wlan_common::WlanChan,
+ bss_id: &[u8; 6],
proxy: &wlantap::WlantapPhyProxy,
) -> Result<(), failure::Error> {
frame_buf.clear();
let mut cap_info = mac_frames::CapabilityInfo(0);
cap_info.set_ess(true);
cap_info.set_short_preamble(true);
- mac_frames::MacFrameWriter::<&mut Vec<u8>>::new(frame_buf).association_response(
- &mac_frames::MgmtHeader {
- frame_control: mac_frames::FrameControl(0), // will be filled automatically
- duration: 0,
- addr1: HW_MAC_ADDR,
- addr2: bss_id.clone(),
- addr3: bss_id.clone(),
- seq_control: mac_frames::SeqControl {
- frag_num: 0,
- seq_num: 123,
+ mac_frames::MacFrameWriter::<&mut Vec<u8>>::new(frame_buf)
+ .association_response(
+ &mac_frames::MgmtHeader {
+ frame_control: mac_frames::FrameControl(0), // will be filled automatically
+ duration: 0,
+ addr1: HW_MAC_ADDR,
+ addr2: bss_id.clone(),
+ addr3: bss_id.clone(),
+ seq_control: mac_frames::SeqControl { frag_num: 0, seq_num: 123 },
+ ht_control: None,
},
- ht_control: None,
- },
- &mac_frames::AssociationResponseFields {
- capability_info: cap_info,
- status_code: 0, // Success
- association_id: 2, // Can be any
- },
- )?
- // These elements will be captured in assoc_ctx to initialize Minstrel
- // tx_vec_idx: 129 130 131 132
- .supported_rates(&[0x82, 0x84, 0x8b, 0x0c, 0x12, 0x96, 0x18, 0x24])?
- // tx_vec_idx: 133 134 (basic)135 136
- .extended_supported_rates(&[48, 72, 128 + 96, 108])?;
+ &mac_frames::AssociationResponseFields {
+ capability_info: cap_info,
+ status_code: 0, // Success
+ association_id: 2, // Can be any
+ },
+ )?
+ // These elements will be captured in assoc_ctx to initialize Minstrel
+ // tx_vec_idx: 129 130 131 132
+ .supported_rates(&[0x82, 0x84, 0x8b, 0x0c, 0x12, 0x96, 0x18, 0x24])?
+ // tx_vec_idx: 133 134 (basic)135 136
+ .extended_supported_rates(&[48, 72, 128 + 96, 108])?;
let rx_info = &mut create_rx_info(channel);
proxy.rx(0, &mut frame_buf.iter().cloned(), rx_info)?;
@@ -212,9 +210,7 @@
let mut exec = fasync::Executor::new().expect("error creating executor");
let wlantap = Wlantap::open().expect("error with Wlantap::open()");
let state = Arc::new(Mutex::new(State::new()));
- let proxy = wlantap
- .create_phy(create_wlantap_config())
- .expect("error creating wlantap config");
+ let proxy = wlantap.create_phy(create_wlantap_config()).expect("error creating wlantap config");
let event_listener = event_listener(state.clone(), proxy.clone());
let beacon_timer = beacon_sender(state.clone(), proxy.clone());
@@ -285,11 +281,8 @@
const BSS_BAZ: [u8; 6] = [0x62, 0x73, 0x73, 0x62, 0x61, 0x7a];
const SSID_BAZ: &[u8] = b"baz";
- const CHANNEL: wlan_common::WlanChan = wlan_common::WlanChan {
- primary: 6,
- secondary80: 0,
- cbw: wlan_common::Cbw::Cbw20,
- };
+ const CHANNEL: wlan_common::WlanChan =
+ wlan_common::WlanChan { primary: 6, secondary80: 0, cbw: wlan_common::Cbw::Cbw20 };
// Temporary workaround to run tests synchronously. This is because wlan service only works with
// one PHY, so having tests with multiple PHYs running in parallel make them flaky.
@@ -326,11 +319,7 @@
break;
}
let slept = retry.sleep_unless_timed_out();
- assert!(
- slept,
- "No ethernet client with mac_addr {:?} found in time",
- &HW_MAC_ADDR
- );
+ assert!(slept, "No ethernet client with mac_addr {:?} found in time", &HW_MAC_ADDR);
}
let wlan_service = app::client::connect_to_service::<fidl_wlan_service::WlanMarker>()
.expect("connecting to wlan service");
@@ -341,8 +330,7 @@
let mut exec = fasync::Executor::new().expect("Failed to create an executor");
let wlan_service = app::client::connect_to_service::<fidl_wlan_service::WlanMarker>()
.expect("Failed to connect to wlan service");
- exec.run_singlethreaded(wlan_service.clear_saved_networks())
- .expect("Clearing SSID");
+ exec.run_singlethreaded(wlan_service.clear_saved_networks()).expect("Clearing SSID");
let mut retry = test_utils::RetryWithBackoff::new(5.seconds());
loop {
@@ -381,18 +369,9 @@
.collect();
aps.sort();
let mut expected_aps = [
- (
- String::from_utf8_lossy(SSID_FOO).to_string(),
- BSS_FOO.to_vec(),
- ),
- (
- String::from_utf8_lossy(SSID_BAR).to_string(),
- BSS_BAR.to_vec(),
- ),
- (
- String::from_utf8_lossy(SSID_BAZ).to_string(),
- BSS_BAZ.to_vec(),
- ),
+ (String::from_utf8_lossy(SSID_FOO).to_string(), BSS_FOO.to_vec()),
+ (String::from_utf8_lossy(SSID_BAR).to_string(), BSS_BAR.to_vec()),
+ (String::from_utf8_lossy(SSID_BAZ).to_string(), BSS_BAZ.to_vec()),
];
expected_aps.sort();
assert_eq!(&expected_aps, &aps[..]);
@@ -407,14 +386,7 @@
let proxy = helper.proxy();
loop_until_iface_is_found(&mut exec, &wlan_service, &mut helper);
- connect(
- &mut exec,
- &wlan_service,
- &proxy,
- &mut helper,
- SSID_FOO,
- &BSS_FOO,
- );
+ connect(&mut exec, &wlan_service, &proxy, &mut helper, SSID_FOO, &BSS_FOO);
let status = status(&mut exec, &wlan_service, &mut helper);
assert_eq!(status.error.code, fidl_wlan_service::ErrCode::Ok);
@@ -428,7 +400,8 @@
}
fn loop_until_iface_is_found(
- exec: &mut fasync::Executor, wlan_service: &fidl_wlan_service::WlanProxy,
+ exec: &mut fasync::Executor,
+ wlan_service: &fidl_wlan_service::WlanProxy,
helper: &mut test_utils::TestHelper,
) {
let mut retry = test_utils::RetryWithBackoff::new(5.seconds());
@@ -444,23 +417,20 @@
}
fn status(
- exec: &mut fasync::Executor, wlan_service: &fidl_wlan_service::WlanProxy,
+ exec: &mut fasync::Executor,
+ wlan_service: &fidl_wlan_service::WlanProxy,
helper: &mut test_utils::TestHelper,
) -> fidl_wlan_service::WlanStatus {
helper
- .run(
- exec,
- 1.seconds(),
- "status request",
- |_| {},
- wlan_service.status(),
- )
+ .run(exec, 1.seconds(), "status request", |_| {}, wlan_service.status())
.expect("expect wlan status")
}
fn scan(
- exec: &mut fasync::Executor, wlan_service: &fidl_wlan_service::WlanProxy,
- phy: &wlantap::WlantapPhyProxy, helper: &mut test_utils::TestHelper,
+ exec: &mut fasync::Executor,
+ wlan_service: &fidl_wlan_service::WlanProxy,
+ phy: &wlantap::WlantapPhyProxy,
+ helper: &mut test_utils::TestHelper,
) -> fidl_wlan_service::ScanResult {
let mut wlanstack_retry = test_utils::RetryWithBackoff::new(5.seconds());
loop {
@@ -507,8 +477,11 @@
}
fn connect(
- exec: &mut fasync::Executor, wlan_service: &fidl_wlan_service::WlanProxy,
- phy: &wlantap::WlantapPhyProxy, helper: &mut test_utils::TestHelper, ssid: &[u8],
+ exec: &mut fasync::Executor,
+ wlan_service: &fidl_wlan_service::WlanProxy,
+ phy: &wlantap::WlantapPhyProxy,
+ helper: &mut test_utils::TestHelper,
+ ssid: &[u8],
bssid: &[u8; 6],
) {
let mut connect_config = create_connect_config(ssid, bssid);
@@ -517,27 +490,20 @@
.run(
exec,
10.seconds(),
- &format!(
- "connect to {}({:2x?})",
- String::from_utf8_lossy(ssid),
- bssid
- ),
+ &format!("connect to {}({:2x?})", String::from_utf8_lossy(ssid), bssid),
|event| {
handle_connect_events(event, &phy, ssid, bssid);
},
connect_fut,
)
.unwrap();
- assert_eq!(
- error.code,
- fidl_wlan_service::ErrCode::Ok,
- "connect failed: {:?}",
- error
- );
+ assert_eq!(error.code, fidl_wlan_service::ErrCode::Ok, "connect failed: {:?}", error);
}
fn handle_connect_events(
- event: wlantap::WlantapPhyEvent, phy: &wlantap::WlantapPhyProxy, ssid: &[u8],
+ event: wlantap::WlantapPhyEvent,
+ phy: &wlantap::WlantapPhyProxy,
+ ssid: &[u8],
bssid: &[u8; 6],
) {
match event {
@@ -573,23 +539,13 @@
.expect("Error connecting to wlan service");
let mut helper = test_utils::TestHelper::begin_test(
&mut exec,
- wlantap::WlantapPhyConfig {
- quiet: true,
- ..create_wlantap_config()
- },
+ wlantap::WlantapPhyConfig { quiet: true, ..create_wlantap_config() },
);
loop_until_iface_is_found(&mut exec, &wlan_service, &mut helper);
let phy = helper.proxy();
- connect(
- &mut exec,
- &wlan_service,
- &phy,
- &mut helper,
- SSID_MINSTREL,
- &BSS_MINSTL,
- );
+ connect(&mut exec, &wlan_service, &phy, &mut helper, SSID_MINSTREL, &BSS_MINSTL);
let beacon_sender_fut = beacon_sender(&BSS_MINSTL, SSID_MINSTREL, &phy).fuse();
pin_mut!(beacon_sender_fut);
@@ -621,11 +577,8 @@
}
// safe to unwrap below because there are at least 7 entries
let max_key = hm.keys().max_by_key(|k| hm[&k]).unwrap();
- let second_largest = hm
- .iter()
- .map(|(k, v)| if k == max_key { 0 } else { *v })
- .max()
- .unwrap();
+ let second_largest =
+ hm.iter().map(|(k, v)| if k == max_key { 0 } else { *v }).max().unwrap();
let max_val = hm[&max_key];
if max_val % 100 == 0 {
println!("{:?}", hm);
@@ -677,8 +630,13 @@
}
fn handle_rate_selection_event<F, G>(
- event: wlantap::WlantapPhyEvent, phy: &wlantap::WlantapPhyProxy, bssid: &[u8; 6],
- hm: &mut HashMap<u16, u64>, should_succeed: F, is_done: G, mut sender: mpsc::Sender<()>,
+ event: wlantap::WlantapPhyEvent,
+ phy: &wlantap::WlantapPhyProxy,
+ bssid: &[u8; 6],
+ hm: &mut HashMap<u16, u64>,
+ should_succeed: F,
+ is_done: G,
+ mut sender: mpsc::Sender<()>,
) where
F: Fn(u16) -> bool,
G: Fn(&HashMap<u16, u64>) -> bool,
@@ -693,11 +651,7 @@
let count = hm.entry(tx_vec_idx).or_insert(0);
*count += 1;
if *count == 1 {
- println!(
- "new tx_vec_idx: {} at #{}",
- tx_vec_idx,
- hm.values().sum::<u64>()
- );
+ println!("new tx_vec_idx: {} at #{}", tx_vec_idx, hm.values().sum::<u64>());
}
if is_done(hm) {
sender.try_send(()).expect("Indicating test successful");
@@ -745,14 +699,14 @@
}
fn create_wlan_tx_status_entry(tx_vec_idx: u16) -> wlantap::WlanTxStatusEntry {
- fidl_fuchsia_wlan_tap::WlanTxStatusEntry {
- tx_vec_idx: tx_vec_idx,
- attempts: 1,
- }
+ fidl_fuchsia_wlan_tap::WlanTxStatusEntry { tx_vec_idx: tx_vec_idx, attempts: 1 }
}
fn send_tx_status_report(
- bssid: [u8; 6], tx_vec_idx: u16, is_successful: bool, proxy: &wlantap::WlantapPhyProxy,
+ bssid: [u8; 6],
+ tx_vec_idx: u16,
+ is_successful: bool,
+ proxy: &wlantap::WlantapPhyProxy,
) -> Result<(), failure::Error> {
use fidl_fuchsia_wlan_tap::WlanTxStatus;
@@ -813,7 +767,9 @@
}
async fn beacon_sender<'a>(
- bssid: &'a [u8; 6], ssid: &'a [u8], phy: &'a wlantap::WlantapPhyProxy,
+ bssid: &'a [u8; 6],
+ ssid: &'a [u8],
+ phy: &'a wlantap::WlantapPhyProxy,
) -> Result<(), failure::Error> {
let mut beacon_timer_stream = fasync::Interval::new(102_400_000.nanos());
while let Some(_) = await!(beacon_timer_stream.next()) {
@@ -835,14 +791,7 @@
loop_until_iface_is_found(&mut exec, &wlan_service, &mut helper);
let proxy = helper.proxy();
- connect(
- &mut exec,
- &wlan_service,
- &proxy,
- &mut helper,
- SSID_ETHERNET,
- &BSS_ETHNET,
- );
+ connect(&mut exec, &wlan_service, &proxy, &mut helper, SSID_ETHERNET, &BSS_ETHNET);
let mut client = exec
.run_singlethreaded(create_eth_client(&HW_MAC_ADDR))
@@ -853,7 +802,8 @@
}
fn verify_tx_and_rx(
- client: &mut ethernet::Client, exec: &mut fasync::Executor,
+ client: &mut ethernet::Client,
+ exec: &mut fasync::Executor,
helper: &mut test_utils::TestHelper,
) {
let mut buf: Vec<u8> = Vec::new();
@@ -891,7 +841,8 @@
}
async fn send_and_receive<'a>(
- client: &'a mut ethernet::Client, buf: &'a Vec<u8>,
+ client: &'a mut ethernet::Client,
+ buf: &'a Vec<u8>,
) -> Result<(eth_frames::EthHeader, Vec<u8>), failure::Error> {
use fidl_fuchsia_hardware_ethernet_ext::EthernetQueueFlags;
let mut client_stream = client.get_stream();
@@ -916,7 +867,9 @@
}
fn handle_eth_tx(
- event: wlantap::WlantapPhyEvent, actual: &mut Vec<u8>, phy: &wlantap::WlantapPhyProxy,
+ event: wlantap::WlantapPhyEvent,
+ actual: &mut Vec<u8>,
+ phy: &wlantap::WlantapPhyProxy,
) {
if let wlantap::WlantapPhyEvent::Tx { args } = event {
let frame_ctrl = get_frame_ctrl(&args.packet.data);
@@ -939,7 +892,10 @@
}
fn rx_wlan_data_frame(
- addr1: &[u8; 6], addr2: &[u8; 6], addr3: &[u8; 6], payload: &[u8],
+ addr1: &[u8; 6],
+ addr2: &[u8; 6],
+ addr3: &[u8; 6],
+ payload: &[u8],
phy: &wlantap::WlantapPhyProxy,
) -> Result<(), failure::Error> {
let mut buf: Vec<u8> = vec![];
@@ -950,10 +906,7 @@
addr1: addr1.clone(),
addr2: addr2.clone(),
addr3: addr3.clone(),
- seq_control: mac_frames::SeqControl {
- frag_num: 0,
- seq_num: 3,
- },
+ seq_control: mac_frames::SeqControl { frag_num: 0, seq_num: 3 },
addr4: None,
qos_control: None,
ht_control: None,
diff --git a/bin/wlan/wlan-hw-sim/src/test_utils.rs b/bin/wlan/wlan-hw-sim/src/test_utils.rs
index 3358f9e..3f42262 100644
--- a/bin/wlan/wlan-hw-sim/src/test_utils.rs
+++ b/bin/wlan/wlan-hw-sim/src/test_utils.rs
@@ -64,15 +64,9 @@
impl TestHelper {
pub fn begin_test(exec: &mut fasync::Executor, config: wlantap::WlantapPhyConfig) -> Self {
let wlantap = Wlantap::open().expect("Failed to open wlantapctl");
- let proxy = wlantap
- .create_phy(config)
- .expect("Failed to create wlantap PHY");
+ let proxy = wlantap.create_phy(config).expect("Failed to create wlantap PHY");
let event_stream = Some(proxy.take_event_stream());
- let mut helper = TestHelper {
- _wlantap: wlantap,
- proxy: Arc::new(proxy),
- event_stream,
- };
+ let mut helper = TestHelper { _wlantap: wlantap, proxy: Arc::new(proxy), event_stream };
helper.wait_for_wlanmac_start(exec);
helper
}
@@ -99,8 +93,12 @@
}
pub fn run<T, E, F, H>(
- &mut self, exec: &mut fasync::Executor, timeout: zx::Duration, context: &str,
- event_handler: H, future: F,
+ &mut self,
+ exec: &mut fasync::Executor,
+ timeout: zx::Duration,
+ context: &str,
+ event_handler: H,
+ future: F,
) -> Result<T, E>
where
H: FnMut(wlantap::WlantapPhyEvent),
@@ -112,9 +110,7 @@
event_handler,
main_future: future,
}
- .on_timeout(timeout.after_now(), || {
- panic!("Did not complete in time: {}", context)
- }),
+ .on_timeout(timeout.after_now(), || panic!("Did not complete in time: {}", context)),
);
match res {
Ok((item, stream)) => {
diff --git a/bin/wlan/wlan-smoke-test/src/main.rs b/bin/wlan/wlan-smoke-test/src/main.rs
index 0f6b7f1..cf0e3ee 100644
--- a/bin/wlan/wlan-smoke-test/src/main.rs
+++ b/bin/wlan/wlan-smoke-test/src/main.rs
@@ -11,8 +11,8 @@
mod opts;
-use connectivity_testing::wlan_service_util;
use crate::opts::Opt;
+use connectivity_testing::wlan_service_util;
use failure::{bail, Error, ResultExt};
use fidl_fuchsia_net_oldhttp::{self as http, HttpServiceProxy};
use fidl_fuchsia_net_stack::{self as netstack, StackMarker, StackProxy};
@@ -107,7 +107,7 @@
wlan_iface.scan_found_target_ssid = true;
}
}
- },
+ }
_ => println!("scan failed"),
};
@@ -140,14 +140,11 @@
while dhcp_check_attempts < 3 && !wlan_iface.dhcp_success {
// check if there is a non-zero ip addr as a first check for dhcp success
- let ip_addrs = match await!(get_ip_addrs_for_wlan_iface(
- &wlan_svc,
- &network_svc,
- *iface_id
- )) {
- Ok(result) => result,
- Err(_) => continue,
- };
+ let ip_addrs =
+ match await!(get_ip_addrs_for_wlan_iface(&wlan_svc, &network_svc, *iface_id)) {
+ Ok(result) => result,
+ Err(_) => continue,
+ };
if check_dhcp_complete(ip_addrs) {
wlan_iface.dhcp_success = true;
} else {
@@ -159,9 +156,7 @@
// after testing, check if we need to disconnect
if requires_disconnect {
- match await!(wlan_service_util::disconnect_from_network(
- &wlan_iface.sme_proxy
- )) {
+ match await!(wlan_service_util::disconnect_from_network(&wlan_iface.sme_proxy)) {
Err(_) => wlan_iface.disconnect_success = false,
_ => wlan_iface.disconnect_success = true,
};
@@ -250,7 +245,8 @@
impl WlanIface {
pub fn new(
- sme_proxy: fidl_sme::ClientSmeProxy, status: fidl_sme::ClientStatusResponse,
+ sme_proxy: fidl_sme::ClientSmeProxy,
+ status: fidl_sme::ClientStatusResponse,
) -> WlanIface {
WlanIface {
sme_proxy: sme_proxy,
@@ -270,7 +266,9 @@
}
fn is_connect_to_target_network_needed<T: AsRef<[u8]>>(
- stay_connected: bool, target_ssid: T, status: &fidl_sme::ClientStatusResponse,
+ stay_connected: bool,
+ target_ssid: T,
+ status: &fidl_sme::ClientStatusResponse,
) -> bool {
if !stay_connected {
// doesn't matter if we are connected, we will force a reconnection
@@ -297,7 +295,8 @@
}
async fn fetch_and_discard_url(
- http_service: HttpServiceProxy, mut url_request: http::UrlRequest,
+ http_service: HttpServiceProxy,
+ mut url_request: http::UrlRequest,
) -> Result<(), Error> {
// Create a UrlLoader instance
let (s, p) = zx::Channel::create().context("failed to create zx channel")?;
@@ -310,11 +309,7 @@
let response = await!(loader_proxy.start(&mut url_request))?;
if let Some(e) = response.error {
- bail!(
- "UrlLoaderProxy error - code:{} ({})",
- e.code,
- e.description.unwrap_or("".into())
- )
+ bail!("UrlLoaderProxy error - code:{} ({})", e.code, e.description.unwrap_or("".into()))
}
let mut socket = match response.body.map(|x| *x) {
@@ -331,7 +326,9 @@
}
async fn get_ip_addrs_for_wlan_iface<'a>(
- wlan_svc: &'a DeviceServiceProxy, network_svc: &'a StackProxy, wlan_iface_id: u16,
+ wlan_svc: &'a DeviceServiceProxy,
+ network_svc: &'a StackProxy,
+ wlan_iface_id: u16,
) -> Result<Vec<netstack::InterfaceAddress>, Error> {
// temporary implementation for getting the ip addrs for a wlan iface. A more robust
// lookup will be designed and implemented in the future (TODO: <bug already filed?>)
diff --git a/bin/wlan/wlan-stress-test/BUILD.gn b/bin/wlan/wlan-stress-test/BUILD.gn
index d802389..9d2356c 100644
--- a/bin/wlan/wlan-stress-test/BUILD.gn
+++ b/bin/wlan/wlan-stress-test/BUILD.gn
@@ -2,18 +2,18 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-import("//build/rust/rustc_binary.gni")
import("//build/package.gni")
+import("//build/rust/rustc_binary.gni")
rustc_binary("bin") {
name = "wlan_stress_test"
edition = "2018"
deps = [
+ "//garnet/lib/rust/connectivity-testing:connectivity-testing",
"//garnet/lib/wlan/fidl:fidl-rustc",
"//garnet/lib/wlan/fidl:service-rustc",
"//garnet/lib/wlan/fidl:sme-rustc",
- "//garnet/lib/rust/connectivity-testing:connectivity-testing",
"//garnet/public/lib/fidl/rust/fidl",
"//garnet/public/rust/fuchsia-app",
"//garnet/public/rust/fuchsia-async",
@@ -29,7 +29,6 @@
}
package("wlan-stress-test") {
-
deps = [
":bin",
]
diff --git a/bin/wlan/wlan-stress-test/meta/wlan-stress-test.cmx b/bin/wlan/wlan-stress-test/meta/wlan-stress-test.cmx
index d67db41..1b361e0 100644
--- a/bin/wlan/wlan-stress-test/meta/wlan-stress-test.cmx
+++ b/bin/wlan/wlan-stress-test/meta/wlan-stress-test.cmx
@@ -3,8 +3,12 @@
"binary": "bin/app"
},
"sandbox": {
- "features": [ "persistent-storage" ],
- "services": [ "fuchsia.wlan.device.service.DeviceService",
- "fuchsia.logger.LogSink" ]
+ "features": [
+ "persistent-storage"
+ ],
+ "services": [
+ "fuchsia.wlan.device.service.DeviceService",
+ "fuchsia.logger.LogSink"
+ ]
}
}
diff --git a/bin/wlan/wlan-stress-test/src/main.rs b/bin/wlan/wlan-stress-test/src/main.rs
index 84f88b5..fe81cac 100644
--- a/bin/wlan/wlan-stress-test/src/main.rs
+++ b/bin/wlan/wlan-stress-test/src/main.rs
@@ -137,9 +137,8 @@
if opt.disconnect_test_enabled {
let start = Instant::now();
- let result = await!(wlan_service_util::disconnect_from_network(
- &wlaniface.sme_proxy
- ));
+ let result =
+ await!(wlan_service_util::disconnect_from_network(&wlaniface.sme_proxy));
match result {
Ok(()) => {
total_disconnect_time_ms +=
@@ -246,10 +245,7 @@
impl WlanIface {
pub fn new(sme_proxy: fidl_sme::ClientSmeProxy, report: TestReport) -> WlanIface {
- WlanIface {
- sme_proxy: sme_proxy,
- report: report,
- }
+ WlanIface { sme_proxy: sme_proxy, report: report }
}
}
diff --git a/bin/wlan/wlancfg/src/client.rs b/bin/wlan/wlancfg/src/client.rs
index d3f4a46..03be39f 100644
--- a/bin/wlan/wlancfg/src/client.rs
+++ b/bin/wlan/wlancfg/src/client.rs
@@ -59,7 +59,9 @@
}
pub fn new_client(
- iface_id: u16, sme: fidl_sme::ClientSmeProxy, ess_store: Arc<KnownEssStore>,
+ iface_id: u16,
+ sme: fidl_sme::ClientSmeProxy,
+ ess_store: Arc<KnownEssStore>,
) -> (Client, impl Future<Output = ()>) {
let (req_sender, req_receiver) = mpsc::unbounded();
let sme_event_stream = sme.take_event_stream();
@@ -79,10 +81,11 @@
}
async fn serve(
- iface_id: u16, services: Services, sme_event_stream: fidl_sme::ClientSmeEventStream,
+ iface_id: u16,
+ services: Services,
+ sme_event_stream: fidl_sme::ClientSmeEventStream,
req_stream: mpsc::UnboundedReceiver<ManualRequest>,
-)
-{
+) {
let state_machine = auto_connect_state(services, req_stream.into_future()).into_state_machine();
let removal_watcher = sme_event_stream.map_ok(|_| ()).try_collect::<()>();
select! {
@@ -100,7 +103,8 @@
}
async fn auto_connect_state(
- services: Services, mut next_req: NextReqFut,
+ services: Services,
+ mut next_req: NextReqFut,
) -> Result<State, failure::Error> {
println!("wlancfg: Starting auto-connect loop");
let auto_connected = auto_connect(&services);
@@ -117,10 +121,10 @@
}
fn handle_manual_request(
- services: Services, req: Option<ManualRequest>,
+ services: Services,
+ req: Option<ManualRequest>,
req_stream: mpsc::UnboundedReceiver<ManualRequest>,
-) -> Result<State, failure::Error>
-{
+) -> Result<State, failure::Error> {
match req {
Some(ManualRequest::Connect(req)) => {
Ok(manual_connect_state(services, req_stream.into_future(), req).into_state())
@@ -164,7 +168,9 @@
}
async fn connect_to_known_network(
- sme: &fidl_sme::ClientSmeProxy, ssid: Vec<u8>, ess: KnownEss,
+ sme: &fidl_sme::ClientSmeProxy,
+ ssid: Vec<u8>,
+ ess: KnownEss,
) -> Result<bool, failure::Error> {
let ssid_str = String::from_utf8_lossy(&ssid).into_owned();
println!("wlancfg: Auto-connecting to '{}'", ssid_str);
@@ -182,7 +188,9 @@
}
async fn manual_connect_state(
- services: Services, mut next_req: NextReqFut, req: ConnectRequest,
+ services: Services,
+ mut next_req: NextReqFut,
+ req: ConnectRequest,
) -> Result<State, failure::Error> {
println!(
"wlancfg: Connecting to '{}' because of a manual request from the user",
@@ -232,7 +240,8 @@
}
async fn connected_state(
- services: Services, mut next_req: NextReqFut,
+ services: Services,
+ mut next_req: NextReqFut,
) -> Result<State, failure::Error> {
let disconnected = wait_for_disconnection(services.clone());
pin_mut!(disconnected);
@@ -258,7 +267,9 @@
}
async fn disconnected_state(
- responder: oneshot::Sender<()>, services: Services, mut next_req: NextReqFut,
+ responder: oneshot::Sender<()>,
+ services: Services,
+ mut next_req: NextReqFut,
) -> Result<State, failure::Error> {
// First, ask the SME to disconnect and wait for its response.
// In the meantime, also listen to user requests.
@@ -323,7 +334,9 @@
}
fn start_connect_txn(
- sme: &fidl_sme::ClientSmeProxy, ssid: &[u8], password: &[u8],
+ sme: &fidl_sme::ClientSmeProxy,
+ ssid: &[u8],
+ password: &[u8],
) -> Result<fidl_sme::ConnectTransactionProxy, failure::Error> {
let (connect_txn, remote) = create_proxy()?;
let mut req = fidl_sme::ConnectRequest {
@@ -909,7 +922,8 @@
}
fn send_manual_connect_request(
- client: &Client, ssid: &[u8],
+ client: &Client,
+ ssid: &[u8],
) -> oneshot::Receiver<fidl_sme::ConnectResultCode> {
let (responder, receiver) = oneshot::channel();
client
@@ -923,7 +937,8 @@
}
fn poll_sme_req(
- exec: &mut fasync::Executor, next_sme_req: &mut StreamFuture<ClientSmeRequestStream>,
+ exec: &mut fasync::Executor,
+ next_sme_req: &mut StreamFuture<ClientSmeRequestStream>,
) -> Poll<ClientSmeRequest> {
exec.run_until_stalled(next_sme_req).map(|(req, stream)| {
*next_sme_req = stream.into_future();
@@ -933,10 +948,10 @@
}
fn send_scan_results(
- exec: &mut fasync::Executor, next_sme_req: &mut StreamFuture<ClientSmeRequestStream>,
+ exec: &mut fasync::Executor,
+ next_sme_req: &mut StreamFuture<ClientSmeRequestStream>,
ssids: &[&[u8]],
- )
- {
+ ) {
let txn = match poll_sme_req(exec, next_sme_req) {
Poll::Ready(ClientSmeRequest::Scan { txn, .. }) => txn,
Poll::Pending => panic!("expected a request to be available"),
@@ -952,10 +967,11 @@
}
fn send_sme_status(
- exec: &mut fasync::Executor, next_sme_req: &mut StreamFuture<ClientSmeRequestStream>,
- connected_to: Option<Box<fidl_sme::BssInfo>>, connecting_to_ssid: Vec<u8>,
- )
- {
+ exec: &mut fasync::Executor,
+ next_sme_req: &mut StreamFuture<ClientSmeRequestStream>,
+ connected_to: Option<Box<fidl_sme::BssInfo>>,
+ connecting_to_ssid: Vec<u8>,
+ ) {
let responder = match poll_sme_req(exec, next_sme_req) {
Poll::Ready(ClientSmeRequest::Status { responder }) => responder,
Poll::Pending => panic!("expected a request to be available"),
@@ -966,7 +982,8 @@
}
fn send_default_sme_status(
- exec: &mut fasync::Executor, next_sme_req: &mut StreamFuture<ClientSmeRequestStream>,
+ exec: &mut fasync::Executor,
+ next_sme_req: &mut StreamFuture<ClientSmeRequestStream>,
) {
let ssid = b"foo";
let bss_info = bss_info(&ssid[..]);
@@ -974,7 +991,8 @@
}
fn expect_status_req_to_sme(
- exec: &mut fasync::Executor, next_sme_req: &mut StreamFuture<ClientSmeRequestStream>,
+ exec: &mut fasync::Executor,
+ next_sme_req: &mut StreamFuture<ClientSmeRequestStream>,
) {
match poll_sme_req(exec, next_sme_req) {
Poll::Ready(ClientSmeRequest::Status { .. }) => (),
@@ -983,10 +1001,12 @@
}
fn exchange_connect_with_sme(
- exec: &mut fasync::Executor, next_sme_req: &mut StreamFuture<ClientSmeRequestStream>,
- expected_ssid: &[u8], expected_password: &[u8], code: fidl_sme::ConnectResultCode,
- )
- {
+ exec: &mut fasync::Executor,
+ next_sme_req: &mut StreamFuture<ClientSmeRequestStream>,
+ expected_ssid: &[u8],
+ expected_password: &[u8],
+ code: fidl_sme::ConnectResultCode,
+ ) {
let txn = expect_connect_req_to_sme(exec, next_sme_req, expected_ssid, expected_password);
txn.control_handle()
.send_on_finished(code)
@@ -994,10 +1014,11 @@
}
fn expect_connect_req_to_sme(
- exec: &mut fasync::Executor, next_sme_req: &mut StreamFuture<ClientSmeRequestStream>,
- expected_ssid: &[u8], expected_password: &[u8],
- ) -> fidl_sme::ConnectTransactionRequestStream
- {
+ exec: &mut fasync::Executor,
+ next_sme_req: &mut StreamFuture<ClientSmeRequestStream>,
+ expected_ssid: &[u8],
+ expected_password: &[u8],
+ ) -> fidl_sme::ConnectTransactionRequestStream {
match poll_sme_req(exec, next_sme_req) {
Poll::Ready(ClientSmeRequest::Connect { req, txn, .. }) => {
assert_eq!(expected_ssid, &req.ssid[..]);
@@ -1011,14 +1032,16 @@
}
fn exchange_disconnect_with_sme(
- exec: &mut fasync::Executor, next_sme_req: &mut StreamFuture<ClientSmeRequestStream>,
+ exec: &mut fasync::Executor,
+ next_sme_req: &mut StreamFuture<ClientSmeRequestStream>,
) {
let responder = expect_disconnect_req_to_sme(exec, next_sme_req);
responder.send().expect("failed to respond to Disconnect request");
}
fn expect_disconnect_req_to_sme(
- exec: &mut fasync::Executor, next_sme_req: &mut StreamFuture<ClientSmeRequestStream>,
+ exec: &mut fasync::Executor,
+ next_sme_req: &mut StreamFuture<ClientSmeRequestStream>,
) -> fidl_sme::ClientSmeDisconnectResponder {
match poll_sme_req(exec, next_sme_req) {
Poll::Ready(ClientSmeRequest::Disconnect { responder }) => responder,
diff --git a/bin/wlan/wlancfg/src/device.rs b/bin/wlan/wlancfg/src/device.rs
index 48e37fe..973859d 100644
--- a/bin/wlan/wlancfg/src/device.rs
+++ b/bin/wlan/wlancfg/src/device.rs
@@ -22,7 +22,9 @@
}
pub async fn handle_event(
- listener: &Listener, evt: DeviceWatcherEvent, ess_store: Arc<KnownEssStore>,
+ listener: &Listener,
+ evt: DeviceWatcherEvent,
+ ess_store: Arc<KnownEssStore>,
) {
println!("wlancfg got event: {:?}", evt);
match evt {
@@ -87,7 +89,9 @@
}
async fn on_iface_added(
- listener: &Listener, iface_id: u16, ess_store: Arc<KnownEssStore>,
+ listener: &Listener,
+ iface_id: u16,
+ ess_store: Arc<KnownEssStore>,
) -> Result<(), failure::Error> {
let service = listener.proxy.clone();
let legacy_client = listener.legacy_client.clone();
diff --git a/bin/wlan/wlancfg/src/known_ess_store.rs b/bin/wlan/wlancfg/src/known_ess_store.rs
index 0bfc49f..604e939 100644
--- a/bin/wlan/wlancfg/src/known_ess_store.rs
+++ b/bin/wlan/wlancfg/src/known_ess_store.rs
@@ -52,7 +52,8 @@
}
pub fn new_with_paths(
- storage_path: PathBuf, tmp_storage_path: PathBuf,
+ storage_path: PathBuf,
+ tmp_storage_path: PathBuf,
) -> Result<Self, failure::Error> {
let ess_list: Vec<EssJsonRead> = match fs::File::open(&storage_path) {
Ok(file) => match serde_json::from_reader(file) {
@@ -101,7 +102,9 @@
self.write(guard)
}
- pub fn known_network_count(&self) -> usize { self.ess_by_ssid.lock().len() }
+ pub fn known_network_count(&self) -> usize {
+ self.ess_by_ssid.lock().len()
+ }
fn write(&self, guard: MutexGuard<EssMap>) -> Result<(), failure::Error> {
let temp_file = TempFile::create(&self.tmp_storage_path)?;
@@ -255,5 +258,7 @@
.expect("Failed to create an KnownEssStore")
}
- fn ess(password: &[u8]) -> KnownEss { KnownEss { password: password.to_vec() } }
+ fn ess(password: &[u8]) -> KnownEss {
+ KnownEss { password: password.to_vec() }
+ }
}
diff --git a/bin/wlan/wlancfg/src/main.rs b/bin/wlan/wlancfg/src/main.rs
index c87f2c8..6727392 100644
--- a/bin/wlan/wlancfg/src/main.rs
+++ b/bin/wlan/wlancfg/src/main.rs
@@ -27,11 +27,14 @@
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Never {}
impl Never {
- pub fn into_any<T>(self) -> T { match self {} }
+ pub fn into_any<T>(self) -> T {
+ match self {}
+ }
}
fn serve_fidl(
- _client_ref: shim::ClientRef, ess_store: Arc<KnownEssStore>,
+ _client_ref: shim::ClientRef,
+ ess_store: Arc<KnownEssStore>,
) -> impl Future<Output = Result<Never, Error>> {
future::ready(
ServicesServer::new()
diff --git a/bin/wlan/wlancfg/src/shim.rs b/bin/wlan/wlancfg/src/shim.rs
index 3fa697f..e360cae 100644
--- a/bin/wlan/wlancfg/src/shim.rs
+++ b/bin/wlan/wlancfg/src/shim.rs
@@ -26,7 +26,9 @@
pub struct ClientRef(Arc<Mutex<Option<Client>>>);
impl ClientRef {
- pub fn new() -> Self { ClientRef(Arc::new(Mutex::new(None))) }
+ pub fn new() -> Self {
+ ClientRef(Arc::new(Mutex::new(None)))
+ }
pub fn set_if_empty(&self, client: Client) {
let mut c = self.0.lock().unwrap();
@@ -57,7 +59,9 @@
const MAX_CONCURRENT_WLAN_REQUESTS: usize = 1000;
pub async fn serve_legacy(
- requests: legacy::WlanRequestStream, client: ClientRef, ess_store: Arc<KnownEssStore>,
+ requests: legacy::WlanRequestStream,
+ client: ClientRef,
+ ess_store: Arc<KnownEssStore>,
) -> Result<(), fidl::Error> {
await!(requests.try_for_each_concurrent(MAX_CONCURRENT_WLAN_REQUESTS, |req| handle_request(
&client,
@@ -67,7 +71,9 @@
}
async fn handle_request(
- client: &ClientRef, req: legacy::WlanRequest, ess_store: Arc<KnownEssStore>,
+ client: &ClientRef,
+ req: legacy::WlanRequest,
+ ess_store: Arc<KnownEssStore>,
) -> Result<(), fidl::Error> {
match req {
legacy::WlanRequest::Scan { req, responder } => {
@@ -141,10 +147,7 @@
return Err(internal_error());
}
- Ok(aps
- .into_iter()
- .map(|ess| convert_bss_info(ess.best_bss))
- .collect())
+ Ok(aps.into_iter().map(|ess| convert_bss_info(ess.best_bss)).collect())
}
);
@@ -155,7 +158,8 @@
}
fn start_scan_txn(
- client: &Client, legacy_req: legacy::ScanRequest,
+ client: &Client,
+ legacy_req: legacy::ScanRequest,
) -> Result<fidl_sme::ScanTransactionProxy, fidl::Error> {
let (scan_txn, remote) = create_proxy()?;
let mut req = fidl_sme::ScanRequest {
@@ -186,13 +190,14 @@
chan: fidl_common::WlanChan {
primary: bss.channel,
secondary80: 0,
- cbw: fidl_common::Cbw::Cbw20
+ cbw: fidl_common::Cbw::Cbw20,
},
}
}
fn connect(
- client: &ClientRef, legacy_req: legacy::ConnectConfig,
+ client: &ClientRef,
+ legacy_req: legacy::ConnectConfig,
) -> impl Future<Output = legacy::Error> {
future::ready(client.get())
.and_then(move |client| {
diff --git a/bin/wlan/wlancfg/src/state_machine.rs b/bin/wlan/wlancfg/src/state_machine.rs
index c79c367..a6e426b 100644
--- a/bin/wlan/wlancfg/src/state_machine.rs
+++ b/bin/wlan/wlancfg/src/state_machine.rs
@@ -34,12 +34,16 @@
pub trait IntoStateExt<E>: Future<Output = Result<State<E>, E>> {
fn into_state(self) -> State<E>
- where Self: Sized + Send + 'static {
+ where
+ Self: Sized + Send + 'static,
+ {
State(FutureObj::new(Box::new(self)))
}
fn into_state_machine(self) -> StateMachine<E>
- where Self: Sized + Send + 'static {
+ where
+ Self: Sized + Send + 'static,
+ {
StateMachine { cur_state: self.into_state() }
}
}
@@ -71,7 +75,8 @@
}
async fn sum_state(
- current: u32, stream: mpsc::UnboundedReceiver<u32>,
+ current: u32,
+ stream: mpsc::UnboundedReceiver<u32>,
) -> Result<State<u32>, u32> {
let (number, stream) = await!(stream.into_future());
match number {
diff --git a/bin/wlan/wlanstack/meta/wlanstack2.cmx b/bin/wlan/wlanstack/meta/wlanstack2.cmx
index 20c93fb..39aa53f 100644
--- a/bin/wlan/wlanstack/meta/wlanstack2.cmx
+++ b/bin/wlan/wlanstack/meta/wlanstack2.cmx
@@ -3,8 +3,15 @@
"binary": "bin/app"
},
"sandbox": {
- "dev": [ "class/wlanphy", "class/wlanif" ],
- "services": [ "fuchsia.cobalt.LoggerFactory" ],
- "system": [ "data/wlanstack2" ]
+ "dev": [
+ "class/wlanphy",
+ "class/wlanif"
+ ],
+ "services": [
+ "fuchsia.cobalt.LoggerFactory"
+ ],
+ "system": [
+ "data/wlanstack2"
+ ]
}
-}
\ No newline at end of file
+}
diff --git a/bin/wlan/wlanstack/src/device.rs b/bin/wlan/wlanstack/src/device.rs
index 83f6e4f..ee93f41 100644
--- a/bin/wlan/wlanstack/src/device.rs
+++ b/bin/wlan/wlanstack/src/device.rs
@@ -15,20 +15,17 @@
stream::{FuturesUnordered, Stream, StreamExt, TryStreamExt},
},
log::{error, info},
- std::{
- marker::Unpin,
- sync::Arc,
- },
+ std::{marker::Unpin, sync::Arc},
wlan_sme::{self, clone_utils},
};
use crate::{
device_watch::{self, NewIfaceDevice},
mlme_query_proxy::MlmeQueryProxy,
- Never,
station,
stats_scheduler::{self, StatsScheduler},
watchable_map::WatchableMap,
+ Never,
};
pub struct PhyDevice {
@@ -81,10 +78,7 @@
info!("new phy #{}: {}", new_phy.id, new_phy.device.path().to_string_lossy());
let id = new_phy.id;
let event_stream = new_phy.proxy.take_event_stream();
- phys.insert(id, PhyDevice {
- proxy: new_phy.proxy,
- device: new_phy.device,
- });
+ phys.insert(id, PhyDevice { proxy: new_phy.proxy, device: new_phy.device });
let r = await!(event_stream.map_ok(|_| ()).try_collect::<()>());
phys.remove(&id);
if let Err(e) = r {
@@ -93,7 +87,10 @@
info!("phy removed: #{}", id);
}
-pub async fn serve_ifaces(ifaces: Arc<IfaceMap>, cobalt_sender: CobaltSender) -> Result<Never, Error> {
+pub async fn serve_ifaces(
+ ifaces: Arc<IfaceMap>,
+ cobalt_sender: CobaltSender,
+) -> Result<Never, Error> {
let mut new_ifaces = device_watch::watch_iface_devices()?;
let mut active_ifaces = FuturesUnordered::new();
loop {
@@ -111,7 +108,11 @@
}
}
-async fn query_and_serve_iface(new_iface: NewIfaceDevice, ifaces: &IfaceMap, cobalt_sender: CobaltSender) {
+async fn query_and_serve_iface(
+ new_iface: NewIfaceDevice,
+ ifaces: &IfaceMap,
+ cobalt_sender: CobaltSender,
+) {
let NewIfaceDevice { id, device, proxy } = new_iface;
let event_stream = proxy.take_event_stream();
let (stats_sched, stats_reqs) = stats_scheduler::create_scheduler();
@@ -127,22 +128,20 @@
let (sme, sme_fut) = match result {
Ok(x) => x,
Err(e) => {
- error!("Failed to create SME for new iface '{}': {}",
- device.path().display(), e);
+ error!("Failed to create SME for new iface '{}': {}", device.path().display(), e);
return;
}
};
- info!("new iface #{} with role '{:?}': {}",
- id, device_info.role, device.path().to_string_lossy());
+ info!(
+ "new iface #{} with role '{:?}': {}",
+ id,
+ device_info.role,
+ device.path().to_string_lossy()
+ );
let mlme_query = MlmeQueryProxy::new(proxy);
- ifaces.insert(id, IfaceDevice {
- sme_server: sme,
- stats_sched,
- device,
- mlme_query,
- device_info,
- });
+ ifaces
+ .insert(id, IfaceDevice { sme_server: sme, stats_sched, device, mlme_query, device_info });
let r = await!(sme_fut);
if let Err(e) = r {
@@ -152,38 +151,45 @@
info!("iface removed: {}", id);
}
-fn create_sme<S>(proxy: fidl_mlme::MlmeProxy,
- event_stream: fidl_mlme::MlmeEventStream,
- device_info: &DeviceInfo,
- stats_requests: S,
- cobalt_sender: CobaltSender)
- -> Result<(SmeServer, impl Future<Output = Result<(), Error>>), Error>
- where S: Stream<Item = stats_scheduler::StatsRequest> + Send + Unpin + 'static
+fn create_sme<S>(
+ proxy: fidl_mlme::MlmeProxy,
+ event_stream: fidl_mlme::MlmeEventStream,
+ device_info: &DeviceInfo,
+ stats_requests: S,
+ cobalt_sender: CobaltSender,
+) -> Result<(SmeServer, impl Future<Output = Result<(), Error>>), Error>
+where
+ S: Stream<Item = stats_scheduler::StatsRequest> + Send + Unpin + 'static,
{
let role = device_info.role;
- let device_info =
- wlan_sme::DeviceInfo {
- addr: device_info.mac_addr,
- bands: clone_utils::clone_bands(&device_info.bands),
- };
+ let device_info = wlan_sme::DeviceInfo {
+ addr: device_info.mac_addr,
+ bands: clone_utils::clone_bands(&device_info.bands),
+ };
match role {
fidl_mlme::MacRole::Client => {
let (sender, receiver) = mpsc::unbounded();
let fut = station::client::serve(
- proxy, device_info, event_stream, receiver, stats_requests, cobalt_sender);
+ proxy,
+ device_info,
+ event_stream,
+ receiver,
+ stats_requests,
+ cobalt_sender,
+ );
Ok((SmeServer::Client(sender), FutureObj::new(Box::new(fut))))
- },
+ }
fidl_mlme::MacRole::Ap => {
let (sender, receiver) = mpsc::unbounded();
- let fut = station::ap::serve(
- proxy, device_info, event_stream, receiver, stats_requests);
+ let fut =
+ station::ap::serve(proxy, device_info, event_stream, receiver, stats_requests);
Ok((SmeServer::Ap(sender), FutureObj::new(Box::new(fut))))
- },
+ }
fidl_mlme::MacRole::Mesh => {
let (sender, receiver) = mpsc::unbounded();
- let fut = station::mesh::serve(
- proxy, device_info, event_stream, receiver, stats_requests);
+ let fut =
+ station::mesh::serve(proxy, device_info, event_stream, receiver, stats_requests);
Ok((SmeServer::Mesh(sender), FutureObj::new(Box::new(fut))))
}
}
diff --git a/bin/wlan/wlanstack/src/device_watch.rs b/bin/wlan/wlanstack/src/device_watch.rs
index b4f91f1..741dd95 100644
--- a/bin/wlan/wlanstack/src/device_watch.rs
+++ b/bin/wlan/wlanstack/src/device_watch.rs
@@ -3,15 +3,15 @@
// found in the LICENSE file.
use failure::format_err;
-use fidl_fuchsia_wlan_mlme as fidl_mlme;
use fidl_fuchsia_wlan_device as fidl_wlan_dev;
+use fidl_fuchsia_wlan_mlme as fidl_mlme;
+use fuchsia_vfs_watcher::{WatchEvent, Watcher};
use fuchsia_wlan_dev as wlan_dev;
-use fuchsia_vfs_watcher::{Watcher, WatchEvent};
use fuchsia_zircon::Status as zx_Status;
use futures::prelude::*;
use log::{error, info};
-use std::io;
use std::fs::File;
+use std::io;
use std::path::{Path, PathBuf};
use std::str::FromStr;
@@ -30,20 +30,14 @@
pub device: wlan_dev::Device,
}
-pub fn watch_phy_devices()
- -> io::Result<impl Stream<Item = io::Result<NewPhyDevice>>>
-{
+pub fn watch_phy_devices() -> io::Result<impl Stream<Item = io::Result<NewPhyDevice>>> {
Ok(watch_new_devices(PHY_PATH)?
.try_filter_map(|path| future::ready(Ok(handle_open_error(&path, new_phy(&path))))))
}
-pub fn watch_iface_devices()
- -> io::Result<impl Stream<Item = io::Result<NewIfaceDevice>>>
-{
+pub fn watch_iface_devices() -> io::Result<impl Stream<Item = io::Result<NewIfaceDevice>>> {
Ok(watch_new_devices(IFACE_PATH)?
- .try_filter_map(|path| {
- future::ready(Ok(handle_open_error(&path, new_iface(&path))))
- }))
+ .try_filter_map(|path| future::ready(Ok(handle_open_error(&path, new_iface(&path))))))
}
fn handle_open_error<T>(path: &PathBuf, r: Result<T, failure::Error>) -> Option<T> {
@@ -57,15 +51,15 @@
r.ok()
}
-fn watch_new_devices<P: AsRef<Path>>(path: P)
- -> io::Result<impl Stream<Item = io::Result<PathBuf>>>
-{
+fn watch_new_devices<P: AsRef<Path>>(
+ path: P,
+) -> io::Result<impl Stream<Item = io::Result<PathBuf>>> {
let dir = File::open(&path)?;
let watcher = Watcher::new(&dir)?;
Ok(watcher.try_filter_map(move |msg| {
future::ready(Ok(match msg.event {
WatchEvent::EXISTING | WatchEvent::ADD_FILE => Some(path.as_ref().join(msg.filename)),
- _ => None
+ _ => None,
}))
}))
}
@@ -74,23 +68,22 @@
let id = id_from_path(path)?;
let device = wlan_dev::Device::new(path)?;
let proxy = wlan_dev::connect_wlan_phy(&device)?;
- Ok(NewPhyDevice{ id, proxy, device })
+ Ok(NewPhyDevice { id, proxy, device })
}
fn new_iface(path: &PathBuf) -> Result<NewIfaceDevice, failure::Error> {
let id = id_from_path(path)?;
let device = wlan_dev::Device::new(path)?;
let proxy = fidl_mlme::MlmeProxy::new(wlan_dev::connect_wlan_iface(&device)?);
- Ok(NewIfaceDevice{ id, proxy, device })
+ Ok(NewIfaceDevice { id, proxy, device })
}
fn id_from_path(path: &PathBuf) -> Result<u16, failure::Error> {
- let file_name = path.file_name().ok_or_else(
- || format_err!("Invalid device path"))?;
- let file_name_str = file_name.to_str().ok_or_else(
- || format_err!("Filename is not valid UTF-8"))?;
- let id = u16::from_str(&file_name_str).map_err(
- |e| format_err!("Failed to parse device filename as a numeric ID: {}", e))?;
+ let file_name = path.file_name().ok_or_else(|| format_err!("Invalid device path"))?;
+ let file_name_str =
+ file_name.to_str().ok_or_else(|| format_err!("Filename is not valid UTF-8"))?;
+ let id = u16::from_str(&file_name_str)
+ .map_err(|e| format_err!("Failed to parse device filename as a numeric ID: {}", e))?;
Ok(id)
}
@@ -110,16 +103,21 @@
let mut new_phy_stream = watch_phy_devices().expect("watch_phy_devices() failed");
let wlantap = wlantap_client::Wlantap::open().expect("Failed to connect to wlantapctl");
let _tap_phy = wlantap.create_phy(create_wlantap_config(*b"wtchph"));
- for _ in 0..10 { // 5 is more than enough even for Toulouse but let's be generous
- let new_phy = exec.run_singlethreaded(
- new_phy_stream.next().on_timeout(2.seconds().after_now(),
- || panic!("No more phys"))
- )
+ for _ in 0..10 {
+ // 5 is more than enough even for Toulouse but let's be generous
+ let new_phy = exec
+ .run_singlethreaded(
+ new_phy_stream
+ .next()
+ .on_timeout(2.seconds().after_now(), || panic!("No more phys")),
+ )
.expect("new_phy_stream ended without yielding a phy")
.expect("new_phy_stream returned an error");
- let query_resp = exec.run_singlethreaded(new_phy.proxy.query())
- .expect("phy query failed");
- if b"wtchph" == &query_resp.info.hw_mac_address { return; }
+ let query_resp =
+ exec.run_singlethreaded(new_phy.proxy.query()).expect("phy query failed");
+ if b"wtchph" == &query_resp.info.hw_mac_address {
+ return;
+ }
}
panic!("Did not get the phy we are looking for");
}
@@ -131,12 +129,15 @@
dev_path: None,
hw_mac_address: mac_addr,
supported_phys: vec![
- SupportedPhy::Dsss, SupportedPhy::Cck, SupportedPhy::Ofdm, SupportedPhy::Ht
+ SupportedPhy::Dsss,
+ SupportedPhy::Cck,
+ SupportedPhy::Ofdm,
+ SupportedPhy::Ht,
],
driver_features: vec![],
mac_roles: vec![fidl_wlan_dev::MacRole::Client],
caps: vec![],
- bands: vec![create_2_4_ghz_band_info()]
+ bands: vec![create_2_4_ghz_band_info()],
},
name: String::from("devwatchtap"),
quiet: false,
@@ -144,7 +145,7 @@
}
fn create_2_4_ghz_band_info() -> fidl_wlan_dev::BandInfo {
- fidl_wlan_dev::BandInfo{
+ fidl_wlan_dev::BandInfo {
band_id: fidl_common::Band::WlanBand2Ghz,
ht_caps: Some(Box::new(fidl_mlme::HtCapabilities {
ht_cap_info: fidl_mlme::HtCapabilityInfo {
@@ -210,15 +211,14 @@
antenna_idx_feedback: false,
rx_asel: false,
tx_sounding_ppdu: false,
- }
-
+ },
})),
vht_caps: None,
basic_rates: vec![2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108],
supported_channels: fidl_wlan_dev::ChannelList {
base_freq: 2407,
- channels: vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
- }
+ channels: vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
+ },
}
}
}
diff --git a/bin/wlan/wlanstack/src/fidl_util.rs b/bin/wlan/wlanstack/src/fidl_util.rs
index 59ee68a..945b312 100644
--- a/bin/wlan/wlanstack/src/fidl_util.rs
+++ b/bin/wlan/wlanstack/src/fidl_util.rs
@@ -10,6 +10,6 @@
| fidl::Error::ServerRequestRead(zx::Status::PEER_CLOSED)
| fidl::Error::ClientRead(zx::Status::PEER_CLOSED)
| fidl::Error::ClientWrite(zx::Status::PEER_CLOSED) => true,
- _ => false
+ _ => false,
}
}
diff --git a/bin/wlan/wlanstack/src/future_util.rs b/bin/wlan/wlanstack/src/future_util.rs
index b0fa63d..ce5f3b9 100644
--- a/bin/wlan/wlanstack/src/future_util.rs
+++ b/bin/wlan/wlanstack/src/future_util.rs
@@ -4,24 +4,24 @@
use futures::ready;
use futures::stream::{Fuse, Stream, StreamExt};
-use futures::task::{Poll, LocalWaker};
+use futures::task::{LocalWaker, Poll};
use pin_utils::{unsafe_pinned, unsafe_unpinned};
use std::marker::Unpin;
use std::pin::Pin;
-pub struct GroupAvailable<S, T, E> where S: Stream<Item = Result<T, E>> {
+pub struct GroupAvailable<S, T, E>
+where
+ S: Stream<Item = Result<T, E>>,
+{
stream: Fuse<S>,
error: Option<E>,
}
-impl<S, T, E> Unpin for GroupAvailable<S, T, E>
-where
- S: Unpin + Stream<Item = Result<T, E>>
-{}
+impl<S, T, E> Unpin for GroupAvailable<S, T, E> where S: Unpin + Stream<Item = Result<T, E>> {}
impl<S, T, E> GroupAvailable<S, T, E>
where
- S: Unpin + Stream<Item = Result<T, E>>
+ S: Unpin + Stream<Item = Result<T, E>>,
{
// Safety: projecting to `Fuse<S>` is safe because GroupAvailable is `!Unpin`
// when `S` is `!Unpin`, and `GroupAvailable` doesn't move out of `stream`.
@@ -32,14 +32,11 @@
impl<S, T, E> Stream for GroupAvailable<S, T, E>
where
- S: Unpin + Stream<Item = Result<T, E>>
+ S: Unpin + Stream<Item = Result<T, E>>,
{
type Item = Result<Vec<T>, E>;
- fn poll_next(
- mut self: Pin<&mut Self>,
- lw: &LocalWaker,
- ) -> Poll<Option<Self::Item>> {
+ fn poll_next(mut self: Pin<&mut Self>, lw: &LocalWaker) -> Poll<Option<Self::Item>> {
if let Some(e) = self.as_mut().error().take() {
return Poll::Ready(Some(Err(e)));
}
@@ -71,10 +68,7 @@
Self: Stream<Item = Result<T, E>>,
Self: Sized,
{
- GroupAvailable {
- stream: self.fuse(),
- error: None
- }
+ GroupAvailable { stream: self.fuse(), error: None }
}
}
@@ -93,9 +87,11 @@
#[test]
fn empty() {
let mut exec = fasync::Executor::new().expect("Failed to create an executor");
- let (item, _) = exec.run_singlethreaded(
- stream::empty::<Result<(), Never>>().group_available().try_into_future())
- .unwrap_or_else(Never::into_any);
+ let (item, _) = exec
+ .run_singlethreaded(
+ stream::empty::<Result<(), Never>>().group_available().try_into_future(),
+ )
+ .unwrap_or_else(Never::into_any);
assert!(item.is_none());
}
@@ -129,10 +125,8 @@
fn buffer_error() {
let mut exec = fasync::Executor::new().expect("Failed to create an executor");
- let mut s = stream::iter(vec![Ok(10i32), Ok(20i32), Err(-30i32)])
- .group_available();
- let item = exec.run_singlethreaded(s.try_next())
- .expect("expected a successful value");
+ let mut s = stream::iter(vec![Ok(10i32), Ok(20i32), Err(-30i32)]).group_available();
+ let item = exec.run_singlethreaded(s.try_next()).expect("expected a successful value");
assert_eq!(Some(vec![10i32, 20i32]), item);
let res = exec.run_singlethreaded(s.try_next());
diff --git a/bin/wlan/wlanstack/src/main.rs b/bin/wlan/wlanstack/src/main.rs
index 008b7fc..a31cfa4 100644
--- a/bin/wlan/wlanstack/src/main.rs
+++ b/bin/wlan/wlanstack/src/main.rs
@@ -7,7 +7,7 @@
#![feature(async_await, await_macro, futures_api)]
#![deny(warnings)]
#![deny(missing_docs)]
-#![recursion_limit="256"]
+#![recursion_limit = "256"]
mod device;
mod device_watch;
@@ -22,18 +22,18 @@
mod watchable_map;
mod watcher_service;
-use failure::{Error, format_err, ResultExt};
+use failure::{format_err, Error, ResultExt};
use fidl::endpoints::ServiceMarker;
use fidl_fuchsia_wlan_device_service::DeviceServiceMarker;
use fuchsia_app::server::ServicesServer;
use fuchsia_async as fasync;
use fuchsia_cobalt;
-use futures::prelude::*;
use futures::channel::mpsc::{self, UnboundedReceiver};
+use futures::prelude::*;
use log::info;
use std::sync::Arc;
-use crate::device::{PhyDevice, PhyMap, IfaceDevice, IfaceMap};
+use crate::device::{IfaceDevice, IfaceMap, PhyDevice, PhyMap};
use crate::watchable_map::MapEvent;
const MAX_LOG_LEVEL: log::LevelFilter = log::LevelFilter::Info;
@@ -46,7 +46,9 @@
impl Never {
#[allow(missing_docs)]
- pub fn into_any<T>(self) -> T { match self {} }
+ pub fn into_any<T>(self) -> T {
+ match self {}
+ }
}
fn main() -> Result<(), Error> {
@@ -62,38 +64,40 @@
let phys = Arc::new(phys);
let ifaces = Arc::new(ifaces);
- let phy_server = device::serve_phys(phys.clone())
- .map_ok(|x| x.into_any());
+ let phy_server = device::serve_phys(phys.clone()).map_ok(|x| x.into_any());
let (cobalt_sender, cobalt_reporter) = fuchsia_cobalt::serve();
- let telemetry_server = telemetry::report_telemetry_periodically(ifaces.clone(), cobalt_sender.clone());
- let iface_server = device::serve_ifaces(ifaces.clone(), cobalt_sender)
- .map_ok(|x| x.into_any());
- let services_server = serve_fidl(phys, ifaces, phy_events, iface_events)?
- .map_ok(Never::into_any);
+ let telemetry_server =
+ telemetry::report_telemetry_periodically(ifaces.clone(), cobalt_sender.clone());
+ let iface_server = device::serve_ifaces(ifaces.clone(), cobalt_sender).map_ok(|x| x.into_any());
+ let services_server =
+ serve_fidl(phys, ifaces, phy_events, iface_events)?.map_ok(Never::into_any);
- exec.run_singlethreaded(services_server.try_join5(phy_server,
- iface_server,
- cobalt_reporter.map(Ok),
- telemetry_server.map(Ok)))
- .map(|((), (), (), (), ())| ())
-
+ exec.run_singlethreaded(services_server.try_join5(
+ phy_server,
+ iface_server,
+ cobalt_reporter.map(Ok),
+ telemetry_server.map(Ok),
+ ))
+ .map(|((), (), (), (), ())| ())
}
-fn serve_fidl(phys: Arc<PhyMap>, ifaces: Arc<IfaceMap>,
- phy_events: UnboundedReceiver<MapEvent<u16, PhyDevice>>,
- iface_events: UnboundedReceiver<MapEvent<u16, IfaceDevice>>)
- -> Result<impl Future<Output = Result<Never, Error>>, Error>
-{
+fn serve_fidl(
+ phys: Arc<PhyMap>,
+ ifaces: Arc<IfaceMap>,
+ phy_events: UnboundedReceiver<MapEvent<u16, PhyDevice>>,
+ iface_events: UnboundedReceiver<MapEvent<u16, IfaceDevice>>,
+) -> Result<impl Future<Output = Result<Never, Error>>, Error> {
let (sender, receiver) = mpsc::unbounded();
let fdio_server = ServicesServer::new()
.add_service((DeviceServiceMarker::NAME, move |channel| {
- sender.unbounded_send(channel).expect("Failed to send a new client to the server future");
+ sender
+ .unbounded_send(channel)
+ .expect("Failed to send a new client to the server future");
}))
.start()
.context("error configuring device service")?
.and_then(|()| future::ready(Err(format_err!("fdio server future exited unexpectedly"))))
.map_err(|e| e.context("fdio server terminated with error").into());
let device_service = service::device_service(phys, ifaces, phy_events, iface_events, receiver);
- Ok(fdio_server.try_join(device_service)
- .map_ok(|x: (Never, Never)| x.0))
+ Ok(fdio_server.try_join(device_service).map_ok(|x: (Never, Never)| x.0))
}
diff --git a/bin/wlan/wlanstack/src/mlme_query_proxy.rs b/bin/wlan/wlanstack/src/mlme_query_proxy.rs
index 91cdfc9..5600bce 100644
--- a/bin/wlan/wlanstack/src/mlme_query_proxy.rs
+++ b/bin/wlan/wlanstack/src/mlme_query_proxy.rs
@@ -2,9 +2,10 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-use{
- fidl_fuchsia_wlan_mlme::{MlmeProxy, MinstrelListResponse,
- MinstrelStatsRequest, MinstrelStatsResponse},
+use {
+ fidl_fuchsia_wlan_mlme::{
+ MinstrelListResponse, MinstrelStatsRequest, MinstrelStatsResponse, MlmeProxy,
+ },
futures::Future,
};
@@ -14,21 +15,20 @@
impl MlmeQueryProxy {
pub fn new(proxy: MlmeProxy) -> Self {
- MlmeQueryProxy {
- proxy,
- }
+ MlmeQueryProxy { proxy }
}
- pub fn get_minstrel_list(&self)
- -> impl Future<Output = Result<MinstrelListResponse, fidl::Error>>
- {
+ pub fn get_minstrel_list(
+ &self,
+ ) -> impl Future<Output = Result<MinstrelListResponse, fidl::Error>> {
self.proxy.list_minstrel_peers()
}
- pub fn get_minstrel_peer(&self, mac_addr: [u8; 6])
- -> impl Future<Output = Result<MinstrelStatsResponse, fidl::Error>>
- {
- let mut req = MinstrelStatsRequest{ mac_addr };
+ pub fn get_minstrel_peer(
+ &self,
+ mac_addr: [u8; 6],
+ ) -> impl Future<Output = Result<MinstrelStatsResponse, fidl::Error>> {
+ let mut req = MinstrelStatsRequest { mac_addr };
self.proxy.get_minstrel_stats(&mut req)
}
-}
\ No newline at end of file
+}
diff --git a/bin/wlan/wlanstack/src/service.rs b/bin/wlan/wlanstack/src/service.rs
index 0919f30..1bd3688 100644
--- a/bin/wlan/wlanstack/src/service.rs
+++ b/bin/wlan/wlanstack/src/service.rs
@@ -5,38 +5,41 @@
use failure::{bail, format_err};
use fidl::encoding::OutOfLine;
use fidl::endpoints::RequestStream;
-use fidl_fuchsia_wlan_device_service::{self as fidl_svc, DeviceServiceRequest};
use fidl_fuchsia_wlan_device as fidl_wlan_dev;
+use fidl_fuchsia_wlan_device_service::{self as fidl_svc, DeviceServiceRequest};
use fidl_fuchsia_wlan_mlme::{self as fidl_mlme, MinstrelStatsResponse};
use fuchsia_async as fasync;
use fuchsia_zircon as zx;
use futures::channel::mpsc::UnboundedReceiver;
+use futures::prelude::*;
use futures::select;
use futures::stream::FuturesUnordered;
-use futures::prelude::*;
use log::{error, info};
use pin_utils::pin_mut;
use std::marker::Unpin;
use std::sync::Arc;
use crate::device::{self, IfaceDevice, IfaceMap, PhyDevice, PhyMap};
-use crate::Never;
use crate::station;
use crate::stats_scheduler::StatsRef;
use crate::watchable_map::MapEvent;
use crate::watcher_service::{self, WatcherService};
+use crate::Never;
const CONCURRENT_LIMIT: usize = 1000;
-pub async fn device_service<S>(phys: Arc<PhyMap>, ifaces: Arc<IfaceMap>,
- phy_events: UnboundedReceiver<MapEvent<u16, PhyDevice>>,
- iface_events: UnboundedReceiver<MapEvent<u16, IfaceDevice>>,
- new_clients: S)
- -> Result<Never, failure::Error>
- where S: Stream<Item = fasync::Channel> + Unpin
+pub async fn device_service<S>(
+ phys: Arc<PhyMap>,
+ ifaces: Arc<IfaceMap>,
+ phy_events: UnboundedReceiver<MapEvent<u16, PhyDevice>>,
+ iface_events: UnboundedReceiver<MapEvent<u16, IfaceDevice>>,
+ new_clients: S,
+) -> Result<Never, failure::Error>
+where
+ S: Stream<Item = fasync::Channel> + Unpin,
{
- let (watcher_service, watcher_fut) = watcher_service::serve_watchers(
- phys.clone(), ifaces.clone(), phy_events, iface_events);
+ let (watcher_service, watcher_fut) =
+ watcher_service::serve_watchers(phys.clone(), ifaces.clone(), phy_events, iface_events);
pin_mut!(watcher_fut);
let mut watcher_fut = watcher_fut.fuse();
let mut active_clients = FuturesUnordered::new();
@@ -57,78 +60,82 @@
}
}
-async fn serve_channel(phys: Arc<PhyMap>, ifaces: Arc<IfaceMap>,
- watcher_service: WatcherService<PhyDevice, IfaceDevice>,
- channel: fasync::Channel)
-{
+async fn serve_channel(
+ phys: Arc<PhyMap>,
+ ifaces: Arc<IfaceMap>,
+ watcher_service: WatcherService<PhyDevice, IfaceDevice>,
+ channel: fasync::Channel,
+) {
let r = await!(fidl_svc::DeviceServiceRequestStream::from_channel(channel)
- .try_for_each_concurrent(CONCURRENT_LIMIT, move |request| {
- handle_fidl_request(request, Arc::clone(&phys), Arc::clone(&ifaces), watcher_service.clone())
- }));
+ .try_for_each_concurrent(CONCURRENT_LIMIT, move |request| handle_fidl_request(
+ request,
+ Arc::clone(&phys),
+ Arc::clone(&ifaces),
+ watcher_service.clone()
+ )));
r.unwrap_or_else(|e| error!("error serving a DeviceService client: {}", e))
}
-async fn handle_fidl_request(request: fidl_svc::DeviceServiceRequest,
- phys: Arc<PhyMap>,
- ifaces: Arc<IfaceMap>,
- watcher_service: WatcherService<PhyDevice, IfaceDevice>)
- -> Result<(), fidl::Error>
-{
+async fn handle_fidl_request(
+ request: fidl_svc::DeviceServiceRequest,
+ phys: Arc<PhyMap>,
+ ifaces: Arc<IfaceMap>,
+ watcher_service: WatcherService<PhyDevice, IfaceDevice>,
+) -> Result<(), fidl::Error> {
// Note that errors from responder.send() are propagated intentionally.
// If we fail to send a response, the only way to recover is to stop serving the client
// and close the channel. Otherwise, the client would be left hanging forever.
match request {
- DeviceServiceRequest::ListPhys{ responder } =>
- responder.send(&mut list_phys(&phys)),
+ DeviceServiceRequest::ListPhys { responder } => responder.send(&mut list_phys(&phys)),
DeviceServiceRequest::QueryPhy { req, responder } => {
let result = await!(query_phy(&phys, req.phy_id));
let (status, mut response) = into_status_and_opt(result);
responder.send(status.into_raw(), response.as_mut().map(OutOfLine))
- },
- DeviceServiceRequest::ListIfaces { responder } =>
- responder.send(&mut list_ifaces(&ifaces)),
+ }
+ DeviceServiceRequest::ListIfaces { responder } => responder.send(&mut list_ifaces(&ifaces)),
DeviceServiceRequest::QueryIface { iface_id, responder } => {
let result = query_iface(&ifaces, iface_id);
let (status, mut response) = into_status_and_opt(result);
responder.send(status.into_raw(), response.as_mut().map(OutOfLine))
- },
+ }
DeviceServiceRequest::CreateIface { req, responder } => {
let result = await!(create_iface(&phys, req));
let (status, mut response) = into_status_and_opt(result);
responder.send(status.into_raw(), response.as_mut().map(OutOfLine))
- },
- DeviceServiceRequest::DestroyIface{ req: _, responder: _ } => unimplemented!(),
- DeviceServiceRequest::GetClientSme{ iface_id, sme, responder } => {
+ }
+ DeviceServiceRequest::DestroyIface { req: _, responder: _ } => unimplemented!(),
+ DeviceServiceRequest::GetClientSme { iface_id, sme, responder } => {
let status = get_client_sme(&ifaces, iface_id, sme);
responder.send(status.into_raw())
- },
- DeviceServiceRequest::GetApSme{ iface_id, sme, responder } => {
+ }
+ DeviceServiceRequest::GetApSme { iface_id, sme, responder } => {
let status = get_ap_sme(&ifaces, iface_id, sme);
responder.send(status.into_raw())
- },
- DeviceServiceRequest::GetMeshSme{ iface_id, sme, responder } => {
+ }
+ DeviceServiceRequest::GetMeshSme { iface_id, sme, responder } => {
let status = get_mesh_sme(&ifaces, iface_id, sme);
responder.send(status.into_raw())
- },
- DeviceServiceRequest::GetIfaceStats{ iface_id, responder } => {
+ }
+ DeviceServiceRequest::GetIfaceStats { iface_id, responder } => {
match await!(get_iface_stats(&ifaces, iface_id)) {
Ok(stats_ref) => {
let mut stats = stats_ref.lock();
responder.send(zx::sys::ZX_OK, Some(OutOfLine(&mut stats)))
- },
+ }
Err(status) => responder.send(status.into_raw(), None),
}
- },
- DeviceServiceRequest::GetMinstrelList{ iface_id, responder } => {
+ }
+ DeviceServiceRequest::GetMinstrelList { iface_id, responder } => {
let (status, mut peers) = await!(list_minstrel_peers(&ifaces, iface_id));
responder.send(status.into_raw(), &mut peers)
- },
- DeviceServiceRequest::GetMinstrelStats{ iface_id, peer_addr, responder } => {
+ }
+ DeviceServiceRequest::GetMinstrelStats { iface_id, peer_addr, responder } => {
let (status, mut peer) = await!(get_minstrel_stats(&ifaces, iface_id, peer_addr));
responder.send(status.into_raw(), peer.as_mut().map(|x| OutOfLine(x.as_mut())))
- },
- DeviceServiceRequest::WatchDevices{ watcher, control_handle: _ } => {
- watcher_service.add_watcher(watcher)
+ }
+ DeviceServiceRequest::WatchDevices { watcher, control_handle: _ } => {
+ watcher_service
+ .add_watcher(watcher)
.unwrap_or_else(|e| error!("error registering a device watcher: {}", e));
Ok(())
}
@@ -146,26 +153,21 @@
let list = phys
.get_snapshot()
.iter()
- .map(|(phy_id, phy)| {
- fidl_svc::PhyListItem {
- phy_id: *phy_id,
- path: phy.device.path().to_string_lossy().into_owned(),
- }
+ .map(|(phy_id, phy)| fidl_svc::PhyListItem {
+ phy_id: *phy_id,
+ path: phy.device.path().to_string_lossy().into_owned(),
})
.collect();
fidl_svc::ListPhysResponse { phys: list }
}
-async fn query_phy(phys: &PhyMap, id: u16)
- -> Result<fidl_svc::QueryPhyResponse, zx::Status>
-{
+async fn query_phy(phys: &PhyMap, id: u16) -> Result<fidl_svc::QueryPhyResponse, zx::Status> {
info!("query_phy(id = {})", id);
let phy = phys.get(&id).ok_or(zx::Status::NOT_FOUND)?;
- let query_result = await!(phy.proxy.query())
- .map_err(move |e| {
- error!("query_phy(id = {}): error sending 'Query' request to phy: {}", id, e);
- zx::Status::INTERNAL
- })?;
+ let query_result = await!(phy.proxy.query()).map_err(move |e| {
+ error!("query_phy(id = {}): error sending 'Query' request to phy: {}", id, e);
+ zx::Status::INTERNAL
+ })?;
info!("query_phy(id = {}): received a 'QueryResult' from device", id);
zx::Status::ok(query_result.status)?;
let mut info = query_result.info;
@@ -178,14 +180,12 @@
let list = ifaces
.get_snapshot()
.iter()
- .map(|(iface_id, iface)| {
- fidl_svc::IfaceListItem {
- iface_id: *iface_id,
- path: iface.device.path().to_string_lossy().into_owned(),
- }
+ .map(|(iface_id, iface)| fidl_svc::IfaceListItem {
+ iface_id: *iface_id,
+ path: iface.device.path().to_string_lossy().into_owned(),
})
.collect();
- fidl_svc::ListIfacesResponse{ ifaces: list }
+ fidl_svc::ListIfacesResponse { ifaces: list }
}
fn query_iface(ifaces: &IfaceMap, id: u16) -> Result<fidl_svc::QueryIfaceResponse, zx::Status> {
@@ -202,31 +202,33 @@
Ok(fidl_svc::QueryIfaceResponse { role, id, dev_path, mac_addr })
}
-async fn create_iface(phys: &PhyMap, req: fidl_svc::CreateIfaceRequest)
- -> Result<fidl_svc::CreateIfaceResponse, zx::Status>
-{
+async fn create_iface(
+ phys: &PhyMap,
+ req: fidl_svc::CreateIfaceRequest,
+) -> Result<fidl_svc::CreateIfaceResponse, zx::Status> {
let phy = phys.get(&req.phy_id).ok_or(zx::Status::NOT_FOUND)?;
let mut phy_req = fidl_wlan_dev::CreateIfaceRequest { role: req.role };
- let r = await!(phy.proxy.create_iface(&mut phy_req))
- .map_err(move |e| {
- error!("Error sending 'CreateIface' request to phy #{}: {}", req.phy_id, e);
- zx::Status::INTERNAL
- })?;
+ let r = await!(phy.proxy.create_iface(&mut phy_req)).map_err(move |e| {
+ error!("Error sending 'CreateIface' request to phy #{}: {}", req.phy_id, e);
+ zx::Status::INTERNAL
+ })?;
zx::Status::ok(r.status)?;
// TODO(gbonik): this is not the ID that we want to return
Ok(fidl_svc::CreateIfaceResponse { iface_id: r.iface_id })
}
-fn get_client_sme(ifaces: &IfaceMap, iface_id: u16, endpoint: station::client::Endpoint)
- -> zx::Status
-{
+fn get_client_sme(
+ ifaces: &IfaceMap,
+ iface_id: u16,
+ endpoint: station::client::Endpoint,
+) -> zx::Status {
let iface = ifaces.get(&iface_id);
let server = match iface {
None => return zx::Status::NOT_FOUND,
Some(ref iface) => match iface.sme_server {
device::SmeServer::Client(ref server) => server,
- _ => return zx::Status::NOT_SUPPORTED
- }
+ _ => return zx::Status::NOT_SUPPORTED,
+ },
};
match server.unbounded_send(endpoint) {
Ok(()) => zx::Status::OK,
@@ -243,8 +245,8 @@
None => return zx::Status::NOT_FOUND,
Some(ref iface) => match iface.sme_server {
device::SmeServer::Ap(ref server) => server,
- _ => return zx::Status::NOT_SUPPORTED
- }
+ _ => return zx::Status::NOT_SUPPORTED,
+ },
};
match server.unbounded_send(endpoint) {
Ok(()) => zx::Status::OK,
@@ -261,8 +263,8 @@
None => return zx::Status::NOT_FOUND,
Some(ref iface) => match iface.sme_server {
device::SmeServer::Mesh(ref server) => server,
- _ => return zx::Status::NOT_SUPPORTED
- }
+ _ => return zx::Status::NOT_SUPPORTED,
+ },
};
match server.unbounded_send(endpoint) {
Ok(()) => zx::Status::OK,
@@ -273,15 +275,15 @@
}
}
-async fn get_iface_stats(ifaces: &IfaceMap, iface_id: u16)
- -> Result<StatsRef, zx::Status>
-{
+async fn get_iface_stats(ifaces: &IfaceMap, iface_id: u16) -> Result<StatsRef, zx::Status> {
let iface = ifaces.get(&iface_id).ok_or(zx::Status::NOT_FOUND)?;
await!(iface.stats_sched.get_stats())
}
-async fn list_minstrel_peers(ifaces: &IfaceMap, iface_id: u16)
- -> (zx::Status, fidl_fuchsia_wlan_minstrel::Peers) {
+async fn list_minstrel_peers(
+ ifaces: &IfaceMap,
+ iface_id: u16,
+) -> (zx::Status, fidl_fuchsia_wlan_minstrel::Peers) {
let empty_peer_list = fidl_fuchsia_wlan_minstrel::Peers { peers: vec![] };
let iface = match ifaces.get(&iface_id) {
Some(iface) => iface,
@@ -289,12 +291,15 @@
};
match await!(iface.mlme_query.get_minstrel_list()) {
Ok(resp) => (zx::Status::OK, resp.peers),
- Err(_) => (zx::Status::INTERNAL, empty_peer_list)
+ Err(_) => (zx::Status::INTERNAL, empty_peer_list),
}
}
-async fn get_minstrel_stats(ifaces: &IfaceMap, iface_id: u16, mac_addr: [u8; 6])
- -> (zx::Status, Option<Box<fidl_fuchsia_wlan_minstrel::Peer>>) {
+async fn get_minstrel_stats(
+ ifaces: &IfaceMap,
+ iface_id: u16,
+ mac_addr: [u8; 6],
+) -> (zx::Status, Option<Box<fidl_fuchsia_wlan_minstrel::Peer>>) {
let iface = match ifaces.get(&iface_id) {
Some(iface) => iface,
None => return (zx::Status::NOT_FOUND, None),
@@ -336,10 +341,13 @@
phy_map.insert(20u16, phy_zero);
let mut list = super::list_phys(&phy_map).phys;
list.sort_by_key(|p| p.phy_id);
- assert_eq!(vec![
- PhyListItem{ phy_id: 10u16, path: "/dev/null".to_string() },
- PhyListItem{ phy_id: 20u16, path: "/dev/zero".to_string() },
- ], list)
+ assert_eq!(
+ vec![
+ PhyListItem { phy_id: 10u16, path: "/dev/null".to_string() },
+ PhyListItem { phy_id: 20u16, path: "/dev/zero".to_string() },
+ ],
+ list
+ )
}
#[test]
@@ -359,15 +367,17 @@
// The call above should trigger a Query message to the phy.
// Pretend that we are the phy and read the message from the other side.
let responder = match exec.run_until_stalled(&mut phy_stream.next()) {
- Poll::Ready(Some(Ok(PhyRequest::Query{ responder }))) => responder,
- _ => panic!("phy_stream returned unexpected result")
+ Poll::Ready(Some(Ok(PhyRequest::Query { responder }))) => responder,
+ _ => panic!("phy_stream returned unexpected result"),
};
// Reply with a fake phy info
- responder.send(&mut fidl_wlan_dev::QueryResponse {
- status: zx::sys::ZX_OK,
- info: fake_phy_info(),
- }).expect("failed to send QueryResponse");
+ responder
+ .send(&mut fidl_wlan_dev::QueryResponse {
+ status: zx::sys::ZX_OK,
+ info: fake_phy_info(),
+ })
+ .expect("failed to send QueryResponse");
// Our original future should complete now, and return the same phy info
let response = match exec.run_until_stalled(&mut query_fut) {
@@ -385,8 +395,7 @@
let query_fut = super::query_phy(&phy_map, 10u16);
pin_mut!(query_fut);
- assert_eq!(Poll::Ready(Err(zx::Status::NOT_FOUND)),
- exec.run_until_stalled(&mut query_fut));
+ assert_eq!(Poll::Ready(Err(zx::Status::NOT_FOUND)), exec.run_until_stalled(&mut query_fut));
}
#[test]
@@ -400,10 +409,13 @@
iface_map.insert(20u16, iface_zero.iface);
let mut list = super::list_ifaces(&iface_map).ifaces;
list.sort_by_key(|p| p.iface_id);
- assert_eq!(vec![
- IfaceListItem{ iface_id: 10u16, path: "/dev/null".to_string() },
- IfaceListItem{ iface_id: 20u16, path: "/dev/zero".to_string() },
- ], list)
+ assert_eq!(
+ vec![
+ IfaceListItem { iface_id: 10u16, path: "/dev/null".to_string() },
+ IfaceListItem { iface_id: 20u16, path: "/dev/zero".to_string() },
+ ],
+ list
+ )
}
#[test]
@@ -443,19 +455,18 @@
// Initiate a CreateIface request. The returned future should not be able
// to produce a result immediately
- let create_fut = super::create_iface(&phy_map, fidl_svc::CreateIfaceRequest {
- phy_id: 10,
- role: fidl_wlan_dev::MacRole::Client,
- });
+ let create_fut = super::create_iface(
+ &phy_map,
+ fidl_svc::CreateIfaceRequest { phy_id: 10, role: fidl_wlan_dev::MacRole::Client },
+ );
pin_mut!(create_fut);
assert_eq!(Poll::Pending, exec.run_until_stalled(&mut create_fut));
// The call above should trigger a CreateIface message to the phy.
// Pretend that we are the phy and read the message from the other side.
let (req, responder) = match exec.run_until_stalled(&mut phy_stream.next()) {
- Poll::Ready(Some(Ok(PhyRequest::CreateIface{ req, responder }))) =>
- (req, responder),
- _ => panic!("phy_stream returned unexpected result")
+ Poll::Ready(Some(Ok(PhyRequest::CreateIface { req, responder }))) => (req, responder),
+ _ => panic!("phy_stream returned unexpected result"),
};
// Since we requested the Client role, the request to the phy should also have
@@ -463,10 +474,9 @@
assert_eq!(fidl_wlan_dev::MacRole::Client, req.role);
// Pretend that we created an interface device with id 123 and send a response
- responder.send(&mut fidl_wlan_dev::CreateIfaceResponse {
- status: zx::sys::ZX_OK,
- iface_id: 123,
- }).expect("failed to send CreateIfaceResponse");
+ responder
+ .send(&mut fidl_wlan_dev::CreateIfaceResponse { status: zx::sys::ZX_OK, iface_id: 123 })
+ .expect("failed to send CreateIfaceResponse");
// Now, our original future should resolve into a response
let response = match exec.run_until_stalled(&mut create_fut) {
@@ -484,10 +494,10 @@
let (phy_map, _phy_map_events) = PhyMap::new();
let phy_map = Arc::new(phy_map);
- let fut = super::create_iface(&phy_map, fidl_svc::CreateIfaceRequest {
- phy_id: 10,
- role: fidl_wlan_dev::MacRole::Client,
- });
+ let fut = super::create_iface(
+ &phy_map,
+ fidl_svc::CreateIfaceRequest { phy_id: 10, role: fidl_wlan_dev::MacRole::Client },
+ );
pin_mut!(fut);
assert_eq!(Poll::Ready(Err(zx::Status::NOT_FOUND)), exec.run_until_stalled(&mut fut));
}
@@ -505,19 +515,21 @@
assert_eq!(zx::Status::OK, super::get_client_sme(&iface_map, 10, server));
// Expect to get a new FIDL client in the stream
- let endpoint = iface.new_sme_clients.try_next()
+ let endpoint = iface
+ .new_sme_clients
+ .try_next()
.expect("expected a message in new_sme_clients")
.expect("didn't expect new_sme_clients stream to end");
let mut sme_stream = endpoint.into_stream().expect("failed to create stream for endpoint");
// Verify that `proxy` is indeed connected to `sme_stream`
- let (_scan_proxy, scan_txn) = create_proxy()
- .expect("failed to create a pair of scan txn endpoints");
+ let (_scan_proxy, scan_txn) =
+ create_proxy().expect("failed to create a pair of scan txn endpoints");
proxy.scan(&mut fake_scan_request(), scan_txn).expect("failed to send a scan request");
let req = match exec.run_until_stalled(&mut sme_stream.next()) {
- Poll::Ready(Some(Ok(fidl_sme::ClientSmeRequest::Scan{ req, .. }))) => req,
- _ => panic!("sme_stream returned unexpected result")
+ Poll::Ready(Some(Ok(fidl_sme::ClientSmeRequest::Scan { req, .. }))) => req,
+ _ => panic!("sme_stream returned unexpected result"),
};
assert_eq!(fake_scan_request(), req);
}
@@ -558,7 +570,9 @@
assert_eq!(zx::Status::OK, super::get_ap_sme(&iface_map, 10, server));
// Expect to get a new FIDL client in the stream
- let endpoint = iface.new_sme_clients.try_next()
+ let endpoint = iface
+ .new_sme_clients
+ .try_next()
.expect("expected a message in new_sme_clients")
.expect("didn't expect new_sme_clients stream to end");
let mut sme_stream = endpoint.into_stream().expect("failed to create stream for endpoint");
@@ -569,13 +583,14 @@
match exec.run_until_stalled(&mut sme_stream.next()) {
Poll::Ready(Some(Ok(fidl_sme::ApSmeRequest::Start { config, responder }))) => {
assert_eq!(fake_ap_config(), config);
- responder.send(fidl_sme::StartApResultCode::Success)
- .expect("failed to send response");
- },
- _ => panic!("sme_stream returned unexpected result")
+ responder
+ .send(fidl_sme::StartApResultCode::Success)
+ .expect("failed to send response");
+ }
+ _ => panic!("sme_stream returned unexpected result"),
};
match exec.run_until_stalled(&mut fut) {
- Poll::Ready(Ok(fidl_sme::StartApResultCode::Success)) => {},
+ Poll::Ready(Ok(fidl_sme::StartApResultCode::Success)) => {}
other => panic!("expected a successful response, got {:?}", other),
}
}
@@ -604,9 +619,10 @@
}
fn fake_phy(path: &str) -> (PhyDevice, PhyRequestStream) {
- let (proxy, server) = create_proxy::<fidl_wlan_dev::PhyMarker>()
- .expect("fake_phy: create_proxy() failed");
- let device = wlan_dev::Device::new(path).expect(&format!("fake_phy: failed to open {}", path));
+ let (proxy, server) =
+ create_proxy::<fidl_wlan_dev::PhyMarker>().expect("fake_phy: create_proxy() failed");
+ let device =
+ wlan_dev::Device::new(path).expect(&format!("fake_phy: failed to open {}", path));
let stream = server.into_stream().expect("fake_phy: failed to create stream");
(PhyDevice { proxy, device }, stream)
}
@@ -632,11 +648,7 @@
mlme_query,
device_info,
};
- FakeClientIface {
- iface,
- _stats_requests: stats_requests,
- new_sme_clients: sme_receiver,
- }
+ FakeClientIface { iface, _stats_requests: stats_requests, new_sme_clients: sme_receiver }
}
struct FakeApIface<St: Stream<Item = StatsRequest>> {
@@ -660,18 +672,14 @@
mlme_query,
device_info,
};
- FakeApIface {
- iface,
- _stats_requests: stats_requests,
- new_sme_clients: sme_receiver
- }
+ FakeApIface { iface, _stats_requests: stats_requests, new_sme_clients: sme_receiver }
}
fn fake_phy_info() -> fidl_wlan_dev::PhyInfo {
fidl_wlan_dev::PhyInfo {
id: 10,
dev_path: Some("/dev/null".to_string()),
- hw_mac_address: [ 0x67, 0x62, 0x6f, 0x6e, 0x69, 0x6b ],
+ hw_mac_address: [0x67, 0x62, 0x6f, 0x6e, 0x69, 0x6b],
supported_phys: Vec::new(),
driver_features: Vec::new(),
mac_roles: Vec::new(),
@@ -684,22 +692,15 @@
fidl_mlme::DeviceInfo {
role: fidl_mlme::MacRole::Client,
bands: vec![],
- mac_addr: [ 0xAC; 6 ],
+ mac_addr: [0xAC; 6],
}
}
fn fake_scan_request() -> fidl_sme::ScanRequest {
- fidl_sme::ScanRequest{
- timeout: 41,
- scan_type: fidl_common::ScanType::Passive,
- }
+ fidl_sme::ScanRequest { timeout: 41, scan_type: fidl_common::ScanType::Passive }
}
fn fake_ap_config() -> fidl_sme::ApConfig {
- fidl_sme::ApConfig {
- ssid: b"qwerty".to_vec(),
- password: vec![],
- channel: 6,
- }
+ fidl_sme::ApConfig { ssid: b"qwerty".to_vec(), password: vec![], channel: 6 }
}
}
diff --git a/bin/wlan/wlanstack/src/station/ap.rs b/bin/wlan/wlanstack/src/station/ap.rs
index 06ec126..8206607 100644
--- a/bin/wlan/wlanstack/src/station/ap.rs
+++ b/bin/wlan/wlanstack/src/station/ap.rs
@@ -5,34 +5,42 @@
use failure::bail;
use fidl_fuchsia_wlan_mlme::{MlmeEventStream, MlmeProxy};
use fidl_fuchsia_wlan_sme as fidl_sme;
-use futures::{select, Stream};
use futures::channel::mpsc;
use futures::prelude::*;
use futures::stream::FuturesUnordered;
+use futures::{select, Stream};
use log::error;
use pin_utils::pin_mut;
use std::marker::Unpin;
use std::sync::{Arc, Mutex};
use wlan_sme::{ap as ap_sme, DeviceInfo};
-use crate::Never;
use crate::stats_scheduler::StatsRequest;
+use crate::Never;
pub type Endpoint = fidl::endpoints::ServerEnd<fidl_sme::ApSmeMarker>;
type Sme = ap_sme::ApSme;
-pub async fn serve<S>(proxy: MlmeProxy,
- device_info: DeviceInfo,
- event_stream: MlmeEventStream,
- new_fidl_clients: mpsc::UnboundedReceiver<Endpoint>,
- stats_requests: S)
- -> Result<(), failure::Error>
- where S: Stream<Item = StatsRequest> + Send + Unpin
+pub async fn serve<S>(
+ proxy: MlmeProxy,
+ device_info: DeviceInfo,
+ event_stream: MlmeEventStream,
+ new_fidl_clients: mpsc::UnboundedReceiver<Endpoint>,
+ stats_requests: S,
+) -> Result<(), failure::Error>
+where
+ S: Stream<Item = StatsRequest> + Send + Unpin,
{
let (sme, mlme_stream, time_stream) = Sme::new(device_info);
let sme = Arc::new(Mutex::new(sme));
let mlme_sme = super::serve_mlme_sme(
- proxy, event_stream, Arc::clone(&sme), mlme_stream, stats_requests, time_stream);
+ proxy,
+ event_stream,
+ Arc::clone(&sme),
+ mlme_stream,
+ stats_requests,
+ time_stream,
+ );
let sme_fidl = serve_fidl(&sme, new_fidl_clients);
pin_mut!(mlme_sme);
pin_mut!(sme_fidl);
@@ -43,10 +51,10 @@
Ok(())
}
-async fn serve_fidl(sme: &Mutex<Sme>,
- new_fidl_clients: mpsc::UnboundedReceiver<Endpoint>)
- -> Result<Never, failure::Error>
-{
+async fn serve_fidl(
+ sme: &Mutex<Sme>,
+ new_fidl_clients: mpsc::UnboundedReceiver<Endpoint>,
+) -> Result<Never, failure::Error> {
let mut new_fidl_clients = new_fidl_clients.fuse();
let mut fidl_clients = FuturesUnordered::new();
loop {
@@ -77,14 +85,15 @@
}
}
-async fn handle_fidl_request(sme: &Mutex<Sme>, request: fidl_sme::ApSmeRequest)
- -> Result<(), ::fidl::Error>
-{
+async fn handle_fidl_request(
+ sme: &Mutex<Sme>,
+ request: fidl_sme::ApSmeRequest,
+) -> Result<(), ::fidl::Error> {
match request {
fidl_sme::ApSmeRequest::Start { config, responder } => {
let r = await!(start(sme, config));
responder.send(r)?;
- },
+ }
fidl_sme::ApSmeRequest::Stop { responder } => {
await!(stop(sme));
responder.send()?;
@@ -94,11 +103,8 @@
}
async fn start(sme: &Mutex<Sme>, config: fidl_sme::ApConfig) -> fidl_sme::StartApResultCode {
- let sme_config = ap_sme::Config {
- ssid: config.ssid,
- password: config.password,
- channel: config.channel,
- };
+ let sme_config =
+ ap_sme::Config { ssid: config.ssid, password: config.password, channel: config.channel };
let receiver = sme.lock().unwrap().on_start_command(sme_config);
let r = await!(receiver).unwrap_or_else(|_| {
@@ -115,8 +121,9 @@
ap_sme::StartResult::InternalError => fidl_sme::StartApResultCode::InternalError,
ap_sme::StartResult::Canceled => fidl_sme::StartApResultCode::Canceled,
ap_sme::StartResult::TimedOut => fidl_sme::StartApResultCode::TimedOut,
- ap_sme::StartResult::PreviousStartInProgress =>
- fidl_sme::StartApResultCode::PreviousStartInProgress,
+ ap_sme::StartResult::PreviousStartInProgress => {
+ fidl_sme::StartApResultCode::PreviousStartInProgress
+ }
ap_sme::StartResult::InvalidArguments => fidl_sme::StartApResultCode::InvalidArguments,
ap_sme::StartResult::DfsUnsupported => fidl_sme::StartApResultCode::DfsUnsupported,
}
diff --git a/bin/wlan/wlanstack/src/station/client.rs b/bin/wlan/wlanstack/src/station/client.rs
index 4bd0020..5232b5a 100644
--- a/bin/wlan/wlanstack/src/station/client.rs
+++ b/bin/wlan/wlanstack/src/station/client.rs
@@ -7,22 +7,24 @@
use fidl_fuchsia_wlan_common as fidl_common;
use fidl_fuchsia_wlan_mlme::{MlmeEventStream, MlmeProxy};
use fidl_fuchsia_wlan_sme::{self as fidl_sme, ClientSmeRequest};
-use futures::{prelude::*, select, stream::FuturesUnordered};
+use fuchsia_zircon as zx;
use futures::channel::mpsc;
+use futures::{prelude::*, select, stream::FuturesUnordered};
use log::{error, info};
use pin_utils::pin_mut;
use std::marker::Unpin;
use std::sync::{Arc, Mutex};
+use wlan_sme::client::{
+ BssInfo, ConnectResult, ConnectionAttemptId, DiscoveryError, EssDiscoveryResult, EssInfo,
+ InfoEvent, ScanTxnId,
+};
use wlan_sme::{client as client_sme, DeviceInfo, InfoStream};
-use wlan_sme::client::{BssInfo, ConnectionAttemptId, ConnectResult, DiscoveryError,
- EssDiscoveryResult, EssInfo, InfoEvent, ScanTxnId};
-use fuchsia_zircon as zx;
-use fuchsia_cobalt::CobaltSender;
use crate::fidl_util::is_peer_closed;
-use crate::Never;
use crate::stats_scheduler::StatsRequest;
use crate::telemetry;
+use crate::Never;
+use fuchsia_cobalt::CobaltSender;
pub type Endpoint = ServerEnd<fidl_sme::ClientSmeMarker>;
type Sme = client_sme::ClientSme;
@@ -36,19 +38,27 @@
rsna_started_time: Option<zx::Time>,
}
-pub async fn serve<S>(proxy: MlmeProxy,
- device_info: DeviceInfo,
- event_stream: MlmeEventStream,
- new_fidl_clients: mpsc::UnboundedReceiver<Endpoint>,
- stats_requests: S,
- cobalt_sender: CobaltSender)
- -> Result<(), failure::Error>
- where S: Stream<Item = StatsRequest> + Unpin
+pub async fn serve<S>(
+ proxy: MlmeProxy,
+ device_info: DeviceInfo,
+ event_stream: MlmeEventStream,
+ new_fidl_clients: mpsc::UnboundedReceiver<Endpoint>,
+ stats_requests: S,
+ cobalt_sender: CobaltSender,
+) -> Result<(), failure::Error>
+where
+ S: Stream<Item = StatsRequest> + Unpin,
{
let (sme, mlme_stream, info_stream, time_stream) = Sme::new(device_info);
let sme = Arc::new(Mutex::new(sme));
let mlme_sme = super::serve_mlme_sme(
- proxy, event_stream, Arc::clone(&sme), mlme_stream, stats_requests, time_stream);
+ proxy,
+ event_stream,
+ Arc::clone(&sme),
+ mlme_stream,
+ stats_requests,
+ time_stream,
+ );
let sme_fidl = serve_fidl(sme, new_fidl_clients, info_stream, cobalt_sender);
pin_mut!(mlme_sme);
pin_mut!(sme_fidl);
@@ -58,21 +68,23 @@
})
}
-async fn serve_fidl(sme: Arc<Mutex<Sme>>,
- new_fidl_clients: mpsc::UnboundedReceiver<Endpoint>,
- info_stream: InfoStream,
- mut cobalt_sender: CobaltSender)
- -> Result<Never, failure::Error>
-{
+async fn serve_fidl(
+ sme: Arc<Mutex<Sme>>,
+ new_fidl_clients: mpsc::UnboundedReceiver<Endpoint>,
+ info_stream: InfoStream,
+ mut cobalt_sender: CobaltSender,
+) -> Result<Never, failure::Error> {
let mut new_fidl_clients = new_fidl_clients.fuse();
let mut info_stream = info_stream.fuse();
let mut fidl_clients = FuturesUnordered::new();
- let mut connection_times = ConnectionTimes { att_id: 0,
- txn_id: 0,
- connect_started_time: None,
- scan_started_time: None,
- assoc_started_time: None,
- rsna_started_time: None };
+ let mut connection_times = ConnectionTimes {
+ att_id: 0,
+ txn_id: 0,
+ connect_started_time: None,
+ scan_started_time: None,
+ assoc_started_time: None,
+ rsna_started_time: None,
+ };
loop {
select! {
info_event = info_stream.next() => match info_event {
@@ -106,18 +118,15 @@
}
}
-async fn handle_fidl_request(sme: &Mutex<Sme>, request: fidl_sme::ClientSmeRequest)
- -> Result<(), fidl::Error>
-{
+async fn handle_fidl_request(
+ sme: &Mutex<Sme>,
+ request: fidl_sme::ClientSmeRequest,
+) -> Result<(), fidl::Error> {
match request {
- ClientSmeRequest::Scan { req, txn, .. } => {
- Ok(await!(scan(sme, txn, req.scan_type))
- .unwrap_or_else(|e| error!("Error handling a scan transaction: {:?}", e)))
- },
- ClientSmeRequest::Connect { req, txn, .. } => {
- Ok(await!(connect(sme, txn, req))
- .unwrap_or_else(|e| error!("Error handling a connect transaction: {:?}", e)))
- },
+ ClientSmeRequest::Scan { req, txn, .. } => Ok(await!(scan(sme, txn, req.scan_type))
+ .unwrap_or_else(|e| error!("Error handling a scan transaction: {:?}", e))),
+ ClientSmeRequest::Connect { req, txn, .. } => Ok(await!(connect(sme, txn, req))
+ .unwrap_or_else(|e| error!("Error handling a connect transaction: {:?}", e))),
ClientSmeRequest::Disconnect { responder } => {
disconnect(sme);
responder.send()
@@ -126,10 +135,11 @@
}
}
-async fn scan(sme: &Mutex<Sme>, txn: ServerEnd<fidl_sme::ScanTransactionMarker>,
- scan_type: fidl_common::ScanType)
- -> Result<(), failure::Error>
-{
+async fn scan(
+ sme: &Mutex<Sme>,
+ txn: ServerEnd<fidl_sme::ScanTransactionMarker>,
+ scan_type: fidl_common::ScanType,
+) -> Result<(), failure::Error> {
let handle = txn.into_stream()?.control_handle();
let receiver = sme.lock().unwrap().on_scan_command(scan_type);
let result = await!(receiver).unwrap_or(Err(DiscoveryError::InternalError));
@@ -138,14 +148,14 @@
Ok(())
}
-async fn connect(sme: &Mutex<Sme>,
- txn: Option<ServerEnd<fidl_sme::ConnectTransactionMarker>>,
- req: fidl_sme::ConnectRequest)
- -> Result<(), failure::Error>
-{
+async fn connect(
+ sme: &Mutex<Sme>,
+ txn: Option<ServerEnd<fidl_sme::ConnectTransactionMarker>>,
+ req: fidl_sme::ConnectRequest,
+) -> Result<(), failure::Error> {
let handle = match txn {
None => None,
- Some(txn) => Some(txn.into_stream()?.control_handle())
+ Some(txn) => Some(txn.into_stream()?.control_handle()),
};
let receiver = sme.lock().unwrap().on_connect_command(req);
let result = await!(receiver).unwrap_or(ConnectResult::Failed);
@@ -168,9 +178,7 @@
fn status(sme: &Mutex<Sme>) -> fidl_sme::ClientStatusResponse {
let status = sme.lock().unwrap().status();
fidl_sme::ClientStatusResponse {
- connected_to: status.connected_to.map(|bss| {
- Box::new(convert_bss_info(bss))
- }),
+ connected_to: status.connected_to.map(|bss| Box::new(convert_bss_info(bss))),
connecting_to_ssid: status.connecting_to.unwrap_or(Vec::new()),
}
}
@@ -183,62 +191,74 @@
return false;
}
-fn handle_info_event(e: InfoEvent,
- cobalt_sender: &mut CobaltSender,
- connection_times: &mut ConnectionTimes,
+fn handle_info_event(
+ e: InfoEvent,
+ cobalt_sender: &mut CobaltSender,
+ connection_times: &mut ConnectionTimes,
) {
match e {
InfoEvent::ConnectStarted => {
connection_times.connect_started_time = Some(zx::Time::get(zx::ClockId::Monotonic));
- },
+ }
InfoEvent::ConnectFinished { result, failure } => {
if let Some(connect_started_time) = connection_times.connect_started_time {
let connection_finished_time = zx::Time::get(zx::ClockId::Monotonic);
- telemetry::report_connection_delay(cobalt_sender, connect_started_time,
- connection_finished_time, &result, &failure);
+ telemetry::report_connection_delay(
+ cobalt_sender,
+ connect_started_time,
+ connection_finished_time,
+ &result,
+ &failure,
+ );
connection_times.connect_started_time = None;
}
- },
+ }
InfoEvent::MlmeScanStart { txn_id } => {
connection_times.txn_id = txn_id;
connection_times.scan_started_time = Some(zx::Time::get(zx::ClockId::Monotonic));
- },
+ }
InfoEvent::MlmeScanEnd { txn_id } => {
if id_mismatch(txn_id, connection_times.txn_id, "ScanTxnId") {
return;
}
if let Some(scan_started_time) = connection_times.scan_started_time {
let scan_finished_time = zx::Time::get(zx::ClockId::Monotonic);
- telemetry::report_scan_delay(cobalt_sender, scan_started_time,
- scan_finished_time);
+ telemetry::report_scan_delay(cobalt_sender, scan_started_time, scan_finished_time);
connection_times.scan_started_time = None;
}
- },
- InfoEvent::ScanDiscoveryFinished { bss_count, ess_count,
- num_bss_by_standard, num_bss_by_channel } => {
+ }
+ InfoEvent::ScanDiscoveryFinished {
+ bss_count,
+ ess_count,
+ num_bss_by_standard,
+ num_bss_by_channel,
+ } => {
telemetry::report_neighbor_networks_count(cobalt_sender, bss_count, ess_count);
telemetry::report_standards(cobalt_sender, num_bss_by_standard);
telemetry::report_channels(cobalt_sender, num_bss_by_channel);
- },
+ }
InfoEvent::AssociationStarted { att_id } => {
connection_times.att_id = att_id;
connection_times.assoc_started_time = Some(zx::Time::get(zx::ClockId::Monotonic));
- },
+ }
InfoEvent::AssociationSuccess { att_id } => {
if id_mismatch(att_id, connection_times.att_id, "ConnectionAttemptId") {
return;
}
if let Some(assoc_started_time) = connection_times.assoc_started_time {
let assoc_finished_time = zx::Time::get(zx::ClockId::Monotonic);
- telemetry::report_assoc_success_delay(cobalt_sender, assoc_started_time,
- assoc_finished_time);
+ telemetry::report_assoc_success_delay(
+ cobalt_sender,
+ assoc_started_time,
+ assoc_finished_time,
+ );
connection_times.assoc_started_time = None;
}
- },
+ }
InfoEvent::RsnaStarted { att_id } => {
connection_times.att_id = att_id;
connection_times.rsna_started_time = Some(zx::Time::get(zx::ClockId::Monotonic));
- },
+ }
InfoEvent::RsnaEstablished { att_id } => {
if id_mismatch(att_id, connection_times.att_id, "ConnectionAttemptId") {
return;
@@ -247,31 +267,35 @@
None => info!("Received UserEvent.RsnaEstablished before UserEvent.RsnaStarted"),
Some(rsna_started_time) => {
let rsna_finished_time = zx::Time::get(zx::ClockId::Monotonic);
- telemetry::report_rsna_established_delay(cobalt_sender, rsna_started_time,
- rsna_finished_time);
+ telemetry::report_rsna_established_delay(
+ cobalt_sender,
+ rsna_started_time,
+ rsna_finished_time,
+ );
connection_times.rsna_started_time = None;
}
}
- },
+ }
}
}
-fn send_scan_results(handle: fidl_sme::ScanTransactionControlHandle,
- result: EssDiscoveryResult) -> Result<(), fidl::Error>
-{
+fn send_scan_results(
+ handle: fidl_sme::ScanTransactionControlHandle,
+ result: EssDiscoveryResult,
+) -> Result<(), fidl::Error> {
match result {
Ok(ess_list) => {
let mut fidl_list = ess_list.into_iter().map(convert_ess_info).collect::<Vec<_>>();
handle.send_on_result(&mut fidl_list.iter_mut())?;
handle.send_on_finished()?;
- },
+ }
Err(e) => {
let mut fidl_err = fidl_sme::ScanError {
code: match e {
DiscoveryError::NotSupported => fidl_sme::ScanErrorCode::NotSupported,
DiscoveryError::InternalError => fidl_sme::ScanErrorCode::InternalError,
},
- message: e.to_string()
+ message: e.to_string(),
};
handle.send_on_error(&mut fidl_err)?;
}
@@ -280,9 +304,7 @@
}
fn convert_ess_info(ess: EssInfo) -> fidl_sme::EssInfo {
- fidl_sme::EssInfo {
- best_bss: convert_bss_info(ess.best_bss),
- }
+ fidl_sme::EssInfo { best_bss: convert_bss_info(ess.best_bss) }
}
fn convert_bss_info(bss: BssInfo) -> fidl_sme::BssInfo {
@@ -292,14 +314,14 @@
rx_dbm: bss.rx_dbm,
channel: bss.channel,
protected: bss.protected,
- compatible: bss.compatible
+ compatible: bss.compatible,
}
}
-fn send_connect_result(handle: Option<fidl_sme::ConnectTransactionControlHandle>,
- result: ConnectResult)
- -> Result<(), fidl::Error>
-{
+fn send_connect_result(
+ handle: Option<fidl_sme::ConnectTransactionControlHandle>,
+ result: ConnectResult,
+) -> Result<(), fidl::Error> {
if let Some(handle) = handle {
let code = match result {
ConnectResult::Success => fidl_sme::ConnectResultCode::Success,
@@ -311,4 +333,3 @@
}
Ok(())
}
-
diff --git a/bin/wlan/wlanstack/src/station/mesh.rs b/bin/wlan/wlanstack/src/station/mesh.rs
index 18ae775..84a5e76 100644
--- a/bin/wlan/wlanstack/src/station/mesh.rs
+++ b/bin/wlan/wlanstack/src/station/mesh.rs
@@ -3,15 +3,16 @@
// found in the LICENSE file.
use {
+ crate::{stats_scheduler::StatsRequest, Never},
failure::bail,
fidl_fuchsia_wlan_mlme::{MlmeEventStream, MlmeProxy},
fidl_fuchsia_wlan_sme as fidl_sme,
futures::{
channel::mpsc,
- Poll,
prelude::*,
select,
stream::{self, FuturesUnordered},
+ Poll,
},
log::error,
pin_utils::pin_mut,
@@ -19,33 +20,33 @@
marker::Unpin,
sync::{Arc, Mutex},
},
- wlan_sme::{
- DeviceInfo,
- mesh as mesh_sme,
- timer::TimeEntry,
- },
- crate::{
- Never,
- stats_scheduler::StatsRequest,
- },
+ wlan_sme::{mesh as mesh_sme, timer::TimeEntry, DeviceInfo},
};
pub type Endpoint = fidl::endpoints::ServerEnd<fidl_sme::MeshSmeMarker>;
type Sme = mesh_sme::MeshSme;
-pub async fn serve<S>(proxy: MlmeProxy,
- device_info: DeviceInfo,
- event_stream: MlmeEventStream,
- new_fidl_clients: mpsc::UnboundedReceiver<Endpoint>,
- stats_requests: S)
- -> Result<(), failure::Error>
- where S: Stream<Item = StatsRequest> + Send + Unpin
+pub async fn serve<S>(
+ proxy: MlmeProxy,
+ device_info: DeviceInfo,
+ event_stream: MlmeEventStream,
+ new_fidl_clients: mpsc::UnboundedReceiver<Endpoint>,
+ stats_requests: S,
+) -> Result<(), failure::Error>
+where
+ S: Stream<Item = StatsRequest> + Send + Unpin,
{
let (sme, mlme_stream) = Sme::new(device_info);
let sme = Arc::new(Mutex::new(sme));
let time_stream = stream::poll_fn::<TimeEntry<()>, _>(|_| Poll::Pending);
let mlme_sme = super::serve_mlme_sme(
- proxy, event_stream, Arc::clone(&sme), mlme_stream, stats_requests, time_stream);
+ proxy,
+ event_stream,
+ Arc::clone(&sme),
+ mlme_stream,
+ stats_requests,
+ time_stream,
+ );
let sme_fidl = serve_fidl(&sme, new_fidl_clients);
pin_mut!(mlme_sme);
pin_mut!(sme_fidl);
@@ -56,10 +57,10 @@
Ok(())
}
-async fn serve_fidl(sme: &Mutex<Sme>,
- new_fidl_clients: mpsc::UnboundedReceiver<Endpoint>)
- -> Result<Never, failure::Error>
-{
+async fn serve_fidl(
+ sme: &Mutex<Sme>,
+ new_fidl_clients: mpsc::UnboundedReceiver<Endpoint>,
+) -> Result<Never, failure::Error> {
let mut fidl_clients = FuturesUnordered::new();
let mut new_fidl_clients = new_fidl_clients.fuse();
loop {
@@ -91,28 +92,27 @@
}
}
-async fn handle_fidl_request(sme: &Mutex<Sme>, request: fidl_sme::MeshSmeRequest)
- -> Result<(), ::fidl::Error>
-{
+async fn handle_fidl_request(
+ sme: &Mutex<Sme>,
+ request: fidl_sme::MeshSmeRequest,
+) -> Result<(), ::fidl::Error> {
match request {
fidl_sme::MeshSmeRequest::Join { config, responder } => {
let code = await!(join_mesh(sme, config));
responder.send(code)
- },
+ }
fidl_sme::MeshSmeRequest::Leave { responder } => {
let code = await!(leave_mesh(sme));
responder.send(code)
- },
+ }
}
}
-async fn join_mesh(sme: &Mutex<Sme>, config: fidl_sme::MeshConfig)
- -> fidl_sme::JoinMeshResultCode
-{
- let receiver = sme.lock().unwrap().on_join_command(mesh_sme::Config {
- mesh_id: config.mesh_id,
- channel: config.channel,
- });
+async fn join_mesh(sme: &Mutex<Sme>, config: fidl_sme::MeshConfig) -> fidl_sme::JoinMeshResultCode {
+ let receiver = sme
+ .lock()
+ .unwrap()
+ .on_join_command(mesh_sme::Config { mesh_id: config.mesh_id, channel: config.channel });
let r = await!(receiver).unwrap_or_else(|_| {
error!("Responder for Join Mesh command was dropped without sending a response");
mesh_sme::JoinMeshResult::InternalError
@@ -125,7 +125,9 @@
mesh_sme::JoinMeshResult::Success => fidl_sme::JoinMeshResultCode::Success,
mesh_sme::JoinMeshResult::Canceled => fidl_sme::JoinMeshResultCode::Canceled,
mesh_sme::JoinMeshResult::InternalError => fidl_sme::JoinMeshResultCode::InternalError,
- mesh_sme::JoinMeshResult::InvalidArguments => fidl_sme::JoinMeshResultCode::InvalidArguments,
+ mesh_sme::JoinMeshResult::InvalidArguments => {
+ fidl_sme::JoinMeshResultCode::InvalidArguments
+ }
mesh_sme::JoinMeshResult::DfsUnsupported => fidl_sme::JoinMeshResultCode::DfsUnsupported,
}
}
diff --git a/bin/wlan/wlanstack/src/station/mod.rs b/bin/wlan/wlanstack/src/station/mod.rs
index 0a6c1de..d60dc5e 100644
--- a/bin/wlan/wlanstack/src/station/mod.rs
+++ b/bin/wlan/wlanstack/src/station/mod.rs
@@ -17,20 +17,28 @@
use pin_utils::pin_mut;
use std::marker::Unpin;
use std::sync::{Arc, Mutex};
-use wlan_sme::{Station, MlmeRequest, MlmeStream, timer::{TimeEntry, TimedEvent}};
+use wlan_sme::{
+ timer::{TimeEntry, TimedEvent},
+ MlmeRequest, MlmeStream, Station,
+};
use crate::fidl_util::is_peer_closed;
-use crate::Never;
use crate::stats_scheduler::StatsRequest;
+use crate::Never;
// The returned future successfully terminates when MLME closes the channel
-async fn serve_mlme_sme<STA, SRS, TS>(proxy: MlmeProxy, mut event_stream: MlmeEventStream,
- station: Arc<Mutex<STA>>, mut mlme_stream: MlmeStream,
- stats_requests: SRS, time_stream: TS)
- -> Result<(), failure::Error>
- where STA: Station,
- SRS: Stream<Item = StatsRequest> + Unpin,
- TS: Stream<Item = TimeEntry<<STA as wlan_sme::Station>::Event>> + Unpin,
+async fn serve_mlme_sme<STA, SRS, TS>(
+ proxy: MlmeProxy,
+ mut event_stream: MlmeEventStream,
+ station: Arc<Mutex<STA>>,
+ mut mlme_stream: MlmeStream,
+ stats_requests: SRS,
+ time_stream: TS,
+) -> Result<(), failure::Error>
+where
+ STA: Station,
+ SRS: Stream<Item = StatsRequest> + Unpin,
+ TS: Stream<Item = TimeEntry<<STA as wlan_sme::Station>::Event>> + Unpin,
{
let (mut stats_sender, stats_receiver) = mpsc::channel(1);
let stats_fut = serve_stats(proxy.clone(), stats_requests, stats_receiver);
@@ -69,9 +77,9 @@
}
}
-fn make_timer_stream<E>(time_stream: impl Stream<Item = TimeEntry<E>>)
- -> impl Stream<Item = TimedEvent<E>> {
-
+fn make_timer_stream<E>(
+ time_stream: impl Stream<Item = TimeEntry<E>>,
+) -> impl Stream<Item = TimedEvent<E>> {
time_stream
.map(|(deadline, timed_event)| fasync::Timer::new(deadline).map(|_| timed_event))
.buffer_unordered(usize::max_value())
@@ -97,8 +105,10 @@
}
}
-fn handle_stats_resp(stats_sender: &mut mpsc::Sender<IfaceStats>,
- resp: fidl_mlme::StatsQueryResponse) -> Result<(), failure::Error> {
+fn handle_stats_resp(
+ stats_sender: &mut mpsc::Sender<IfaceStats>,
+ resp: fidl_mlme::StatsQueryResponse,
+) -> Result<(), failure::Error> {
stats_sender.try_send(resp.stats).or_else(|e| {
if e.is_full() {
// We only expect one response from MLME per each request, so the bounded
@@ -111,14 +121,18 @@
})
}
-async fn serve_stats<S>(proxy: MlmeProxy, mut stats_requests: S,
- mut responses: mpsc::Receiver<IfaceStats>)
- -> Result<Never, failure::Error>
- where S: Stream<Item = StatsRequest> + Unpin
+async fn serve_stats<S>(
+ proxy: MlmeProxy,
+ mut stats_requests: S,
+ mut responses: mpsc::Receiver<IfaceStats>,
+) -> Result<Never, failure::Error>
+where
+ S: Stream<Item = StatsRequest> + Unpin,
{
while let Some(req) = await!(stats_requests.next()) {
- proxy.stats_query_req().map_err(
- |e| format_err!("Failed to send a StatsReq to MLME: {}", e))?;
+ proxy
+ .stats_query_req()
+ .map_err(|e| format_err!("Failed to send a StatsReq to MLME: {}", e))?;
match await!(responses.next()) {
Some(response) => req.reply(response),
None => bail!("Stream of stats responses has ended unexpectedly"),
@@ -133,8 +147,8 @@
use {
fuchsia_zircon::{self as zx, prelude::DurationNum},
futures::channel::mpsc::{self, UnboundedSender},
- pin_utils::pin_mut,
futures::Poll,
+ pin_utils::pin_mut,
};
type Event = u32;
diff --git a/bin/wlan/wlanstack/src/stats_scheduler.rs b/bin/wlan/wlanstack/src/stats_scheduler.rs
index 76294ab..a019e87 100644
--- a/bin/wlan/wlanstack/src/stats_scheduler.rs
+++ b/bin/wlan/wlanstack/src/stats_scheduler.rs
@@ -4,7 +4,7 @@
use fidl_fuchsia_wlan_stats::IfaceStats;
use fuchsia_zircon as zx;
-use futures::channel::{oneshot, mpsc};
+use futures::channel::{mpsc, oneshot};
use futures::prelude::*;
use parking_lot::Mutex;
use std::sync::Arc;
@@ -19,25 +19,22 @@
type Responder = oneshot::Sender<StatsRef>;
pub struct StatsScheduler {
- queue: mpsc::UnboundedSender<Responder>
+ queue: mpsc::UnboundedSender<Responder>,
}
-pub fn create_scheduler()
- -> (StatsScheduler, impl Stream<Item = StatsRequest>)
-{
+pub fn create_scheduler() -> (StatsScheduler, impl Stream<Item = StatsRequest>) {
let (sender, receiver) = mpsc::unbounded();
- let scheduler = StatsScheduler{ queue: sender };
+ let scheduler = StatsScheduler { queue: sender };
let req_stream = receiver
- .map(Ok).group_available()
+ .map(Ok)
+ .group_available()
.map_ok(StatsRequest)
.map(|x| x.unwrap_or_else(Never::into_any));
(scheduler, req_stream)
}
impl StatsScheduler {
- pub fn get_stats(&self)
- -> impl Future<Output = Result<StatsRef, zx::Status>>
- {
+ pub fn get_stats(&self) -> impl Future<Output = Result<StatsRef, zx::Status>> {
let (sender, receiver) = oneshot::channel();
// Ignore the error: if the other side is closed, `sender` will be immediately
// dropped, and `receiver` will be notified
@@ -83,14 +80,14 @@
match res1 {
Poll::Ready(Ok(r)) => assert_eq!(fake_iface_stats(100), *r.lock()),
Poll::Ready(Err(e)) => panic!("request future 1 returned an error: {:?}", e),
- Poll::Pending => panic!("request future 1 returned 'Pending'")
+ Poll::Pending => panic!("request future 1 returned 'Pending'"),
}
let res2 = exec.run_until_stalled(&mut fut2);
match res2 {
Poll::Ready(Ok(r)) => assert_eq!(fake_iface_stats(100), *r.lock()),
Poll::Ready(Err(e)) => panic!("request future 2 returned an error: {:?}", e),
- Poll::Pending => panic!("request future 2 returned 'Pending'")
+ Poll::Pending => panic!("request future 2 returned 'Pending'"),
}
let mut fut3 = sched.get_stats();
@@ -99,7 +96,7 @@
match res3 {
Poll::Ready(Ok(r)) => assert_eq!(fake_iface_stats(200), *r.lock()),
Poll::Ready(Err(e)) => panic!("request future 3 returned an error: {:?}", e),
- Poll::Pending => panic!("request future 3 returned 'Pending'")
+ Poll::Pending => panic!("request future 3 returned 'Pending'"),
}
}
@@ -161,10 +158,7 @@
}
fn fake_counter(count: u64) -> Counter {
- Counter {
- count: count,
- name: "foo".to_string(),
- }
+ Counter { count: count, name: "foo".to_string() }
}
}
diff --git a/bin/wlan/wlanstack/src/telemetry.rs b/bin/wlan/wlanstack/src/telemetry.rs
index 6418abb..b981587 100644
--- a/bin/wlan/wlanstack/src/telemetry.rs
+++ b/bin/wlan/wlanstack/src/telemetry.rs
@@ -3,8 +3,9 @@
// found in the LICENSE file.
use fidl_fuchsia_cobalt::HistogramBucket;
-use fidl_fuchsia_wlan_mlme::{AssociateResultCodes, AuthenticateResultCodes,
- JoinResultCodes, ScanResultCodes};
+use fidl_fuchsia_wlan_mlme::{
+ AssociateResultCodes, AuthenticateResultCodes, JoinResultCodes, ScanResultCodes,
+};
use fidl_fuchsia_wlan_stats as fidl_stats;
use fidl_fuchsia_wlan_stats::MlmeStats::{ApMlmeStats, ClientMlmeStats};
use fuchsia_async as fasync;
@@ -16,15 +17,15 @@
use log::error;
use parking_lot::Mutex;
use std::cmp::PartialOrd;
-use std::collections::HashMap;
use std::collections::hash_map::Entry;
+use std::collections::HashMap;
use std::default::Default;
use std::ops::Sub;
use std::sync::Arc;
use wlan_sme::client::{ConnectFailure, ConnectResult, Standard};
-use fuchsia_cobalt::CobaltSender;
use crate::device::IfaceMap;
+use fuchsia_cobalt::CobaltSender;
type StatsRef = Arc<Mutex<fidl_stats::IfaceStats>>;
@@ -87,20 +88,18 @@
}
fn report_stats(
- last_stats: &fidl_stats::IfaceStats, current_stats: &fidl_stats::IfaceStats,
+ last_stats: &fidl_stats::IfaceStats,
+ current_stats: &fidl_stats::IfaceStats,
sender: &mut CobaltSender,
) {
report_mlme_stats(&last_stats.mlme_stats, ¤t_stats.mlme_stats, sender);
- report_dispatcher_stats(
- &last_stats.dispatcher_stats,
- ¤t_stats.dispatcher_stats,
- sender,
- );
+ report_dispatcher_stats(&last_stats.dispatcher_stats, ¤t_stats.dispatcher_stats, sender);
}
fn report_dispatcher_stats(
- last_stats: &fidl_stats::DispatcherStats, current_stats: &fidl_stats::DispatcherStats,
+ last_stats: &fidl_stats::DispatcherStats,
+ current_stats: &fidl_stats::DispatcherStats,
sender: &mut CobaltSender,
) {
// These indexes must match the Cobalt config from
@@ -111,26 +110,17 @@
report_dispatcher_packets(
DISPATCHER_IN_PACKET_COUNT_INDEX,
- get_diff(
- last_stats.any_packet.in_.count,
- current_stats.any_packet.in_.count,
- ),
+ get_diff(last_stats.any_packet.in_.count, current_stats.any_packet.in_.count),
sender,
);
report_dispatcher_packets(
DISPATCHER_OUT_PACKET_COUNT_INDEX,
- get_diff(
- last_stats.any_packet.out.count,
- current_stats.any_packet.out.count,
- ),
+ get_diff(last_stats.any_packet.out.count, current_stats.any_packet.out.count),
sender,
);
report_dispatcher_packets(
DISPATCHER_DROP_PACKET_COUNT_INDEX,
- get_diff(
- last_stats.any_packet.drop.count,
- current_stats.any_packet.drop.count,
- ),
+ get_diff(last_stats.any_packet.drop.count, current_stats.any_packet.drop.count),
sender,
);
}
@@ -144,7 +134,8 @@
}
fn report_mlme_stats(
- last: &Option<Box<fidl_stats::MlmeStats>>, current: &Option<Box<fidl_stats::MlmeStats>>,
+ last: &Option<Box<fidl_stats::MlmeStats>>,
+ current: &Option<Box<fidl_stats::MlmeStats>>,
sender: &mut CobaltSender,
) {
if let (Some(ref last), Some(ref current)) = (last, current) {
@@ -159,7 +150,8 @@
}
fn report_client_mlme_stats(
- last_stats: &fidl_stats::ClientMlmeStats, current_stats: &fidl_stats::ClientMlmeStats,
+ last_stats: &fidl_stats::ClientMlmeStats,
+ current_stats: &fidl_stats::ClientMlmeStats,
sender: &mut CobaltSender,
) {
report_rssi_stats(
@@ -179,7 +171,8 @@
}
fn report_client_mlme_rx_tx_frames(
- last_stats: &fidl_stats::ClientMlmeStats, current_stats: &fidl_stats::ClientMlmeStats,
+ last_stats: &fidl_stats::ClientMlmeStats,
+ current_stats: &fidl_stats::ClientMlmeStats,
sender: &mut CobaltSender,
) {
// These indexes must match the Cobalt config from
@@ -189,18 +182,12 @@
sender.log_event_count(
CobaltMetricId::RxTxFrameCount as u32,
CLIENT_MLME_RX_FRAME_COUNT_INDEX,
- get_diff(
- last_stats.rx_frame.in_.count,
- current_stats.rx_frame.in_.count,
- ) as i64,
+ get_diff(last_stats.rx_frame.in_.count, current_stats.rx_frame.in_.count) as i64,
);
sender.log_event_count(
CobaltMetricId::RxTxFrameCount as u32,
CLIENT_MLME_TX_FRAME_COUNT_INDEX,
- get_diff(
- last_stats.tx_frame.out.count,
- current_stats.tx_frame.out.count,
- ) as i64,
+ get_diff(last_stats.tx_frame.out.count, current_stats.tx_frame.out.count) as i64,
);
// These indexes must match the Cobalt config from
@@ -210,23 +197,20 @@
sender.log_event_count(
CobaltMetricId::RxTxFrameBytes as u32,
CLIENT_MLME_RX_FRAME_BYTES_INDEX,
- get_diff(
- last_stats.rx_frame.in_bytes.count,
- current_stats.rx_frame.in_bytes.count,
- ) as i64,
+ get_diff(last_stats.rx_frame.in_bytes.count, current_stats.rx_frame.in_bytes.count) as i64,
);
sender.log_event_count(
CobaltMetricId::RxTxFrameBytes as u32,
CLIENT_MLME_TX_FRAME_BYTES_INDEX,
- get_diff(
- last_stats.tx_frame.out_bytes.count,
- current_stats.tx_frame.out_bytes.count,
- ) as i64,
+ get_diff(last_stats.tx_frame.out_bytes.count, current_stats.tx_frame.out_bytes.count)
+ as i64,
);
}
fn report_rssi_stats(
- rssi_metric_id: u32, last_stats: &fidl_stats::RssiStats, current_stats: &fidl_stats::RssiStats,
+ rssi_metric_id: u32,
+ last_stats: &fidl_stats::RssiStats,
+ current_stats: &fidl_stats::RssiStats,
sender: &mut CobaltSender,
) {
// In the internal stats histogram, hist[x] represents the number of frames
@@ -260,15 +244,20 @@
}
pub fn report_scan_delay(
- sender: &mut CobaltSender, scan_started_time: zx::Time, scan_finished_time: zx::Time,
+ sender: &mut CobaltSender,
+ scan_started_time: zx::Time,
+ scan_finished_time: zx::Time,
) {
let delay_micros = (scan_finished_time - scan_started_time).nanos() / 1000;
sender.log_elapsed_time(CobaltMetricId::ScanDelay as u32, 0, delay_micros);
}
pub fn report_connection_delay(
- sender: &mut CobaltSender, conn_started_time: zx::Time, conn_finished_time: zx::Time,
- result: &ConnectResult, failure: &Option<ConnectFailure>,
+ sender: &mut CobaltSender,
+ conn_started_time: zx::Time,
+ conn_finished_time: zx::Time,
+ result: &ConnectResult,
+ failure: &Option<ConnectFailure>,
) {
let delay_micros = (conn_finished_time - conn_started_time).nanos() / 1000;
let cobalt_index = match (result, failure) {
@@ -288,21 +277,27 @@
}
pub fn report_assoc_success_delay(
- sender: &mut CobaltSender, assoc_started_time: zx::Time, assoc_finished_time: zx::Time,
+ sender: &mut CobaltSender,
+ assoc_started_time: zx::Time,
+ assoc_finished_time: zx::Time,
) {
let delay_micros = (assoc_finished_time - assoc_started_time).nanos() / 1000;
sender.log_elapsed_time(CobaltMetricId::AssociationDelay as u32, 0, delay_micros);
}
pub fn report_rsna_established_delay(
- sender: &mut CobaltSender, rsna_started_time: zx::Time, rsna_finished_time: zx::Time,
+ sender: &mut CobaltSender,
+ rsna_started_time: zx::Time,
+ rsna_finished_time: zx::Time,
) {
let delay_micros = (rsna_finished_time - rsna_started_time).nanos() / 1000;
sender.log_elapsed_time(CobaltMetricId::RsnaDelay as u32, 0, delay_micros);
}
pub fn report_neighbor_networks_count(
- sender: &mut CobaltSender, bss_count: usize, ess_count: usize,
+ sender: &mut CobaltSender,
+ bss_count: usize,
+ ess_count: usize,
) {
const BSS_COUNT_INDEX: u32 = 0;
const ESS_COUNT_INDEX: u32 = 1;
@@ -318,7 +313,10 @@
);
}
-pub fn report_standards(sender: &mut CobaltSender, mut num_bss_by_standard: HashMap<Standard, usize>) {
+pub fn report_standards(
+ sender: &mut CobaltSender,
+ mut num_bss_by_standard: HashMap<Standard, usize>,
+) {
const ALL_STANDARDS: [(Standard, StandardLabel); 5] = [
(Standard::B, StandardLabel::B),
(Standard::G, StandardLabel::G),
@@ -331,21 +329,13 @@
Entry::Vacant(_) => 0 as i64,
Entry::Occupied(e) => *e.get() as i64,
};
- sender.log_event_count(
- CobaltMetricId::WlanStandards as u32,
- label.clone() as u32,
- count,
- )
+ sender.log_event_count(CobaltMetricId::WlanStandards as u32, label.clone() as u32, count)
});
}
pub fn report_channels(sender: &mut CobaltSender, num_bss_by_channel: HashMap<u8, usize>) {
num_bss_by_channel.into_iter().for_each(|(channel, count)| {
- sender.log_event_count(
- CobaltMetricId::WlanChannels as u32,
- channel as u32,
- count as i64,
- );
+ sender.log_event_count(CobaltMetricId::WlanChannels as u32, channel as u32, count as i64);
});
}
@@ -393,17 +383,23 @@
let result = match result {
ConnectFailure::NoMatchingBssFound => NoMatchingBssFoundId,
ConnectFailure::ScanFailure(scan_failure) => match scan_failure {
- ScanResultCodes::Success => { return None; }
+ ScanResultCodes::Success => {
+ return None;
+ }
NotSupported => ScanNotSupportedId,
InvalidArgs => ScanInvalidArgsId,
InternalError => ScanInternalErrorId,
- }
+ },
ConnectFailure::JoinFailure(join_failure) => match join_failure {
- JoinResultCodes::Success => { return None; }
+ JoinResultCodes::Success => {
+ return None;
+ }
JoinFailureTimeout => JoinFailureTimeoutId,
},
ConnectFailure::AuthenticationFailure(auth_failure) => match auth_failure {
- AuthenticateResultCodes::Success => { return None; }
+ AuthenticateResultCodes::Success => {
+ return None;
+ }
Refused => AuthRefusedId,
AntiCloggingTokenRequired => AuthAntiCloggingTokenRequiredId,
FiniteCyclicGroupNotSupported => AuthFiniteCyclicGroupNotSupportedId,
@@ -411,7 +407,9 @@
AuthFailureTimeout => AuthFailureTimeoutId,
},
ConnectFailure::AssociationFailure(assoc_failure) => match assoc_failure {
- AssociateResultCodes::Success => { return None; }
+ AssociateResultCodes::Success => {
+ return None;
+ }
RefusedReasonUnspecified => AssocRefusedReasonUnspecifiedId,
RefusedNotAuthenticated => AssocRefusedNotAuthenticatedId,
RefusedCapabilitiesMismatch => AssocRefusedCapabilitiesMismatchId,
diff --git a/bin/wlan/wlanstack/src/watchable_map.rs b/bin/wlan/wlanstack/src/watchable_map.rs
index 1304f44..a488024 100644
--- a/bin/wlan/wlanstack/src/watchable_map.rs
+++ b/bin/wlan/wlanstack/src/watchable_map.rs
@@ -4,7 +4,7 @@
use futures::channel::mpsc::{self, UnboundedReceiver, UnboundedSender};
use parking_lot::Mutex;
-use std::collections::{HashMap};
+use std::collections::HashMap;
use std::hash::Hash;
use std::sync::Arc;
@@ -16,18 +16,27 @@
///
/// All mutations and snapshots are totally ordered, and events in the
/// queue are guaranteed to follow the same order.
-pub struct WatchableMap<K, V> where K: Hash + Eq {
- inner: Mutex<Inner<K, V>>
+pub struct WatchableMap<K, V>
+where
+ K: Hash + Eq,
+{
+ inner: Mutex<Inner<K, V>>,
}
#[derive(Debug)]
-pub enum MapEvent<K, V> where K: Hash + Eq {
+pub enum MapEvent<K, V>
+where
+ K: Hash + Eq,
+{
KeyInserted(K),
KeyRemoved(K),
- Snapshot(Arc<HashMap<K, Arc<V>>>)
+ Snapshot(Arc<HashMap<K, Arc<V>>>),
}
-struct Inner<K, V> where K: Hash + Eq {
+struct Inner<K, V>
+where
+ K: Hash + Eq,
+{
// Storing the map in an Arc allows us to use copy-on-write:
// taking a snapshot is simply cloning an Arc, and all mutations
// use Arc::make_mut() which avoids a copy if no snapshots
@@ -37,17 +46,14 @@
}
impl<K, V> WatchableMap<K, V>
- where K: Clone + Hash + Eq
+where
+ K: Clone + Hash + Eq,
{
/// Returns an empty map and the receiving end of the event queue
pub fn new() -> (Self, UnboundedReceiver<MapEvent<K, V>>) {
let (sender, receiver) = mpsc::unbounded();
- let map = WatchableMap {
- inner: Mutex::new(Inner {
- map: Arc::new(HashMap::new()),
- sender
- })
- };
+ let map =
+ WatchableMap { inner: Mutex::new(Inner { map: Arc::new(HashMap::new()), sender }) };
(map, receiver)
}
@@ -55,7 +61,9 @@
pub fn insert(&self, key: K, value: V) {
let mut inner = self.inner.lock();
Arc::make_mut(&mut inner.map).insert(key.clone(), Arc::new(value));
- inner.sender.unbounded_send(MapEvent::KeyInserted(key))
+ inner
+ .sender
+ .unbounded_send(MapEvent::KeyInserted(key))
.expect("failed to enqueue KeyInserted");
}
@@ -63,14 +71,18 @@
pub fn remove(&self, key: &K) {
let mut inner = self.inner.lock();
Arc::make_mut(&mut inner.map).remove(key);
- inner.sender.unbounded_send(MapEvent::KeyRemoved(key.clone()))
+ inner
+ .sender
+ .unbounded_send(MapEvent::KeyRemoved(key.clone()))
.expect("failed to enqueue KeyRemoved");
}
/// Take a snapshot and push it to the queue
pub fn request_snapshot(&self) {
let inner = self.inner.lock();
- inner.sender.unbounded_send(MapEvent::Snapshot(inner.map.clone()))
+ inner
+ .sender
+ .unbounded_send(MapEvent::Snapshot(inner.map.clone()))
.expect("failed to enqueue Snapshot");
}
@@ -80,7 +92,9 @@
}
pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<Arc<V>>
- where K: ::std::borrow::Borrow<Q>, Q: Hash + Eq
+ where
+ K: ::std::borrow::Borrow<Q>,
+ Q: Hash + Eq,
{
self.inner.lock().map.get(k).map(|v| v.clone())
}
@@ -108,10 +122,14 @@
map.insert(4u16, "bar");
let snapshot_two = map.get_snapshot();
- assert_eq!(vec![(3u16, "foo")],
- snapshot_one.iter().map(|(k, v)| (*k, **v)).collect::<Vec<_>>());
- assert_eq!(vec![(4u16, "bar")],
- snapshot_two.iter().map(|(k, v)| (*k, **v)).collect::<Vec<_>>());
+ assert_eq!(
+ vec![(3u16, "foo")],
+ snapshot_one.iter().map(|(k, v)| (*k, **v)).collect::<Vec<_>>()
+ );
+ assert_eq!(
+ vec![(4u16, "bar")],
+ snapshot_two.iter().map(|(k, v)| (*k, **v)).collect::<Vec<_>>()
+ );
}
#[test]
@@ -119,39 +137,43 @@
let (map, mut recv) = WatchableMap::new();
map.insert(3u16, "foo");
match recv.try_next() {
- Ok(Some(MapEvent::KeyInserted(3u16))) => {},
- other => panic!("expected KeyInserted(3), got {:?}", other)
+ Ok(Some(MapEvent::KeyInserted(3u16))) => {}
+ other => panic!("expected KeyInserted(3), got {:?}", other),
}
map.request_snapshot();
let snapshot_one = match recv.try_next() {
Ok(Some(MapEvent::Snapshot(s))) => s,
- other => panic!("expected Snapshot, got {:?}", other)
+ other => panic!("expected Snapshot, got {:?}", other),
};
map.remove(&3u16);
match recv.try_next() {
- Ok(Some(MapEvent::KeyRemoved(3u16))) => {},
- other => panic!("expected KeyRemoved(3), got {:?}", other)
+ Ok(Some(MapEvent::KeyRemoved(3u16))) => {}
+ other => panic!("expected KeyRemoved(3), got {:?}", other),
}
map.insert(4u16, "bar");
match recv.try_next() {
- Ok(Some(MapEvent::KeyInserted(4u16))) => {},
- other => panic!("expected KeyInserted(4), got {:?}", other)
+ Ok(Some(MapEvent::KeyInserted(4u16))) => {}
+ other => panic!("expected KeyInserted(4), got {:?}", other),
}
map.request_snapshot();
let snapshot_two = match recv.try_next() {
Ok(Some(MapEvent::Snapshot(s))) => s,
- other => panic!("expected Snapshot, got {:?}", other)
+ other => panic!("expected Snapshot, got {:?}", other),
};
assert!(recv.try_next().is_err());
- assert_eq!(vec![(3u16, "foo")],
- snapshot_one.iter().map(|(k, v)| (*k, **v)).collect::<Vec<_>>());
- assert_eq!(vec![(4u16, "bar")],
- snapshot_two.iter().map(|(k, v)| (*k, **v)).collect::<Vec<_>>());
+ assert_eq!(
+ vec![(3u16, "foo")],
+ snapshot_one.iter().map(|(k, v)| (*k, **v)).collect::<Vec<_>>()
+ );
+ assert_eq!(
+ vec![(4u16, "bar")],
+ snapshot_two.iter().map(|(k, v)| (*k, **v)).collect::<Vec<_>>()
+ );
}
}
diff --git a/bin/wlan/wlanstack/src/watcher_service.rs b/bin/wlan/wlanstack/src/watcher_service.rs
index b3c00d7..6d1a930 100644
--- a/bin/wlan/wlanstack/src/watcher_service.rs
+++ b/bin/wlan/wlanstack/src/watcher_service.rs
@@ -4,6 +4,9 @@
use failure::format_err;
use fidl::endpoints::{RequestStream, ServerEnd};
+use fidl_fuchsia_wlan_device_service::{
+ self as fidl_svc, DeviceWatcherControlHandle, DeviceWatcherRequestStream,
+};
use futures::channel::mpsc::{self, UnboundedReceiver, UnboundedSender};
use futures::prelude::*;
use futures::try_join;
@@ -11,74 +14,67 @@
use parking_lot::Mutex;
use std::collections::HashMap;
use std::sync::Arc;
-use fidl_fuchsia_wlan_device_service::{self as fidl_svc, DeviceWatcherControlHandle, DeviceWatcherRequestStream};
-use crate::Never;
use crate::watchable_map::{MapEvent, WatchableMap};
+use crate::Never;
// In reality, P and I are always PhyDevice and IfaceDevice, respectively.
// They are generic solely for the purpose of mocking for tests.
-pub fn serve_watchers<P, I>(phys: Arc<WatchableMap<u16, P>>,
- ifaces: Arc<WatchableMap<u16, I>>,
- phy_events: UnboundedReceiver<MapEvent<u16, P>>,
- iface_events: UnboundedReceiver<MapEvent<u16, I>>)
- -> (WatcherService<P, I>, impl Future<Output = Result<Never, failure::Error>>)
- where P: 'static, I: 'static
+pub fn serve_watchers<P, I>(
+ phys: Arc<WatchableMap<u16, P>>,
+ ifaces: Arc<WatchableMap<u16, I>>,
+ phy_events: UnboundedReceiver<MapEvent<u16, P>>,
+ iface_events: UnboundedReceiver<MapEvent<u16, I>>,
+) -> (WatcherService<P, I>, impl Future<Output = Result<Never, failure::Error>>)
+where
+ P: 'static,
+ I: 'static,
{
- let inner = Arc::new(Mutex::new(Inner {
- watchers: HashMap::new(),
- next_watcher_id: 0,
- phys,
- ifaces
- }));
+ let inner =
+ Arc::new(Mutex::new(Inner { watchers: HashMap::new(), next_watcher_id: 0, phys, ifaces }));
let (reaper_sender, reaper_receiver) = mpsc::unbounded();
- let s = WatcherService {
- inner: Arc::clone(&inner),
- reaper_queue: reaper_sender
- };
+ let s = WatcherService { inner: Arc::clone(&inner), reaper_queue: reaper_sender };
let fut = async move {
let phy_fut = notify_phy_watchers(phy_events, &inner);
let iface_fut = notify_iface_watchers(iface_events, &inner);
let reaper_fut = reap_watchers(&inner, reaper_receiver);
- try_join!(phy_fut, iface_fut, reaper_fut)
- .map(|x: (Never, Never, Never)| x.0)
+ try_join!(phy_fut, iface_fut, reaper_fut).map(|x: (Never, Never, Never)| x.0)
};
(s, fut)
}
pub struct WatcherService<P, I> {
inner: Arc<Mutex<Inner<P, I>>>,
- reaper_queue: UnboundedSender<ReaperTask>
+ reaper_queue: UnboundedSender<ReaperTask>,
}
// Manual clone impl since #derive uses incorrect trait bounds
impl<P, I> Clone for WatcherService<P, I> {
fn clone(&self) -> Self {
- WatcherService {
- inner: self.inner.clone(),
- reaper_queue: self.reaper_queue.clone()
- }
+ WatcherService { inner: self.inner.clone(), reaper_queue: self.reaper_queue.clone() }
}
}
impl<P, I> WatcherService<P, I> {
- pub fn add_watcher(&self, endpoint: ServerEnd<fidl_svc::DeviceWatcherMarker>)
- -> Result<(), fidl::Error>
- {
+ pub fn add_watcher(
+ &self,
+ endpoint: ServerEnd<fidl_svc::DeviceWatcherMarker>,
+ ) -> Result<(), fidl::Error> {
let stream = endpoint.into_stream()?;
let handle = stream.control_handle();
let mut guard = self.inner.lock();
let inner = &mut *guard;
- self.reaper_queue.unbounded_send(ReaperTask {
- watcher_channel: stream,
- watcher_id: inner.next_watcher_id
- }).expect("failed to submit a task to the watcher reaper: {}");
- inner.watchers.insert(inner.next_watcher_id, Watcher {
- handle,
- sent_phy_snapshot: false,
- sent_iface_snapshot: false
- });
+ self.reaper_queue
+ .unbounded_send(ReaperTask {
+ watcher_channel: stream,
+ watcher_id: inner.next_watcher_id,
+ })
+ .expect("failed to submit a task to the watcher reaper: {}");
+ inner.watchers.insert(
+ inner.next_watcher_id,
+ Watcher { handle, sent_phy_snapshot: false, sent_iface_snapshot: false },
+ );
inner.phys.request_snapshot();
inner.ifaces.request_snapshot();
inner.next_watcher_id += 1;
@@ -101,8 +97,9 @@
impl<P, I> Inner<P, I> {
fn notify_watchers<F, G>(&mut self, sent_snapshot: F, send_event: G)
- where F: Fn(&Watcher) -> bool,
- G: Fn(&DeviceWatcherControlHandle) -> Result<(), fidl::Error>
+ where
+ F: Fn(&Watcher) -> bool,
+ G: Fn(&DeviceWatcherControlHandle) -> Result<(), fidl::Error>,
{
self.watchers.retain(|_, w| {
if sent_snapshot(w) {
@@ -114,10 +111,14 @@
})
}
- fn send_snapshot<F, G, T>(&mut self, sent_snapshot: F, send_on_add: G,
- snapshot: Arc<HashMap<u16, T>>)
- where F: Fn(&mut Watcher) -> &mut bool,
- G: Fn(&DeviceWatcherControlHandle, u16) -> Result<(), fidl::Error>
+ fn send_snapshot<F, G, T>(
+ &mut self,
+ sent_snapshot: F,
+ send_on_add: G,
+ snapshot: Arc<HashMap<u16, T>>,
+ ) where
+ F: Fn(&mut Watcher) -> &mut bool,
+ G: Fn(&DeviceWatcherControlHandle, u16) -> Result<(), fidl::Error>,
{
self.watchers.retain(|_, w| {
if !*sent_snapshot(w) {
@@ -142,35 +143,45 @@
r.is_ok()
}
-async fn notify_phy_watchers<P, I>(mut events: UnboundedReceiver<MapEvent<u16, P>>,
- inner: &Mutex<Inner<P, I>>)
- -> Result<Never, failure::Error>
-{
+async fn notify_phy_watchers<P, I>(
+ mut events: UnboundedReceiver<MapEvent<u16, P>>,
+ inner: &Mutex<Inner<P, I>>,
+) -> Result<Never, failure::Error> {
while let Some(e) = await!(events.next()) {
match e {
- MapEvent::KeyInserted(id) => inner.lock().notify_watchers(
- |w| w.sent_phy_snapshot, |h| h.send_on_phy_added(id)),
- MapEvent::KeyRemoved(id) => inner.lock().notify_watchers(
- |w| w.sent_phy_snapshot, |h| h.send_on_phy_removed(id)),
+ MapEvent::KeyInserted(id) => {
+ inner.lock().notify_watchers(|w| w.sent_phy_snapshot, |h| h.send_on_phy_added(id))
+ }
+ MapEvent::KeyRemoved(id) => {
+ inner.lock().notify_watchers(|w| w.sent_phy_snapshot, |h| h.send_on_phy_removed(id))
+ }
MapEvent::Snapshot(s) => inner.lock().send_snapshot(
- |w| &mut w.sent_phy_snapshot, |h, id| h.send_on_phy_added(id), s)
+ |w| &mut w.sent_phy_snapshot,
+ |h, id| h.send_on_phy_added(id),
+ s,
+ ),
}
}
Err(format_err!("stream of events from the phy device map has ended unexpectedly"))
}
-async fn notify_iface_watchers<P, I>(mut events: UnboundedReceiver<MapEvent<u16, I>>,
- inner: &Mutex<Inner<P, I>>)
- -> Result<Never, failure::Error>
-{
+async fn notify_iface_watchers<P, I>(
+ mut events: UnboundedReceiver<MapEvent<u16, I>>,
+ inner: &Mutex<Inner<P, I>>,
+) -> Result<Never, failure::Error> {
while let Some(e) = await!(events.next()) {
match e {
- MapEvent::KeyInserted(id) => inner.lock().notify_watchers(
- |w| w.sent_iface_snapshot, |h| h.send_on_iface_added(id)),
- MapEvent::KeyRemoved(id) => inner.lock().notify_watchers(
- |w| w.sent_iface_snapshot, |h| h.send_on_iface_removed(id)),
+ MapEvent::KeyInserted(id) => inner
+ .lock()
+ .notify_watchers(|w| w.sent_iface_snapshot, |h| h.send_on_iface_added(id)),
+ MapEvent::KeyRemoved(id) => inner
+ .lock()
+ .notify_watchers(|w| w.sent_iface_snapshot, |h| h.send_on_iface_removed(id)),
MapEvent::Snapshot(s) => inner.lock().send_snapshot(
- |w| &mut w.sent_iface_snapshot, |h, id| h.send_on_iface_added(id), s)
+ |w| &mut w.sent_iface_snapshot,
+ |h, id| h.send_on_iface_added(id),
+ s,
+ ),
}
}
Err(format_err!("stream of events from the iface device map has ended unexpectedly"))
@@ -185,9 +196,10 @@
/// Performing this clean up solely when notification fails is not sufficient:
/// in the scenario where devices are not being added or removed, but new clients come and go,
/// the watcher list could grow without bound.
-async fn reap_watchers<P, I>(inner: &Mutex<Inner<P, I>>, watchers: UnboundedReceiver<ReaperTask>)
- -> Result<Never, failure::Error>
-{
+async fn reap_watchers<P, I>(
+ inner: &Mutex<Inner<P, I>>,
+ watchers: UnboundedReceiver<ReaperTask>,
+) -> Result<Never, failure::Error> {
const REAP_CONCURRENT_LIMIT: usize = 10000;
await!(watchers.for_each_concurrent(REAP_CONCURRENT_LIMIT, move |w| {
// Wait for the other side to close the channel (or an error to occur)
@@ -216,8 +228,8 @@
let (helper, future) = setup();
pin_mut!(future);
assert_eq!(0, helper.service.inner.lock().watchers.len());
- let (client_end, server_end) = fidl::endpoints::create_endpoints()
- .expect("Failed to create endpoints");
+ let (client_end, server_end) =
+ fidl::endpoints::create_endpoints().expect("Failed to create endpoints");
// Add a watcher and check that it was added to the map
helper.service.add_watcher(server_end).expect("add_watcher failed");
@@ -242,8 +254,8 @@
let exec = &mut fasync::Executor::new().expect("Failed to create an executor");
let (helper, future) = setup();
pin_mut!(future);
- let (proxy, server_end) = fidl::endpoints::create_proxy()
- .expect("Failed to create endpoints");
+ let (proxy, server_end) =
+ fidl::endpoints::create_proxy().expect("Failed to create endpoints");
helper.service.add_watcher(server_end).expect("add_watcher failed");
helper.phys.insert(20, 2000);
@@ -259,16 +271,16 @@
assert_eq!(3, events.len());
// Sadly, generated Event struct doesn't implement PartialEq
match &events[0] {
- &DeviceWatcherEvent::OnPhyAdded{ phy_id: 20 } => {},
- other => panic!("Expected OnPhyAdded(20), got {:?}", other)
+ &DeviceWatcherEvent::OnPhyAdded { phy_id: 20 } => {}
+ other => panic!("Expected OnPhyAdded(20), got {:?}", other),
}
match &events[1] {
- &DeviceWatcherEvent::OnPhyAdded{ phy_id: 30 } => {},
- other => panic!("Expected OnPhyAdded(30), got {:?}", other)
+ &DeviceWatcherEvent::OnPhyAdded { phy_id: 30 } => {}
+ other => panic!("Expected OnPhyAdded(30), got {:?}", other),
}
match &events[2] {
- &DeviceWatcherEvent::OnPhyRemoved{ phy_id: 20 } => {},
- other => panic!("Expected OnPhyRemoved(20), got {:?}", other)
+ &DeviceWatcherEvent::OnPhyRemoved { phy_id: 20 } => {}
+ other => panic!("Expected OnPhyRemoved(20), got {:?}", other),
}
}
@@ -277,8 +289,8 @@
let exec = &mut fasync::Executor::new().expect("Failed to create an executor");
let (helper, future) = setup();
pin_mut!(future);
- let (proxy, server_end) = fidl::endpoints::create_proxy()
- .expect("Failed to create endpoints");
+ let (proxy, server_end) =
+ fidl::endpoints::create_proxy().expect("Failed to create endpoints");
helper.service.add_watcher(server_end).expect("add_watcher failed");
helper.ifaces.insert(50, 5000);
@@ -292,12 +304,12 @@
let events = fetch_events(exec, proxy.take_event_stream());
assert_eq!(2, events.len());
match &events[0] {
- &DeviceWatcherEvent::OnIfaceAdded{ iface_id: 50 } => {},
- other => panic!("Expected OnIfaceAdded(50), got {:?}", other)
+ &DeviceWatcherEvent::OnIfaceAdded { iface_id: 50 } => {}
+ other => panic!("Expected OnIfaceAdded(50), got {:?}", other),
}
match &events[1] {
- &DeviceWatcherEvent::OnIfaceRemoved{ iface_id: 50 } => {},
- other => panic!("Expected OnIfaceRemoved(50), got {:?}", other)
+ &DeviceWatcherEvent::OnIfaceRemoved { iface_id: 50 } => {}
+ other => panic!("Expected OnIfaceRemoved(50), got {:?}", other),
}
}
@@ -313,8 +325,8 @@
helper.phys.remove(&20);
// Now add the watcher and pump the events
- let (proxy, server_end) = fidl::endpoints::create_proxy()
- .expect("Failed to create endpoints");
+ let (proxy, server_end) =
+ fidl::endpoints::create_proxy().expect("Failed to create endpoints");
helper.service.add_watcher(server_end).expect("add_watcher failed");
if let Poll::Ready(Err(e)) = exec.run_until_stalled(&mut future) {
panic!("server future returned an error: {:?}", e);
@@ -324,8 +336,8 @@
let events = fetch_events(exec, proxy.take_event_stream());
assert_eq!(1, events.len());
match &events[0] {
- &DeviceWatcherEvent::OnPhyAdded{ phy_id: 30 } => {},
- other => panic!("Expected OnPhyAdded(30), got {:?}", other)
+ &DeviceWatcherEvent::OnPhyAdded { phy_id: 30 } => {}
+ other => panic!("Expected OnPhyAdded(30), got {:?}", other),
}
}
@@ -341,8 +353,8 @@
helper.ifaces.remove(&20);
// Now add the watcher and pump the events
- let (proxy, server_end) = fidl::endpoints::create_proxy()
- .expect("Failed to create endpoints");
+ let (proxy, server_end) =
+ fidl::endpoints::create_proxy().expect("Failed to create endpoints");
helper.service.add_watcher(server_end).expect("add_watcher failed");
if let Poll::Ready(Err(e)) = exec.run_until_stalled(&mut future) {
panic!("server future returned an error: {:?}", e);
@@ -352,8 +364,8 @@
let events = fetch_events(exec, proxy.take_event_stream());
assert_eq!(1, events.len());
match &events[0] {
- &DeviceWatcherEvent::OnIfaceAdded{ iface_id: 30 } => {},
- other => panic!("Expected OnIfaceAdded(30), got {:?}", other)
+ &DeviceWatcherEvent::OnIfaceAdded { iface_id: 30 } => {}
+ other => panic!("Expected OnIfaceAdded(30), got {:?}", other),
}
}
@@ -366,13 +378,13 @@
helper.ifaces.insert(20, 2000);
// Add first watcher
- let (proxy_one, server_end_one) = fidl::endpoints::create_proxy()
- .expect("Failed to create endpoints");
+ let (proxy_one, server_end_one) =
+ fidl::endpoints::create_proxy().expect("Failed to create endpoints");
helper.service.add_watcher(server_end_one).expect("add_watcher failed (1)");
// Add second watcher
- let (proxy_two, server_end_two) = fidl::endpoints::create_proxy()
- .expect("Failed to create endpoints");
+ let (proxy_two, server_end_two) =
+ fidl::endpoints::create_proxy().expect("Failed to create endpoints");
helper.service.add_watcher(server_end_two).expect("add_watcher failed (2)");
// Deliver events
@@ -397,13 +409,10 @@
let (client_chan, server_chan) = zx::Channel::create().unwrap();
// Make a channel without a WRITE permission to make sure sending an event fails
let server_handle: zx::Handle = server_chan.into();
- let reduced_chan: zx::Channel = server_handle
- .replace(zx::Rights::READ | zx::Rights::WAIT)
- .unwrap()
- .into();
+ let reduced_chan: zx::Channel =
+ server_handle.replace(zx::Rights::READ | zx::Rights::WAIT).unwrap().into();
- helper.service.add_watcher(ServerEnd::new(reduced_chan))
- .expect("add_watcher failed");
+ helper.service.add_watcher(ServerEnd::new(reduced_chan)).expect("add_watcher failed");
if let Poll::Ready(Err(e)) = exec.run_until_stalled(&mut future) {
panic!("future returned an error (1): {:?}", e);
}
@@ -434,13 +443,16 @@
let (ifaces, iface_events) = WatchableMap::new();
let phys = Arc::new(phys);
let ifaces = Arc::new(ifaces);
- let (service, future) = serve_watchers(phys.clone(), ifaces.clone(), phy_events, iface_events);
+ let (service, future) =
+ serve_watchers(phys.clone(), ifaces.clone(), phy_events, iface_events);
let helper = Helper { phys, ifaces, service };
(helper, future)
}
- fn fetch_events(exec: &mut fasync::Executor,
- stream: fidl_svc::DeviceWatcherEventStream) -> Vec<DeviceWatcherEvent> {
+ fn fetch_events(
+ exec: &mut fasync::Executor,
+ stream: fidl_svc::DeviceWatcherEventStream,
+ ) -> Vec<DeviceWatcherEvent> {
let events = Arc::new(Mutex::new(Some(Vec::new())));
let events_two = events.clone();
let mut event_fut = stream
diff --git a/bin/wlan/wlantool/src/main.rs b/bin/wlan/wlantool/src/main.rs
index efb0c13..40c9b80 100644
--- a/bin/wlan/wlantool/src/main.rs
+++ b/bin/wlan/wlantool/src/main.rs
@@ -7,11 +7,13 @@
use failure::{bail, format_err, Error, ResultExt};
use fidl::endpoints;
-use fidl_fuchsia_wlan_device_service::{self as wlan_service, DeviceServiceMarker,
- DeviceServiceProxy};
+use fidl_fuchsia_wlan_device_service::{
+ self as wlan_service, DeviceServiceMarker, DeviceServiceProxy,
+};
use fidl_fuchsia_wlan_minstrel::Peer;
-use fidl_fuchsia_wlan_sme::{self as fidl_sme, ConnectResultCode, ConnectTransactionEvent,
- ScanTransactionEvent};
+use fidl_fuchsia_wlan_sme::{
+ self as fidl_sme, ConnectResultCode, ConnectTransactionEvent, ScanTransactionEvent,
+};
use fuchsia_app::client::connect_to_service;
use fuchsia_async as fasync;
use fuchsia_zircon as zx;
@@ -32,8 +34,8 @@
println!("{:?}", opt);
let mut exec = fasync::Executor::new().context("error creating event loop")?;
- let wlan_svc =
- connect_to_service::<DeviceServiceMarker>().context("failed to connect to device service")?;
+ let wlan_svc = connect_to_service::<DeviceServiceMarker>()
+ .context("failed to connect to device service")?;
let fut = async {
match opt {
@@ -66,41 +68,37 @@
async fn do_iface(cmd: opts::IfaceCmd, wlan_svc: WlanSvc) -> Result<(), Error> {
match cmd {
opts::IfaceCmd::New { phy_id, role } => {
- let mut req = wlan_service::CreateIfaceRequest {
- phy_id: phy_id,
- role: role.into(),
- };
+ let mut req = wlan_service::CreateIfaceRequest { phy_id: phy_id, role: role.into() };
- let response = await!(wlan_svc.create_iface(&mut req)).context("error getting response")?;
+ let response =
+ await!(wlan_svc.create_iface(&mut req)).context("error getting response")?;
println!("response: {:?}", response);
- },
+ }
opts::IfaceCmd::Delete { phy_id, iface_id } => {
- let mut req = wlan_service::DestroyIfaceRequest {
- phy_id: phy_id,
- iface_id: iface_id,
- };
+ let mut req = wlan_service::DestroyIfaceRequest { phy_id: phy_id, iface_id: iface_id };
- let response = await!(wlan_svc.destroy_iface(&mut req)).context("error destroying iface")?;
+ let response =
+ await!(wlan_svc.destroy_iface(&mut req)).context("error destroying iface")?;
match zx::Status::ok(response) {
Ok(()) => println!("destroyed iface {:?}", iface_id),
Err(s) => println!("error destroying iface: {:?}", s),
}
- },
+ }
opts::IfaceCmd::List => {
let response = await!(wlan_svc.list_ifaces()).context("error getting response")?;
println!("response: {:?}", response);
- },
+ }
opts::IfaceCmd::Query { iface_id } => {
let response =
await!(wlan_svc.query_iface(iface_id)).context("error querying iface")?;
println!("response: {:?}", response);
- },
+ }
opts::IfaceCmd::Stats { iface_id } => {
let ids = await!(get_iface_ids(wlan_svc.clone(), iface_id))?;
for iface_id in ids {
let (status, resp) = await!(wlan_svc.get_iface_stats(iface_id))
- .context("error getting stats for iface")?;
+ .context("error getting stats for iface")?;
match status {
zx::sys::ZX_OK => {
match resp {
@@ -108,40 +106,44 @@
Some(r) => println!("Iface {}: {:#?}", iface_id, r),
None => println!("Iface {} returns empty stats resonse", iface_id),
}
- },
+ }
status => println!("error getting stats for Iface {}: {}", iface_id, status),
}
}
- },
- opts::IfaceCmd::Minstrel(cmd) => {
- match cmd {
- opts::MinstrelCmd::List{ iface_id } => {
- let ids = await!(get_iface_ids(wlan_svc.clone(), iface_id))?;
- for id in ids {
- if let Ok(peers) = await!(list_minstrel_peers(wlan_svc.clone(), id)) {
- if peers.is_empty() { continue; }
- println!("iface {} has {} peers:", id, peers.len());
- for peer in peers {
- println!("{}", peer);
- }
+ }
+ opts::IfaceCmd::Minstrel(cmd) => match cmd {
+ opts::MinstrelCmd::List { iface_id } => {
+ let ids = await!(get_iface_ids(wlan_svc.clone(), iface_id))?;
+ for id in ids {
+ if let Ok(peers) = await!(list_minstrel_peers(wlan_svc.clone(), id)) {
+ if peers.is_empty() {
+ continue;
+ }
+ println!("iface {} has {} peers:", id, peers.len());
+ for peer in peers {
+ println!("{}", peer);
}
}
- },
- opts::MinstrelCmd::Show{ iface_id, peer_addr } => {
- let peer_addr = match peer_addr {
- Some(s) => Some(s.parse()?),
- None => None,
- };
- let ids = await!(get_iface_ids(wlan_svc.clone(), iface_id))?;
- for id in ids {
- if let Err(e) = await!(show_minstrel_peer_for_iface(
- wlan_svc.clone(), id, peer_addr))
- {
- println!("querying peer(s) {} on iface {} returned an error: {}",
- peer_addr.unwrap_or(MacAddr([0; 6])), id, e);
- }
+ }
+ }
+ opts::MinstrelCmd::Show { iface_id, peer_addr } => {
+ let peer_addr = match peer_addr {
+ Some(s) => Some(s.parse()?),
+ None => None,
+ };
+ let ids = await!(get_iface_ids(wlan_svc.clone(), iface_id))?;
+ for id in ids {
+ if let Err(e) =
+ await!(show_minstrel_peer_for_iface(wlan_svc.clone(), id, peer_addr))
+ {
+ println!(
+ "querying peer(s) {} on iface {} returned an error: {}",
+ peer_addr.unwrap_or(MacAddr([0; 6])),
+ id,
+ e
+ );
}
- },
+ }
}
},
}
@@ -183,15 +185,18 @@
let sme = await!(get_client_sme(wlan_svc, iface_id))?;
await!(sme.disconnect())
.map_err(|e| format_err!("error sending disconnect request: {}", e))
- },
+ }
opts::ClientCmd::Status { iface_id } => {
let sme = await!(get_client_sme(wlan_svc, iface_id))?;
let st = await!(sme.status())?;
match st.connected_to {
Some(bss) => {
- println!("Connected to '{}' (bssid {})",
- String::from_utf8_lossy(&bss.ssid), MacAddr(bss.bssid));
- },
+ println!(
+ "Connected to '{}' (bssid {})",
+ String::from_utf8_lossy(&bss.ssid),
+ MacAddr(bss.bssid)
+ );
+ }
None => println!("Not connected to a network"),
}
if !st.connecting_to_ssid.is_empty() {
@@ -215,14 +220,18 @@
match r {
fidl_sme::StartApResultCode::InvalidArguments => {
println!("{:?}: Channel {:?} is invalid", r, config.channel);
- },
+ }
fidl_sme::StartApResultCode::DfsUnsupported => {
- println!("{:?}: The specified role does not support DFS channel {:?}",
- r, config.channel);
- },
- _ => { println!("{:?}", r ); },
+ println!(
+ "{:?}: The specified role does not support DFS channel {:?}",
+ r, config.channel
+ );
+ }
+ _ => {
+ println!("{:?}", r);
+ }
}
- },
+ }
opts::ApCmd::Stop { iface_id } => {
let sme = await!(get_ap_sme(wlan_svc, iface_id))?;
let r = await!(sme.stop());
@@ -236,22 +245,23 @@
match cmd {
opts::MeshCmd::Join { iface_id, mesh_id, channel } => {
let sme = await!(get_mesh_sme(wlan_svc, iface_id))?;
- let mut config = fidl_sme::MeshConfig {
- mesh_id: mesh_id.as_bytes().to_vec(),
- channel,
- };
+ let mut config = fidl_sme::MeshConfig { mesh_id: mesh_id.as_bytes().to_vec(), channel };
let r = await!(sme.join(&mut config))?;
match r {
fidl_sme::JoinMeshResultCode::InvalidArguments => {
println!("{:?}: Channel {:?} is invalid", r, config.channel);
- },
+ }
fidl_sme::JoinMeshResultCode::DfsUnsupported => {
- println!("{:?}: The specified role does not support DFS channel {:?}",
- r, config.channel);
- },
- _ => { println!("{:?}", r ); },
+ println!(
+ "{:?}: The specified role does not support DFS channel {:?}",
+ r, config.channel
+ );
+ }
+ _ => {
+ println!("{:?}", r);
+ }
}
- },
+ }
opts::MeshCmd::Leave { iface_id } => {
let sme = await!(get_mesh_sme(wlan_svc, iface_id))?;
let r = await!(sme.leave());
@@ -266,8 +276,11 @@
impl fmt::Display for MacAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
- write!(f, "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
- self.0[0], self.0[1], self.0[2], self.0[3], self.0[4], self.0[5])
+ write!(
+ f,
+ "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
+ self.0[0], self.0[1], self.0[2], self.0[3], self.0[4], self.0[5]
+ )
}
}
@@ -286,7 +299,9 @@
index += 1;
}
- if index != 6 { bail!("Too few octets"); }
+ if index != 6 {
+ bail!("Too few octets");
+ }
Ok(MacAddr(bytes))
}
}
@@ -294,7 +309,9 @@
async fn handle_scan_transaction(scan_txn: fidl_sme::ScanTransactionProxy) -> Result<(), Error> {
let mut printed_header = false;
let mut events = scan_txn.take_event_stream();
- while let Some(evt) = await!(events.try_next()).context("failed to fetch all results before the channel was closed")? {
+ while let Some(evt) = await!(events.try_next())
+ .context("failed to fetch all results before the channel was closed")?
+ {
match evt {
ScanTransactionEvent::OnResult { aps } => {
if !printed_header {
@@ -305,11 +322,11 @@
print_scan_result(ap);
}
}
- ScanTransactionEvent::OnFinished { } => break,
+ ScanTransactionEvent::OnFinished {} => break,
ScanTransactionEvent::OnError { error } => {
eprintln!("Error: {}", error.message);
break;
- },
+ }
}
}
Ok(())
@@ -320,23 +337,27 @@
}
fn is_ascii(v: &Vec<u8>) -> bool {
- for val in v {
- if val > &0x7e { return false; }
- }
- return true;
+ for val in v {
+ if val > &0x7e {
+ return false;
+ }
+ }
+ return true;
}
-fn is_printable_ascii(v: &Vec<u8>) ->bool {
- for val in v {
- if val < &0x20 || val > &0x7e { return false; }
- }
- return true;
+fn is_printable_ascii(v: &Vec<u8>) -> bool {
+ for val in v {
+ if val < &0x20 || val > &0x7e {
+ return false;
+ }
+ }
+ return true;
}
fn print_scan_result(ess: fidl_sme::EssInfo) {
let is_ascii = is_ascii(&ess.best_bss.ssid);
let is_ascii_print = is_printable_ascii(&ess.best_bss.ssid);
- let is_utf8 = String::from_utf8(ess.best_bss.ssid.clone()).is_ok();
+ let is_utf8 = String::from_utf8(ess.best_bss.ssid.clone()).is_ok();
let is_hex = !is_utf8 || (is_ascii && !is_ascii_print);
let ssid_str;
@@ -346,28 +367,34 @@
ssid_str = format!("\"{}\"", String::from_utf8_lossy(&ess.best_bss.ssid));
}
- println!("{} {:4} {:8} {:9} {}",
+ println!(
+ "{} {:4} {:8} {:9} {}",
MacAddr(ess.best_bss.bssid),
ess.best_bss.rx_dbm,
ess.best_bss.channel,
if ess.best_bss.protected { "Y" } else { "N" },
- ssid_str);
+ ssid_str
+ );
}
-async fn handle_connect_transaction(connect_txn: fidl_sme::ConnectTransactionProxy)
- -> Result<(), Error>
-{
+async fn handle_connect_transaction(
+ connect_txn: fidl_sme::ConnectTransactionProxy,
+) -> Result<(), Error> {
let mut events = connect_txn.take_event_stream();
- while let Some(evt) = await!(events.try_next()).context("failed to receive connect result before the channel was closed")? {
+ while let Some(evt) = await!(events.try_next())
+ .context("failed to receive connect result before the channel was closed")?
+ {
match evt {
ConnectTransactionEvent::OnFinished { code } => {
match code {
ConnectResultCode::Success => println!("Connected successfully"),
- ConnectResultCode::Canceled =>
- eprintln!("Connecting was canceled or superseded by another command"),
+ ConnectResultCode::Canceled => {
+ eprintln!("Connecting was canceled or superseded by another command")
+ }
ConnectResultCode::Failed => eprintln!("Failed to connect to network"),
- ConnectResultCode::BadCredentials =>
- eprintln!("Failed to connect to network; bad credentials"),
+ ConnectResultCode::BadCredentials => {
+ eprintln!("Failed to connect to network; bad credentials")
+ }
}
break;
}
@@ -376,11 +403,13 @@
Ok(())
}
-async fn get_client_sme(wlan_svc: WlanSvc, iface_id: u16)
- -> Result<fidl_sme::ClientSmeProxy, Error>
-{
+async fn get_client_sme(
+ wlan_svc: WlanSvc,
+ iface_id: u16,
+) -> Result<fidl_sme::ClientSmeProxy, Error> {
let (proxy, remote) = endpoints::create_proxy()?;
- let status = await!(wlan_svc.get_client_sme(iface_id, remote)).context("error sending GetClientSme request")?;
+ let status = await!(wlan_svc.get_client_sme(iface_id, remote))
+ .context("error sending GetClientSme request")?;
if status == zx::sys::ZX_OK {
Ok(proxy)
} else {
@@ -388,11 +417,10 @@
}
}
-async fn get_ap_sme(wlan_svc: WlanSvc, iface_id: u16)
- -> Result<fidl_sme::ApSmeProxy, Error>
-{
+async fn get_ap_sme(wlan_svc: WlanSvc, iface_id: u16) -> Result<fidl_sme::ApSmeProxy, Error> {
let (proxy, remote) = endpoints::create_proxy()?;
- let status = await!(wlan_svc.get_ap_sme(iface_id, remote)).context("error sending GetApSme request")?;
+ let status =
+ await!(wlan_svc.get_ap_sme(iface_id, remote)).context("error sending GetApSme request")?;
if status == zx::sys::ZX_OK {
Ok(proxy)
} else {
@@ -400,11 +428,10 @@
}
}
-async fn get_mesh_sme(wlan_svc: WlanSvc, iface_id: u16)
- -> Result<fidl_sme::MeshSmeProxy, Error>
-{
+async fn get_mesh_sme(wlan_svc: WlanSvc, iface_id: u16) -> Result<fidl_sme::MeshSmeProxy, Error> {
let (proxy, remote) = endpoints::create_proxy()?;
- let status = await!(wlan_svc.get_mesh_sme(iface_id, remote)).context("error sending GetMeshSme request")?;
+ let status = await!(wlan_svc.get_mesh_sme(iface_id, remote))
+ .context("error sending GetMeshSme request")?;
if status == zx::sys::ZX_OK {
Ok(proxy)
} else {
@@ -426,28 +453,36 @@
let (status, resp) = await!(wlan_svc.get_minstrel_list(iface_id))
.context(format!("Error getting minstrel peer list iface {}", iface_id))?;
if status == zx::sys::ZX_OK {
- Ok(resp.peers.into_iter().map(|v| {
- let mut arr = [0u8; 6];
- arr.copy_from_slice(v.as_slice());
- MacAddr(arr)
- }).collect())
+ Ok(resp
+ .peers
+ .into_iter()
+ .map(|v| {
+ let mut arr = [0u8; 6];
+ arr.copy_from_slice(v.as_slice());
+ MacAddr(arr)
+ })
+ .collect())
} else {
println!("Error getting minstrel peer list from iface {}: {}", iface_id, status);
Ok(vec![])
}
}
-async fn show_minstrel_peer_for_iface(wlan_svc: WlanSvc, id: u16, peer_addr: Option<MacAddr>)
- -> Result<(), Error>
-{
+async fn show_minstrel_peer_for_iface(
+ wlan_svc: WlanSvc,
+ id: u16,
+ peer_addr: Option<MacAddr>,
+) -> Result<(), Error> {
let peer_addrs = await!(get_peer_addrs(wlan_svc.clone(), id, peer_addr))?;
let mut first_peer = true;
for mut peer_addr in peer_addrs {
let (status, resp) = await!(wlan_svc.get_minstrel_stats(id, &mut peer_addr.0))
.context(format!("Error getting minstrel stats from peer {}", peer_addr))?;
if status != zx::sys::ZX_OK {
- println!("error getting minstrel stats for {} from iface {}: {}",
- peer_addr, id, status);
+ println!(
+ "error getting minstrel stats for {} from iface {}: {}",
+ peer_addr, id, status
+ );
} else if let Some(peer) = resp {
if first_peer {
println!("iface {}", id);
@@ -459,9 +494,11 @@
Ok(())
}
-
-async fn get_peer_addrs(wlan_svc: WlanSvc, iface_id: u16, peer_addr: Option<MacAddr>)
- -> Result<Vec<MacAddr>, Error> {
+async fn get_peer_addrs(
+ wlan_svc: WlanSvc,
+ iface_id: u16,
+ peer_addr: Option<MacAddr>,
+) -> Result<Vec<MacAddr>, Error> {
match peer_addr {
Some(addr) => Ok(vec![addr]),
None => await!(list_minstrel_peers(wlan_svc, iface_id)),
@@ -469,21 +506,34 @@
}
fn print_minstrel_stats(mut peer: Box<Peer>) {
- let total_attempts : f64 = peer.entries.iter().map(|e| e.attempts_total as f64).sum();
- let total_success : f64 = peer.entries.iter().map(|e| e.success_total as f64).sum();
- println!("{}, max_tp: {}, max_probability: {}, attempts/success: {:.6}, probes: {}",
- MacAddr(peer.mac_addr), peer.max_tp, peer.max_probability,
- total_attempts / total_success, peer.probes);
- println!(" TxVector succ_c att_c succ_t att_t \
- probability throughput probes probe_cycles_skipped");
+ let total_attempts: f64 = peer.entries.iter().map(|e| e.attempts_total as f64).sum();
+ let total_success: f64 = peer.entries.iter().map(|e| e.success_total as f64).sum();
+ println!(
+ "{}, max_tp: {}, max_probability: {}, attempts/success: {:.6}, probes: {}",
+ MacAddr(peer.mac_addr),
+ peer.max_tp,
+ peer.max_probability,
+ total_attempts / total_success,
+ peer.probes
+ );
+ println!(
+ " TxVector succ_c att_c succ_t att_t \
+ probability throughput probes probe_cycles_skipped"
+ );
peer.entries.sort_by(|l, r| l.tx_vector_idx.cmp(&r.tx_vector_idx));
for e in peer.entries {
- println!("{}{} {:<36} {:7} {:7} {:7} {:7} {:11.4} {:10.3} {:6} {:20}",
+ println!(
+ "{}{} {:<36} {:7} {:7} {:7} {:7} {:11.4} {:10.3} {:6} {:20}",
if e.tx_vector_idx == peer.max_tp { "T" } else { " " },
- if e.tx_vector_idx == peer.max_probability {"P"} else {" "},
- e.tx_vec_desc, e.success_cur, e.attempts_cur,
- e.success_total, e.attempts_total,
- e.probability * 100.0, e.cur_tp, e.probes_total,
+ if e.tx_vector_idx == peer.max_probability { "P" } else { " " },
+ e.tx_vec_desc,
+ e.success_cur,
+ e.attempts_cur,
+ e.success_total,
+ e.attempts_total,
+ e.probability * 100.0,
+ e.cur_tp,
+ e.probes_total,
e.probe_cycles_skipped,
);
}
@@ -495,16 +545,22 @@
#[test]
fn format_bssid() {
- assert_eq!("01:02:03:ab:cd:ef",
- format!("{}", MacAddr([ 0x01, 0x02, 0x03, 0xab, 0xcd, 0xef])));
+ assert_eq!(
+ "01:02:03:ab:cd:ef",
+ format!("{}", MacAddr([0x01, 0x02, 0x03, 0xab, 0xcd, 0xef]))
+ );
}
#[test]
fn mac_addr_from_str() {
- assert_eq!(MacAddr::from_str("01:02:03:ab:cd:ef").unwrap(),
- MacAddr([0x01, 0x02, 0x03, 0xab, 0xcd, 0xef]));
- assert_eq!(MacAddr::from_str("01:02-03:ab-cd:ef").unwrap(),
- MacAddr([0x01, 0x02, 0x03, 0xab, 0xcd, 0xef]));
+ assert_eq!(
+ MacAddr::from_str("01:02:03:ab:cd:ef").unwrap(),
+ MacAddr([0x01, 0x02, 0x03, 0xab, 0xcd, 0xef])
+ );
+ assert_eq!(
+ MacAddr::from_str("01:02-03:ab-cd:ef").unwrap(),
+ MacAddr([0x01, 0x02, 0x03, 0xab, 0xcd, 0xef])
+ );
assert!(MacAddr::from_str("01:02:03:ab:cd").is_err());
assert!(MacAddr::from_str("01:02:03:04:05:06:07").is_err());
assert!(MacAddr::from_str("01:02:gg:gg:gg:gg").is_err());
diff --git a/bin/wlan/wlantool/src/opts.rs b/bin/wlan/wlantool/src/opts.rs
index d935d23..c2482fc 100644
--- a/bin/wlan/wlantool/src/opts.rs
+++ b/bin/wlan/wlantool/src/opts.rs
@@ -5,11 +5,11 @@
#![allow(deprecated)] // Necessary for AsciiExt usage from clap args_enum macro
use clap::{_clap_count_exprs, arg_enum};
-use fidl_fuchsia_wlan_device as wlan;
use fidl_fuchsia_wlan_common as wlan_common;
+use fidl_fuchsia_wlan_device as wlan;
use structopt::StructOpt;
-arg_enum!{
+arg_enum! {
#[derive(PartialEq, Copy, Clone, Debug)]
pub enum RoleArg {
Client,
@@ -17,7 +17,7 @@
}
}
-arg_enum!{
+arg_enum! {
#[derive(PartialEq, Copy, Clone, Debug)]
pub enum PhyArg {
Erp,
@@ -26,7 +26,7 @@
}
}
-arg_enum!{
+arg_enum! {
#[derive(PartialEq, Copy, Clone, Debug)]
pub enum CbwArg {
Cbw20,
@@ -35,7 +35,7 @@
}
}
-arg_enum!{
+arg_enum! {
#[derive(PartialEq, Copy, Clone, Debug)]
pub enum ScanTypeArg {
Active,
@@ -127,8 +127,13 @@
/// id of the phy that will host the iface
phy_id: u16,
- #[structopt(short = "r", long = "role", raw(possible_values = "&RoleArg::variants()"),
- default_value = "Client", raw(case_insensitive = "true"))]
+ #[structopt(
+ short = "r",
+ long = "role",
+ raw(possible_values = "&RoleArg::variants()"),
+ default_value = "Client",
+ raw(case_insensitive = "true")
+ )]
/// role of the new iface
role: RoleArg,
},
@@ -153,9 +158,7 @@
iface_id: u16,
},
#[structopt(name = "stats")]
- Stats {
- iface_id: Option<u16>,
- },
+ Stats { iface_id: Option<u16> },
#[structopt(name = "minstrel")]
Minstrel(MinstrelCmd),
}
@@ -163,14 +166,9 @@
#[derive(StructOpt, Clone, Debug)]
pub enum MinstrelCmd {
#[structopt(name = "list")]
- List {
- iface_id: Option<u16>,
- },
+ List { iface_id: Option<u16> },
#[structopt(name = "show")]
- Show {
- iface_id: Option<u16>,
- peer_addr: Option<String>,
- },
+ Show { iface_id: Option<u16>, peer_addr: Option<String> },
}
#[derive(StructOpt, Clone, Debug)]
@@ -179,11 +177,15 @@
Scan {
#[structopt(raw(required = "true"))]
iface_id: u16,
- #[structopt(short = "s", long = "scan-type", default_value = "passive",
- raw(possible_values = "&ScanTypeArg::variants()"),
- raw(case_insensitive = "true"),
- help = "Experimental. Default scan type on each channel. \
- Behavior may differ on DFS channel")]
+ #[structopt(
+ short = "s",
+ long = "scan-type",
+ default_value = "passive",
+ raw(possible_values = "&ScanTypeArg::variants()"),
+ raw(case_insensitive = "true"),
+ help = "Experimental. Default scan type on each channel. \
+ Behavior may differ on DFS channel"
+ )]
scan_type: ScanTypeArg,
},
#[structopt(name = "connect")]
@@ -194,17 +196,31 @@
ssid: String,
#[structopt(short = "p", long = "password", help = "WPA2 PSK")]
password: Option<String>,
- #[structopt(short = "y", long = "phy", raw(possible_values = "&PhyArg::variants()"),
- raw(case_insensitive = "true"), help = "Specify an upper bound")]
+ #[structopt(
+ short = "y",
+ long = "phy",
+ raw(possible_values = "&PhyArg::variants()"),
+ raw(case_insensitive = "true"),
+ help = "Specify an upper bound"
+ )]
phy: Option<PhyArg>,
- #[structopt(short = "w", long = "cbw", raw(possible_values = "&CbwArg::variants()"),
- raw(case_insensitive = "true"), help = "Specify an upper bound")]
+ #[structopt(
+ short = "w",
+ long = "cbw",
+ raw(possible_values = "&CbwArg::variants()"),
+ raw(case_insensitive = "true"),
+ help = "Specify an upper bound"
+ )]
cbw: Option<CbwArg>,
- #[structopt(short = "s", long = "scan-type", default_value = "passive",
- raw(possible_values = "&ScanTypeArg::variants()"),
- raw(case_insensitive = "true"),
- help = "Experimental. Default scan type on each channel. \
- Behavior may differ on DFS channel")]
+ #[structopt(
+ short = "s",
+ long = "scan-type",
+ default_value = "passive",
+ raw(possible_values = "&ScanTypeArg::variants()"),
+ raw(case_insensitive = "true"),
+ help = "Experimental. Default scan type on each channel. \
+ Behavior may differ on DFS channel"
+ )]
scan_type: ScanTypeArg,
},
#[structopt(name = "disconnect")]
@@ -216,7 +232,7 @@
Status {
#[structopt(raw(required = "true"))]
iface_id: u16,
- }
+ },
}
#[derive(StructOpt, Clone, Debug)]
@@ -256,5 +272,5 @@
Leave {
#[structopt(raw(required = "true"))]
iface_id: u16,
- }
+ },
}