use crate::filter::Advertisement;
use crate::timer;
use futures_core::Stream;
pub use futures_util::future::BoxFuture;
use futures_util::StreamExt;
use std::collections::HashMap;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
#[derive(Debug, Clone)]
pub struct Candidate {
pub id: String,
pub name: Option<String>,
pub advertisement: Advertisement,
}
impl Candidate {
pub fn rssi(&self) -> Option<i32> {
(self.advertisement.rssi != crate::filter::UNAVAILABLE_RSSI)
.then_some(self.advertisement.rssi)
}
pub fn label(&self) -> &str {
self.name.as_deref().unwrap_or(&self.id)
}
pub fn merge(&mut self, newer: Candidate) {
if newer.name.is_some() {
self.name = newer.name;
}
self.advertisement.merge(newer.advertisement);
}
#[cfg(feature = "classic")]
pub fn class_of_device(&self) -> Option<crate::classic::ClassOfDevice> {
self.advertisement.class_of_device
}
}
pub struct Candidates {
pub inner: crate::backlog::Receiver<Candidate>,
}
impl Stream for Candidates {
type Item = Candidate;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Candidate>> {
Pin::new(&mut self.inner).poll_next(cx)
}
}
pub trait DeviceChooser: Send + Sync + 'static {
fn choose(&self, candidates: Candidates) -> BoxFuture<'static, Option<String>>;
}
#[derive(Debug, Clone)]
pub struct FirstMatch {
timeout: Option<Duration>,
}
impl FirstMatch {
pub fn new() -> Self {
Self { timeout: None }
}
pub fn with_timeout(timeout: Duration) -> Self {
Self {
timeout: Some(timeout),
}
}
}
impl Default for FirstMatch {
fn default() -> Self {
Self::with_timeout(Duration::from_secs(10))
}
}
impl DeviceChooser for FirstMatch {
fn choose(&self, mut candidates: Candidates) -> BoxFuture<'static, Option<String>> {
let timeout = self.timeout;
Box::pin(async move {
let first = async move { candidates.next().await.map(|c| c.id) };
match timeout {
None => first.await,
Some(d) => timer::timeout(d, first).await.ok().flatten(),
}
})
}
}
#[derive(Debug, Clone)]
pub struct StrongestSignal {
window: Duration,
}
impl StrongestSignal {
pub fn new(window: Duration) -> Self {
Self { window }
}
}
impl Default for StrongestSignal {
fn default() -> Self {
Self::new(Duration::from_secs(4))
}
}
impl DeviceChooser for StrongestSignal {
fn choose(&self, candidates: Candidates) -> BoxFuture<'static, Option<String>> {
let window = self.window;
Box::pin(async move {
let seen = collect_for(candidates, window).await;
seen.into_iter()
.max_by_key(|c| c.rssi().unwrap_or(i32::MIN))
.map(|c| c.id)
})
}
}
pub struct Predicate<F>(std::sync::Arc<F>);
impl<F> Predicate<F>
where
F: Fn(&Candidate) -> bool + Send + Sync + 'static,
{
pub fn new(predicate: F) -> Self {
Self(std::sync::Arc::new(predicate))
}
}
impl<F> DeviceChooser for Predicate<F>
where
F: Fn(&Candidate) -> bool + Send + Sync + 'static,
{
fn choose(&self, mut candidates: Candidates) -> BoxFuture<'static, Option<String>> {
let predicate = self.0.clone();
Box::pin(async move {
while let Some(c) = candidates.next().await {
if predicate(&c) {
return Some(c.id);
}
}
None
})
}
}
async fn collect_for(mut candidates: Candidates, window: Duration) -> Vec<Candidate> {
let mut seen: HashMap<String, Candidate> = HashMap::new();
let gather = async {
while let Some(c) = candidates.next().await {
seen.insert(c.id.clone(), c);
}
};
let _ = timer::timeout(window, gather).await;
seen.into_values().collect()
}
#[cfg(feature = "terminal-chooser")]
#[derive(Debug, Clone)]
pub struct TerminalChooser {
window: Duration,
prompt: String,
}
#[cfg(feature = "terminal-chooser")]
impl TerminalChooser {
pub fn new(window: Duration) -> Self {
Self {
window,
prompt: "Select a device".into(),
}
}
pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
self.prompt = prompt.into();
self
}
}
#[cfg(feature = "terminal-chooser")]
impl Default for TerminalChooser {
fn default() -> Self {
Self::new(Duration::from_secs(5))
}
}
#[cfg(feature = "terminal-chooser")]
impl DeviceChooser for TerminalChooser {
fn choose(&self, candidates: Candidates) -> BoxFuture<'static, Option<String>> {
use std::io::Write;
let (window, prompt) = (self.window, self.prompt.clone());
Box::pin(async move {
eprintln!("Scanning for {:.0}s…", window.as_secs_f32());
let mut found = collect_for(candidates, window).await;
if found.is_empty() {
eprintln!("No matching devices found.");
return None;
}
found.sort_by_key(|c| std::cmp::Reverse(c.rssi().unwrap_or(i32::MIN)));
eprintln!();
for (i, c) in found.iter().enumerate() {
match c.rssi() {
Some(db) => {
eprintln!(" [{}] {:<28} {:>4} dBm {}", i + 1, c.label(), db, c.id)
}
None => eprintln!(" [{}] {:<28} {:>8} {}", i + 1, c.label(), "—", c.id),
}
}
eprint!("\n{prompt} [1-{}, or Enter to cancel]: ", found.len());
let _ = std::io::stderr().flush();
let (tx, rx) = futures_channel::oneshot::channel();
std::thread::spawn(move || {
let mut line = String::new();
let ok = std::io::stdin().read_line(&mut line).is_ok();
let _ = tx.send(ok.then_some(line));
});
let line = rx.await.ok().flatten()?;
let n: usize = line.trim().parse().ok()?;
found.get(n.checked_sub(1)?).map(|c| c.id.clone())
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn merging_sightings_accumulates_what_each_packet_said() {
let service = crate::uuid::BluetoothUuid::from_u16(0x180f);
let mut seen = Candidate {
id: "device".into(),
name: None,
advertisement: Advertisement {
service_uuids: vec![service],
..Advertisement::default()
},
};
seen.merge(Candidate {
id: "device".into(),
name: Some("Named".into()),
advertisement: Advertisement::default(),
});
seen.merge(Candidate {
id: "device".into(),
name: None,
advertisement: Advertisement::default(),
});
assert_eq!(seen.name.as_deref(), Some("Named"));
assert_eq!(seen.advertisement.service_uuids, vec![service]);
}
}