webbluetooth_core/
chooser.rs1use crate::filter::Advertisement;
16use crate::timer;
17use futures_core::Stream;
18pub use futures_util::future::BoxFuture;
25use futures_util::StreamExt;
26use std::collections::HashMap;
27use std::pin::Pin;
28use std::task::{Context, Poll};
29use std::time::Duration;
30
31#[derive(Debug, Clone)]
33pub struct Candidate {
34 pub id: String,
38 pub name: Option<String>,
40 pub advertisement: Advertisement,
42}
43
44impl Candidate {
45 pub fn rssi(&self) -> Option<i32> {
47 (self.advertisement.rssi != crate::filter::UNAVAILABLE_RSSI)
48 .then_some(self.advertisement.rssi)
49 }
50
51 pub fn label(&self) -> &str {
53 self.name.as_deref().unwrap_or(&self.id)
54 }
55
56 #[cfg(feature = "classic")]
58 pub fn class_of_device(&self) -> Option<crate::classic::ClassOfDevice> {
59 self.advertisement.class_of_device
60 }
61}
62
63pub struct Candidates {
65 pub inner: crate::backlog::Receiver<Candidate>,
68}
69
70impl Stream for Candidates {
71 type Item = Candidate;
72 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Candidate>> {
73 Pin::new(&mut self.inner).poll_next(cx)
74 }
75}
76
77pub trait DeviceChooser: Send + Sync + 'static {
83 fn choose(&self, candidates: Candidates) -> BoxFuture<'static, Option<String>>;
88}
89
90#[derive(Debug, Clone)]
97pub struct FirstMatch {
98 timeout: Option<Duration>,
99}
100
101impl FirstMatch {
102 pub fn new() -> Self {
104 Self { timeout: None }
105 }
106
107 pub fn with_timeout(timeout: Duration) -> Self {
109 Self {
110 timeout: Some(timeout),
111 }
112 }
113}
114
115impl Default for FirstMatch {
116 fn default() -> Self {
117 Self::with_timeout(Duration::from_secs(10))
118 }
119}
120
121impl DeviceChooser for FirstMatch {
122 fn choose(&self, mut candidates: Candidates) -> BoxFuture<'static, Option<String>> {
123 let timeout = self.timeout;
124 Box::pin(async move {
125 let first = async move { candidates.next().await.map(|c| c.id) };
126 match timeout {
127 None => first.await,
128 Some(d) => timer::timeout(d, first).await.ok().flatten(),
129 }
130 })
131 }
132}
133
134#[derive(Debug, Clone)]
140pub struct StrongestSignal {
141 window: Duration,
142}
143
144impl StrongestSignal {
145 pub fn new(window: Duration) -> Self {
147 Self { window }
148 }
149}
150
151impl Default for StrongestSignal {
152 fn default() -> Self {
153 Self::new(Duration::from_secs(4))
154 }
155}
156
157impl DeviceChooser for StrongestSignal {
158 fn choose(&self, candidates: Candidates) -> BoxFuture<'static, Option<String>> {
159 let window = self.window;
160 Box::pin(async move {
161 let seen = collect_for(candidates, window).await;
162 seen.into_iter()
163 .max_by_key(|c| c.rssi().unwrap_or(i32::MIN))
164 .map(|c| c.id)
165 })
166 }
167}
168
169pub struct Predicate<F>(std::sync::Arc<F>);
174
175impl<F> Predicate<F>
176where
177 F: Fn(&Candidate) -> bool + Send + Sync + 'static,
178{
179 pub fn new(predicate: F) -> Self {
181 Self(std::sync::Arc::new(predicate))
182 }
183}
184
185impl<F> DeviceChooser for Predicate<F>
186where
187 F: Fn(&Candidate) -> bool + Send + Sync + 'static,
188{
189 fn choose(&self, mut candidates: Candidates) -> BoxFuture<'static, Option<String>> {
190 let predicate = self.0.clone();
191 Box::pin(async move {
192 while let Some(c) = candidates.next().await {
193 if predicate(&c) {
194 return Some(c.id);
195 }
196 }
197 None
198 })
199 }
200}
201
202async fn collect_for(mut candidates: Candidates, window: Duration) -> Vec<Candidate> {
205 let mut seen: HashMap<String, Candidate> = HashMap::new();
206 let gather = async {
207 while let Some(c) = candidates.next().await {
208 seen.insert(c.id.clone(), c);
209 }
210 };
211 let _ = timer::timeout(window, gather).await;
212 seen.into_values().collect()
213}
214
215#[cfg(feature = "terminal-chooser")]
221#[derive(Debug, Clone)]
222pub struct TerminalChooser {
223 window: Duration,
224 prompt: String,
225}
226
227#[cfg(feature = "terminal-chooser")]
228impl TerminalChooser {
229 pub fn new(window: Duration) -> Self {
231 Self {
232 window,
233 prompt: "Select a device".into(),
234 }
235 }
236
237 pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
239 self.prompt = prompt.into();
240 self
241 }
242}
243
244#[cfg(feature = "terminal-chooser")]
245impl Default for TerminalChooser {
246 fn default() -> Self {
247 Self::new(Duration::from_secs(5))
248 }
249}
250
251#[cfg(feature = "terminal-chooser")]
252impl DeviceChooser for TerminalChooser {
253 fn choose(&self, candidates: Candidates) -> BoxFuture<'static, Option<String>> {
254 use std::io::Write;
255 let (window, prompt) = (self.window, self.prompt.clone());
256 Box::pin(async move {
257 eprintln!("Scanning for {:.0}s…", window.as_secs_f32());
258 let mut found = collect_for(candidates, window).await;
259 if found.is_empty() {
260 eprintln!("No matching devices found.");
261 return None;
262 }
263 found.sort_by_key(|c| std::cmp::Reverse(c.rssi().unwrap_or(i32::MIN)));
264
265 eprintln!();
266 for (i, c) in found.iter().enumerate() {
267 match c.rssi() {
268 Some(db) => {
269 eprintln!(" [{}] {:<28} {:>4} dBm {}", i + 1, c.label(), db, c.id)
270 }
271 None => eprintln!(" [{}] {:<28} {:>8} {}", i + 1, c.label(), "—", c.id),
272 }
273 }
274 eprint!("\n{prompt} [1-{}, or Enter to cancel]: ", found.len());
275 let _ = std::io::stderr().flush();
276
277 let (tx, rx) = futures_channel::oneshot::channel();
279 std::thread::spawn(move || {
280 let mut line = String::new();
281 let ok = std::io::stdin().read_line(&mut line).is_ok();
282 let _ = tx.send(ok.then_some(line));
283 });
284 let line = rx.await.ok().flatten()?;
285
286 let n: usize = line.trim().parse().ok()?;
287 found.get(n.checked_sub(1)?).map(|c| c.id.clone())
288 })
289 }
290}