Skip to content

Commit

Permalink
Add a Chromecast discovery example
Browse files Browse the repository at this point in the history
  • Loading branch information
Dylan McKay committed Nov 27, 2016
1 parent 60b5160 commit acab2e5
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 0 deletions.
17 changes: 17 additions & 0 deletions examples/chromecast_discovery.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
extern crate mdns;

use std::time::Duration;

fn main() {
let duration = Duration::from_secs(5);

mdns::discover("_googlecast._tcp.local", Some(duration), |response| {
let addresses = response.records().filter_map(|record| {
if let mdns::RecordKind::A(addr) = record.kind { Some(addr) } else { None }
});

for address in addresses {
println!("found Chromecast on {}", address);
}
}).expect("error while performing Chromecast discovery");
}
35 changes: 35 additions & 0 deletions src/discover.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use {mDNS, Error, Response};
use std::time::{SystemTime, Duration};

use io;

pub fn discover<F>(service_name: &str,
duration: Option<Duration>,
mut f: F) -> Result<(), Error>
where F: FnMut(Response) {
let mut io = io::Io::new()?;

let mut mdns = mDNS::new(service_name)?;
io.register(&mut mdns)?;

let finish_at = duration.map(|duration| SystemTime::now() + duration);

loop {
let poll_timeout = finish_at.map(|finish_at| {
finish_at.duration_since(SystemTime::now()).unwrap()
});

io.poll(&mut mdns, poll_timeout)?;

for response in mdns.responses() {
f(response)
}

if let Some(finish_at) = finish_at {
if SystemTime::now() >= finish_at {
break;
}
}
}
Ok(())
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
pub use self::mdns::mDNS;
pub use self::response::{Response, Record, RecordKind};
pub use self::errors::{Error, ErrorKind};
pub use self::discover::discover;

pub mod mdns;
pub mod response;
pub mod errors;
pub mod discover;
mod io;

extern crate mio;
Expand Down
11 changes: 11 additions & 0 deletions src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,17 @@ impl Response
additional: packet.additional.iter().map(Record::from_resource_record).collect(),
}
}

pub fn records(&self) -> ::std::vec::IntoIter<&Record> {
let records: Vec<_> = vec![&self.answers, &self.nameservers, &self.additional].into_iter().flat_map(|c| c.iter()).collect();
records.into_iter()
}

pub fn is_empty(&self) -> bool {
self.answers.is_empty() &&
self.nameservers.is_empty() &&
self.additional.is_empty()
}
}

impl Record
Expand Down

0 comments on commit acab2e5

Please sign in to comment.