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 pub fn merge(&mut self, newer: Candidate) {
68 if newer.name.is_some() {
69 self.name = newer.name;
70 }
71 self.advertisement.merge(newer.advertisement);
72 }
73
74 #[cfg(feature = "classic")]
76 pub fn class_of_device(&self) -> Option<crate::classic::ClassOfDevice> {
77 self.advertisement.class_of_device
78 }
79}
80
81pub struct Candidates {
83 pub inner: crate::backlog::Receiver<Candidate>,
86}
87
88impl Stream for Candidates {
89 type Item = Candidate;
90 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Candidate>> {
91 Pin::new(&mut self.inner).poll_next(cx)
92 }
93}
94
95pub trait DeviceChooser: Send + Sync + 'static {
101 fn choose(&self, candidates: Candidates) -> BoxFuture<'static, Option<String>>;
106}
107
108#[derive(Debug, Clone)]
115pub struct FirstMatch {
116 timeout: Option<Duration>,
117}
118
119impl FirstMatch {
120 pub fn new() -> Self {
122 Self { timeout: None }
123 }
124
125 pub fn with_timeout(timeout: Duration) -> Self {
127 Self {
128 timeout: Some(timeout),
129 }
130 }
131}
132
133impl Default for FirstMatch {
134 fn default() -> Self {
135 Self::with_timeout(Duration::from_secs(10))
136 }
137}
138
139impl DeviceChooser for FirstMatch {
140 fn choose(&self, mut candidates: Candidates) -> BoxFuture<'static, Option<String>> {
141 let timeout = self.timeout;
142 Box::pin(async move {
143 let first = async move { candidates.next().await.map(|c| c.id) };
144 match timeout {
145 None => first.await,
146 Some(d) => timer::timeout(d, first).await.ok().flatten(),
147 }
148 })
149 }
150}
151
152#[derive(Debug, Clone)]
158pub struct StrongestSignal {
159 window: Duration,
160}
161
162impl StrongestSignal {
163 pub fn new(window: Duration) -> Self {
165 Self { window }
166 }
167}
168
169impl Default for StrongestSignal {
170 fn default() -> Self {
171 Self::new(Duration::from_secs(4))
172 }
173}
174
175impl DeviceChooser for StrongestSignal {
176 fn choose(&self, candidates: Candidates) -> BoxFuture<'static, Option<String>> {
177 let window = self.window;
178 Box::pin(async move {
179 let seen = collect_for(candidates, window).await;
180 seen.into_iter()
181 .max_by_key(|c| c.rssi().unwrap_or(i32::MIN))
182 .map(|c| c.id)
183 })
184 }
185}
186
187pub struct Predicate<F>(std::sync::Arc<F>);
192
193impl<F> Predicate<F>
194where
195 F: Fn(&Candidate) -> bool + Send + Sync + 'static,
196{
197 pub fn new(predicate: F) -> Self {
199 Self(std::sync::Arc::new(predicate))
200 }
201}
202
203impl<F> DeviceChooser for Predicate<F>
204where
205 F: Fn(&Candidate) -> bool + Send + Sync + 'static,
206{
207 fn choose(&self, mut candidates: Candidates) -> BoxFuture<'static, Option<String>> {
208 let predicate = self.0.clone();
209 Box::pin(async move {
210 while let Some(c) = candidates.next().await {
211 if predicate(&c) {
212 return Some(c.id);
213 }
214 }
215 None
216 })
217 }
218}
219
220async fn collect_for(mut candidates: Candidates, window: Duration) -> Vec<Candidate> {
223 let mut seen: HashMap<String, Candidate> = HashMap::new();
224 let gather = async {
225 while let Some(c) = candidates.next().await {
226 seen.insert(c.id.clone(), c);
227 }
228 };
229 let _ = timer::timeout(window, gather).await;
230 seen.into_values().collect()
231}
232
233#[cfg(feature = "terminal-chooser")]
239#[derive(Debug, Clone)]
240pub struct TerminalChooser {
241 window: Duration,
242 prompt: String,
243}
244
245#[cfg(feature = "terminal-chooser")]
246impl TerminalChooser {
247 pub fn new(window: Duration) -> Self {
249 Self {
250 window,
251 prompt: "Select a device".into(),
252 }
253 }
254
255 pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
257 self.prompt = prompt.into();
258 self
259 }
260}
261
262#[cfg(feature = "terminal-chooser")]
263impl Default for TerminalChooser {
264 fn default() -> Self {
265 Self::new(Duration::from_secs(5))
266 }
267}
268
269#[cfg(feature = "terminal-chooser")]
270impl DeviceChooser for TerminalChooser {
271 fn choose(&self, candidates: Candidates) -> BoxFuture<'static, Option<String>> {
272 use std::io::Write;
273 let (window, prompt) = (self.window, self.prompt.clone());
274 Box::pin(async move {
275 eprintln!("Scanning for {:.0}s…", window.as_secs_f32());
276 let mut found = collect_for(candidates, window).await;
277 if found.is_empty() {
278 eprintln!("No matching devices found.");
279 return None;
280 }
281 found.sort_by_key(|c| std::cmp::Reverse(c.rssi().unwrap_or(i32::MIN)));
282
283 eprintln!();
284 for (i, c) in found.iter().enumerate() {
285 match c.rssi() {
286 Some(db) => {
287 eprintln!(" [{}] {:<28} {:>4} dBm {}", i + 1, c.label(), db, c.id)
288 }
289 None => eprintln!(" [{}] {:<28} {:>8} {}", i + 1, c.label(), "—", c.id),
290 }
291 }
292 eprint!("\n{prompt} [1-{}, or Enter to cancel]: ", found.len());
293 let _ = std::io::stderr().flush();
294
295 let (tx, rx) = futures_channel::oneshot::channel();
297 std::thread::spawn(move || {
298 let mut line = String::new();
299 let ok = std::io::stdin().read_line(&mut line).is_ok();
300 let _ = tx.send(ok.then_some(line));
301 });
302 let line = rx.await.ok().flatten()?;
303
304 let n: usize = line.trim().parse().ok()?;
305 found.get(n.checked_sub(1)?).map(|c| c.id.clone())
306 })
307 }
308}
309
310#[cfg(test)]
311mod tests {
312 use super::*;
313
314 #[test]
318 fn merging_sightings_accumulates_what_each_packet_said() {
319 let service = crate::uuid::BluetoothUuid::from_u16(0x180f);
320 let mut seen = Candidate {
321 id: "device".into(),
322 name: None,
323 advertisement: Advertisement {
324 service_uuids: vec![service],
325 ..Advertisement::default()
326 },
327 };
328 seen.merge(Candidate {
329 id: "device".into(),
330 name: Some("Named".into()),
331 advertisement: Advertisement::default(),
332 });
333 seen.merge(Candidate {
334 id: "device".into(),
335 name: None,
336 advertisement: Advertisement::default(),
337 });
338
339 assert_eq!(seen.name.as_deref(), Some("Named"));
340 assert_eq!(seen.advertisement.service_uuids, vec![service]);
341 }
342}