Skip to content

Commit

Permalink
iwlist test cases 1 & 2 implemented
Browse files Browse the repository at this point in the history
  • Loading branch information
booyaa committed Aug 13, 2016
1 parent 851f30d commit f649195
Showing 1 changed file with 76 additions and 27 deletions.
103 changes: 76 additions & 27 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,10 @@ use regex::Regex;
pub enum Error {
SyntaxRegexError,
CommandNotFound,
NoMatch,
FailedToParse,
NoValue,
}
// impl From<regex::Error> for Error {
// fn from(err: regex::Error) -> Self {
// Error::SyntaxRegexError(err)
// }
// }

/// Wifi struct used to return information about wifi hotspots
#[derive(Debug,PartialEq,Eq)]
Expand All @@ -60,17 +58,8 @@ pub struct Wifi {

/// Returns WiFi hotspots in your area (OSX/MacOS)
#[cfg(target_os="macos")]
// pub fn scan() -> Result<Vec<Wifi>, String> {
pub fn scan() -> Result<Vec<Wifi>, Error> {
use std::process::Command;

// let output = match Command::new("/System/Library/PrivateFrameworks/Apple80211.\
// framework/Versions/Current/Resources/airport")
// .arg("-s")
// .output() {
// Ok(output) => output,
// Err(_) => return Err("Failed to find airport utility (are you using OSX?)".to_string()),
// };
let output = try!(Command::new("/System/Library/PrivateFrameworks/Apple80211.\
framework/Versions/Current/Resources/airport")
.arg("-s")
Expand Down Expand Up @@ -98,8 +87,7 @@ pub fn scan() -> Result<Vec<Wifi>, Error> {
}



// fn parse_airport(network_list: &str) -> Result<Vec<Wifi>, String> {
#[allow(dead_code)]
fn parse_airport(network_list: &str) -> Result<Vec<Wifi>, Error> {
println!("airport_parse");
let mut wifis: Vec<Wifi> = Vec::new();
Expand Down Expand Up @@ -133,46 +121,53 @@ fn parse_airport(network_list: &str) -> Result<Vec<Wifi>, Error> {
Ok(wifis)
}

#[allow(dead_code)]
fn parse_iwlist(network_list: &str) -> Result<Vec<Wifi>, Error> {
println!("Start");
let mut wifis: Vec<Wifi> = Vec::new();

let cell_regex = try!(Regex::new(r"Cell [0-9]{2,} - Address:")
.map_err(|_| Error::SyntaxRegexError));

println!("cell_regex");
let mac_regex =
try!(Regex::new(r"([0-9a-zA-Z]{1}[0-9a-zA-Z]{1}[:]{1}){5}[0-9a-zA-Z]{1}[0-9a-zA-Z]{1}")
.map_err(|_| Error::SyntaxRegexError));


println!("mac_regex");
for block in cell_regex.split(&network_list) {
println!("block");
let mut lines = block.lines();

let mut wifi_mac = String::new();
let mut wifi_ssid = String::new();
let mut wifi_channel = String::new();
let mut wifi_rssi = String::new();
let wifi_security = String::new();
let wifi_security = String::new(); // FIXME needs implementing


let mac_matches = mac_regex.captures(try!(lines.next().ok_or(Error::NoValue)));


let mac_matches = mac_regex.captures(lines.next().unwrap());
if let Some(matches) = mac_matches {
if let Some(mac) = matches.at(0) {
wifi_mac = mac.to_string();
}
}


for line in lines {
if line.find("ESSID:").is_some() {
let ssid = line.split(":").nth(1).unwrap_or("").replace("\"", "");
wifi_ssid = ssid.to_string();
// println!("SSID: {}", wifi_ssid);
} else if line.find("Frequency:").is_some() {
wifi_channel = line.split("Channel")
.nth(1)
.unwrap_or("")
.replace(")", "")
.trim()
.to_string();
// println!("Channel: {}", wifi_channel);
} else if line.find("Signal level").is_some() {
if line.find("Quality").is_some() {
// case1
Expand All @@ -182,16 +177,24 @@ fn parse_iwlist(network_list: &str) -> Result<Vec<Wifi>, Error> {
.replace("dBm", "")
.trim()
.to_string();
// println!("Signal level (case1): {}", wifi_rssi);
} else {
// case 3 (raspi)
println!("rssi: case 3 pending");
let re = try!(Regex::new(r"Signal level=(\d+)/100")
.map_err(|_| Error::SyntaxRegexError));
let value_raw = try!(try!(re.captures(line).ok_or(Error::FailedToParse))
.at(1)
.ok_or(Error::NoValue));
let value = try!(value_raw.parse::<i32>().map_err(|_| Error::FailedToParse));
let strength_calc = ((100 * value) / 100) / 2 - 100;
wifi_rssi = strength_calc.to_string();

// println!("Signal level (case3): {}", wifi_rssi);
}
}


// FIXME make less vomit inducing
if !wifi_ssid.is_empty() && !wifi_mac.is_empty() && !wifi_rssi.is_empty() {
println!("ssid: {} mac: {} ", wifi_ssid, wifi_mac);

wifis.push(Wifi {
ssid: wifi_ssid.to_string(),
mac: wifi_mac.to_string(),
Expand All @@ -200,20 +203,64 @@ fn parse_iwlist(network_list: &str) -> Result<Vec<Wifi>, Error> {
security: wifi_security.to_string(),
});

println!("\tAdded {} to vec", wifi_mac);
wifi_ssid = String::new();
wifi_mac = String::new();
wifi_rssi = String::new();
wifi_channel = String::new();
}

// else {
// println!("no wifi");
// continue;
// }
// println!("end of lines");
} // for

}
Ok(wifis)
}

#[cfg(test)]
#[test]
fn should_parse_iwlist_type_1() {
let mut expected: Vec<Wifi> = Vec::new();
expected.push(Wifi {
mac: "00:35:1A:6F:0F:40".to_string(),
ssid: "TEST-Wifi".to_string(),
channel: "6".to_string(),
signal_level: "-72".to_string(),
security: "".to_string(),
});

expected.push(Wifi {
mac: "00:F2:8B:8F:58:77".to_string(),
ssid: "<hidden>".to_string(),
channel: "11".to_string(),
signal_level: "-71".to_string(),
security: "".to_string(),
});

// FIXME: should be a better way to create test fixtures
use std::path::PathBuf;
let mut path = PathBuf::new();
path.push("tests");
path.push("fixtures");
path.push("iwlist");
path.push("iwlist01_ubuntu1404.txt");

let file_path = path.as_os_str();

Ok(wifis)
use std::fs::File;
use std::io::Read;

let mut file = File::open(&file_path).unwrap();

let mut filestr = String::new();
let result = file.read_to_string(&mut filestr).unwrap();
println!("Read {} bytes", result);

let result = parse_iwlist(&filestr).unwrap();
assert_eq!(expected[0], result[0]);
assert_eq!(expected[1], result[28]);
}

#[cfg(test)]
Expand All @@ -237,6 +284,7 @@ fn should_parse_iwlist_type_2() {
security: "".to_string(),
});

// FIXME: should be a better way to create test fixtures
use std::path::PathBuf;
let mut path = PathBuf::new();
path.push("tests");
Expand Down Expand Up @@ -280,6 +328,7 @@ fn should_parse_airport() {
security: "WPA2(PSK/AES/AES)".to_string(),
});

// FIXME: should be a better way to create test fixtures
use std::path::PathBuf;
let mut path = PathBuf::new();
path.push("tests");
Expand Down

0 comments on commit f649195

Please sign in to comment.