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
57pub struct Candidates {
59 pub inner: crate::backlog::Receiver<Candidate>,
62}
63
64impl Stream for Candidates {
65 type Item = Candidate;
66 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Candidate>> {
67 Pin::new(&mut self.inner).poll_next(cx)
68 }
69}
70
71pub trait DeviceChooser: Send + Sync + 'static {
77 fn choose(&self, candidates: Candidates) -> BoxFuture<'static, Option<String>>;
82}
83
84#[derive(Debug, Clone)]
91pub struct FirstMatch {
92 timeout: Option<Duration>,
93}
94
95impl FirstMatch {
96 pub fn new() -> Self {
98 Self { timeout: None }
99 }
100
101 pub fn with_timeout(timeout: Duration) -> Self {
103 Self {
104 timeout: Some(timeout),
105 }
106 }
107}
108
109impl Default for FirstMatch {
110 fn default() -> Self {
111 Self::with_timeout(Duration::from_secs(10))
112 }
113}
114
115impl DeviceChooser for FirstMatch {
116 fn choose(&self, mut candidates: Candidates) -> BoxFuture<'static, Option<String>> {
117 let timeout = self.timeout;
118 Box::pin(async move {
119 let first = async move { candidates.next().await.map(|c| c.id) };
120 match timeout {
121 None => first.await,
122 Some(d) => timer::timeout(d, first).await.ok().flatten(),
123 }
124 })
125 }
126}
127
128#[derive(Debug, Clone)]
134pub struct StrongestSignal {
135 window: Duration,
136}
137
138impl StrongestSignal {
139 pub fn new(window: Duration) -> Self {
141 Self { window }
142 }
143}
144
145impl Default for StrongestSignal {
146 fn default() -> Self {
147 Self::new(Duration::from_secs(4))
148 }
149}
150
151impl DeviceChooser for StrongestSignal {
152 fn choose(&self, candidates: Candidates) -> BoxFuture<'static, Option<String>> {
153 let window = self.window;
154 Box::pin(async move {
155 let seen = collect_for(candidates, window).await;
156 seen.into_iter()
157 .max_by_key(|c| c.rssi().unwrap_or(i32::MIN))
158 .map(|c| c.id)
159 })
160 }
161}
162
163pub struct Predicate<F>(std::sync::Arc<F>);
168
169impl<F> Predicate<F>
170where
171 F: Fn(&Candidate) -> bool + Send + Sync + 'static,
172{
173 pub fn new(predicate: F) -> Self {
175 Self(std::sync::Arc::new(predicate))
176 }
177}
178
179impl<F> DeviceChooser for Predicate<F>
180where
181 F: Fn(&Candidate) -> bool + Send + Sync + 'static,
182{
183 fn choose(&self, mut candidates: Candidates) -> BoxFuture<'static, Option<String>> {
184 let predicate = self.0.clone();
185 Box::pin(async move {
186 while let Some(c) = candidates.next().await {
187 if predicate(&c) {
188 return Some(c.id);
189 }
190 }
191 None
192 })
193 }
194}
195
196async fn collect_for(mut candidates: Candidates, window: Duration) -> Vec<Candidate> {
199 let mut seen: HashMap<String, Candidate> = HashMap::new();
200 let gather = async {
201 while let Some(c) = candidates.next().await {
202 seen.insert(c.id.clone(), c);
203 }
204 };
205 let _ = timer::timeout(window, gather).await;
206 seen.into_values().collect()
207}
208
209#[cfg(feature = "terminal-chooser")]
215#[derive(Debug, Clone)]
216pub struct TerminalChooser {
217 window: Duration,
218 prompt: String,
219}
220
221#[cfg(feature = "terminal-chooser")]
222impl TerminalChooser {
223 pub fn new(window: Duration) -> Self {
225 Self {
226 window,
227 prompt: "Select a device".into(),
228 }
229 }
230
231 pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
233 self.prompt = prompt.into();
234 self
235 }
236}
237
238#[cfg(feature = "terminal-chooser")]
239impl Default for TerminalChooser {
240 fn default() -> Self {
241 Self::new(Duration::from_secs(5))
242 }
243}
244
245#[cfg(feature = "terminal-chooser")]
246impl DeviceChooser for TerminalChooser {
247 fn choose(&self, candidates: Candidates) -> BoxFuture<'static, Option<String>> {
248 use std::io::Write;
249 let (window, prompt) = (self.window, self.prompt.clone());
250 Box::pin(async move {
251 eprintln!("Scanning for {:.0}s…", window.as_secs_f32());
252 let mut found = collect_for(candidates, window).await;
253 if found.is_empty() {
254 eprintln!("No matching devices found.");
255 return None;
256 }
257 found.sort_by_key(|c| std::cmp::Reverse(c.rssi().unwrap_or(i32::MIN)));
258
259 eprintln!();
260 for (i, c) in found.iter().enumerate() {
261 match c.rssi() {
262 Some(db) => {
263 eprintln!(" [{}] {:<28} {:>4} dBm {}", i + 1, c.label(), db, c.id)
264 }
265 None => eprintln!(" [{}] {:<28} {:>8} {}", i + 1, c.label(), "—", c.id),
266 }
267 }
268 eprint!("\n{prompt} [1-{}, or Enter to cancel]: ", found.len());
269 let _ = std::io::stderr().flush();
270
271 let (tx, rx) = futures_channel::oneshot::channel();
273 std::thread::spawn(move || {
274 let mut line = String::new();
275 let ok = std::io::stdin().read_line(&mut line).is_ok();
276 let _ = tx.send(ok.then_some(line));
277 });
278 let line = rx.await.ok().flatten()?;
279
280 let n: usize = line.trim().parse().ok()?;
281 found.get(n.checked_sub(1)?).map(|c| c.id.clone())
282 })
283 }
284}