Krolyxon
Commit c7666c2

Branches

Refs →

budctlcratesbudctl-guisrcworker.rs

388 lines · 13.9 KB · Rust

1//! The connection to the buds, on a thread of its own. budctl-core blocks, and a write with its
2//! read-back can take seconds, so the window never waits on it: it sends [`Command`]s and gets
3//! [`Event`]s back, in order, one per command.
4//!
5//! The session opens when a command needs it and closes after [`IDLE`] without one, so the
6//! control channel is free for other apps (CLAUDE.md, connection behavior). While it is open, the
7//! buds' own requests are answered.
8
9use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
10use std::thread;
11use std::time::{Duration, Instant};
12
13use budctl_core::bt::BdAddr;
14use budctl_core::devices::Session;
15use budctl_core::status::{
16 EqBand, EqPreset, EqPresets, Gesture, NoiseControl, NoiseMode, Status, Switch, TouchControls,
17};
18use budctl_core::{Error, Kind, Result};
19use iced::futures::channel::mpsc as channel;
20use iced::futures::{SinkExt, Stream, StreamExt};
21
22/// How long the session stays open after the last command.
23const IDLE: Duration = Duration::from_secs(10);
24/// How often an open session answers the buds while it waits for a command.
25const SERVE_EVERY: Duration = Duration::from_millis(100);
26
27#[derive(Debug, Clone)]
28pub enum Command {
29 /// Read everything, connecting first if needed.
30 Read,
31 Noise(NoiseMode),
32 /// A switch's key, and whether to turn it on.
33 Switch(&'static str, bool),
34 /// Select a built-in EQ preset, by name.
35 Eq(String),
36 /// Save a custom EQ preset (`custom-<id>`) with these bands changed, which also selects it.
37 /// With no bands, it only selects it.
38 CustomEq(String, Vec<EqBand>),
39 /// Give a bud's gesture an action, by name: `left`, `double-tap`, `play-pause`.
40 Touch {
41 side: String,
42 gesture: String,
43 action: String,
44 },
45 /// Set the noise-control modes a hold steps through.
46 HoldCycle(Vec<String>),
47 /// Start (`true`) or stop ringing the buds.
48 Find(bool),
49 /// Set the bass level.
50 Bass(i8),
51}
52
53#[derive(Debug, Clone)]
54pub enum Event {
55 /// The worker takes commands here.
56 Ready(Sender<Command>),
57 /// The buds a new session is for, by the name their owner gave them. Answers no command.
58 Found(String),
59 /// The answer to [`Command::Read`]. Boxed: it is much larger than the other events.
60 Read(Box<Reading>),
61 /// The answer to [`Command::Noise`]: what the buds report after the write.
62 Noise(NoiseControl),
63 /// The answer to [`Command::Switch`]: the switch, as read back.
64 Switch(Switch),
65 /// The answer to [`Command::Eq`]: the preset now in use.
66 Eq(String),
67 /// The answer to [`Command::CustomEq`]: the preset, as read back.
68 CustomEq(EqPreset),
69 /// The answer to [`Command::Touch`]: the whole gesture table, as read back.
70 Touch(Vec<Gesture>),
71 /// The answer to [`Command::HoldCycle`]: the modes, as read back.
72 HoldCycle(Vec<String>),
73 /// The answer to [`Command::Find`]: whether the buds were told to ring.
74 Ringing(bool),
75 /// The answer to [`Command::Bass`]: the level the buds took.
76 Bass(i8),
77 /// The answer to a command that failed. The session is closed; the next command opens a
78 /// new one.
79 Failed { kind: Kind, message: String },
80 /// The link dropped while the session waited. Answers no command.
81 Lost(String),
82}
83
84#[derive(Debug, Clone)]
85pub struct Reading {
86 pub status: Status,
87 /// The EQ presets, when the buds can list them: they name the custom ones.
88 pub eq: Option<EqPresets>,
89 /// The touch controls, when the buds report them.
90 pub touch: Option<TouchControls>,
91 /// The levels the bass level takes, when the buds have one to set.
92 pub bass_range: Option<(i8, i8)>,
93}
94
95/// The worker, as a stream of events for an iced subscription. `device` picks the buds, as
96/// `budctl --device` does.
97pub fn run(device: &Option<BdAddr>) -> impl Stream<Item = Event> + use<> {
98 let device = *device;
99 iced::stream::channel(16, async move |mut output: channel::Sender<Event>| {
100 let (commands, inbox) = mpsc::channel();
101 let (events, mut outbox) = channel::unbounded();
102 if output.send(Event::Ready(commands)).await.is_err() {
103 return;
104 }
105 let worker = Worker::new(bluetooth(device), events, IDLE);
106 let started = thread::Builder::new()
107 .name("budctl-buds".to_owned())
108 .spawn(move || worker.run(&inbox));
109 if let Err(e) = started {
110 let message = format!("could not start the Bluetooth thread: {e}");
111 let _ = output.send(Event::Lost(message)).await;
112 return;
113 }
114 while let Some(event) = outbox.next().await {
115 if output.send(event).await.is_err() {
116 break;
117 }
118 }
119 })
120}
121
122/// Finds the buds and opens a session, calling `found` with their name once it is known.
123type Connect = Box<dyn FnMut(&dyn Fn(String)) -> Result<Box<dyn Session>> + Send>;
124
125/// Over Bluetooth, through BlueZ: what the window uses. Tests use a fake.
126fn bluetooth(device: Option<BdAddr>) -> Connect {
127 Box::new(move |found| {
128 let (device, model) = budctl_core::select(budctl_core::scan()?, device)?;
129 found(device.alias.clone());
130 budctl_core::connect(&device, model)
131 })
132}
133
134struct Worker {
135 connect: Connect,
136 session: Option<Box<dyn Session>>,
137 events: channel::UnboundedSender<Event>,
138 last_command: Instant,
139 /// How long the session stays open after the last command.
140 idle: Duration,
141}
142
143impl Worker {
144 fn new(connect: Connect, events: channel::UnboundedSender<Event>, idle: Duration) -> Self {
145 Worker {
146 connect,
147 session: None,
148 events,
149 last_command: Instant::now(),
150 idle,
151 }
152 }
153
154 /// Runs until the window is gone.
155 fn run(mut self, inbox: &Receiver<Command>) {
156 loop {
157 let next = if self.session.is_some() {
158 inbox.recv_timeout(SERVE_EVERY)
159 } else {
160 inbox.recv().map_err(|_| RecvTimeoutError::Disconnected)
161 };
162 match next {
163 Ok(command) => {
164 self.last_command = Instant::now();
165 self.handle(command);
166 }
167 Err(RecvTimeoutError::Timeout) => self.wait(),
168 Err(RecvTimeoutError::Disconnected) => return,
169 }
170 }
171 }
172
173 /// Between commands: answer the buds, and close the session once it has been idle long
174 /// enough.
175 fn wait(&mut self) {
176 let Some(session) = self.session.as_mut() else {
177 return;
178 };
179 if self.last_command.elapsed() >= self.idle {
180 self.session = None;
181 if budctl_core::debug::enabled() {
182 eprintln!(
183 "# session closed after {} s without a command",
184 self.idle.as_secs()
185 );
186 }
187 } else if let Err(error) = session.serve() {
188 self.session = None;
189 self.send(Event::Lost(error.to_string()));
190 }
191 }
192
193 fn handle(&mut self, command: Command) {
194 let answer = match command {
195 Command::Read => self.read().map(|reading| Event::Read(Box::new(reading))),
196 Command::Noise(mode) => self
197 .session()
198 .and_then(|session| session.set_noise_control(mode))
199 .map(Event::Noise),
200 Command::Switch(key, on) => self
201 .session()
202 .and_then(|session| session.set_switch(key, on))
203 .map(Event::Switch),
204 Command::Eq(preset) => self
205 .session()
206 .and_then(|session| session.set_eq(&preset))
207 .map(Event::Eq),
208 Command::CustomEq(preset, bands) => self
209 .session()
210 .and_then(|session| session.set_custom_eq(&preset, &bands))
211 .map(Event::CustomEq),
212 Command::Touch { side, gesture, action } => self
213 .session()
214 .and_then(|session| session.set_touch(&side, &gesture, &action, false))
215 .map(|change| Event::Touch(change.gestures)),
216 Command::Bass(level) => self
217 .session()
218 .and_then(|session| session.set_bass_level(level))
219 .map(|()| Event::Bass(level)),
220 Command::Find(ring) => self
221 .session()
222 .and_then(|session| session.find(ring))
223 .map(|()| Event::Ringing(ring)),
224 Command::HoldCycle(modes) => {
225 let modes: Vec<&str> = modes.iter().map(String::as_str).collect();
226 self.session()
227 .and_then(|session| session.set_hold_cycle(&modes))
228 .map(Event::HoldCycle)
229 }
230 };
231 match answer {
232 Ok(event) => self.send(event),
233 Err(error) => {
234 self.session = None;
235 self.send(Event::Failed {
236 kind: error.kind(),
237 message: error.to_string(),
238 });
239 }
240 }
241 }
242
243 fn read(&mut self) -> Result<Reading> {
244 let session = self.session()?;
245 let status = session.status()?;
246 let eq = session.eq_presets().ok();
247 let touch = session.touch_controls().ok();
248 let bass_range = session.bass_range();
249 Ok(Reading {
250 status,
251 eq,
252 touch,
253 bass_range,
254 })
255 }
256
257 /// The open session, opening one first if there is none.
258 fn session(&mut self) -> Result<&mut Box<dyn Session>> {
259 if self.session.is_none() {
260 let events = self.events.clone();
261 let found = move |name| {
262 let _ = events.unbounded_send(Event::Found(name));
263 };
264 self.session = Some((self.connect)(&found)?);
265 }
266 self.session
267 .as_mut()
268 .ok_or_else(|| Error::NotConnected("the session closed".to_owned()))
269 }
270
271 fn send(&self, event: Event) {
272 // An error only means the window is gone; `run` ends on its next receive.
273 let _ = self.events.unbounded_send(event);
274 }
275}
276
277#[cfg(test)]
278mod tests {
279 use super::*;
280 use iced::futures::executor::block_on;
281 use std::sync::Arc;
282 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
283
284 /// What the fake sessions report back to the test.
285 #[derive(Clone, Default)]
286 struct Probe {
287 opened: Arc<AtomicUsize>,
288 served: Arc<AtomicUsize>,
289 closed: Arc<AtomicBool>,
290 /// Make `serve` fail, as when the buds drop the link.
291 drop_link: Arc<AtomicBool>,
292 }
293
294 struct Fake(Probe);
295
296 impl Session for Fake {
297 fn status(&mut self) -> Result<Status> {
298 Ok(Status::default())
299 }
300
301 fn serve(&mut self) -> Result<()> {
302 self.0.served.fetch_add(1, Ordering::SeqCst);
303 if self.0.drop_link.load(Ordering::SeqCst) {
304 return Err(Error::NotConnected("the buds closed the control link".to_owned()));
305 }
306 Ok(())
307 }
308 }
309
310 impl Drop for Fake {
311 fn drop(&mut self) {
312 self.0.closed.store(true, Ordering::SeqCst);
313 }
314 }
315
316 /// A worker on its own thread with fake buds, closing idle sessions after 200 ms.
317 fn start(
318 probe: &Probe,
319 ) -> (
320 Sender<Command>,
321 channel::UnboundedReceiver<Event>,
322 thread::JoinHandle<()>,
323 ) {
324 let fake = probe.clone();
325 let connect: Connect = Box::new(move |found| {
326 found("Fake buds".to_owned());
327 fake.opened.fetch_add(1, Ordering::SeqCst);
328 fake.closed.store(false, Ordering::SeqCst);
329 Ok(Box::new(Fake(fake.clone())))
330 });
331 let (events, outbox) = channel::unbounded();
332 let (commands, inbox) = mpsc::channel();
333 let worker = Worker::new(connect, events, Duration::from_millis(200));
334 let thread = thread::spawn(move || worker.run(&inbox));
335 (commands, outbox, thread)
336 }
337
338 /// Waits, at most 5 s, for `done`. A receive that times out stands in for a sleep.
339 fn wait_for(done: impl Fn() -> bool) {
340 let (_keep, never) = mpsc::channel::<()>();
341 let deadline = Instant::now() + Duration::from_secs(5);
342 while !done() {
343 assert!(Instant::now() < deadline, "gave up waiting");
344 let _ = never.recv_timeout(Duration::from_millis(10));
345 }
346 }
347
348 #[test]
349 fn an_idle_session_closes_and_the_next_command_opens_another() {
350 let probe = Probe::default();
351 let (commands, mut events, thread) = start(&probe);
352
353 commands.send(Command::Read).unwrap();
354 assert!(matches!(block_on(events.next()), Some(Event::Found(name)) if name == "Fake buds"));
355 assert!(matches!(block_on(events.next()), Some(Event::Read(_))));
356 assert_eq!(probe.opened.load(Ordering::SeqCst), 1);
357
358 // While it waits, it answers the buds; then it closes the session.
359 wait_for(|| probe.closed.load(Ordering::SeqCst));
360 assert!(probe.served.load(Ordering::SeqCst) > 0);
361
362 commands.send(Command::Read).unwrap();
363 assert!(matches!(block_on(events.next()), Some(Event::Found(_))));
364 assert!(matches!(block_on(events.next()), Some(Event::Read(_))));
365 assert_eq!(probe.opened.load(Ordering::SeqCst), 2);
366
367 // The window goes away: the worker ends.
368 drop(commands);
369 thread.join().unwrap();
370 }
371
372 #[test]
373 fn a_dropped_link_is_reported_once() {
374 let probe = Probe::default();
375 let (commands, mut events, thread) = start(&probe);
376 commands.send(Command::Read).unwrap();
377 let _ = block_on(events.next());
378 let _ = block_on(events.next());
379
380 probe.drop_link.store(true, Ordering::SeqCst);
381 assert!(matches!(block_on(events.next()), Some(Event::Lost(_))));
382 assert!(probe.closed.load(Ordering::SeqCst));
383
384 drop(commands);
385 thread.join().unwrap();
386 assert!(block_on(events.next()).is_none(), "nothing more after the link dropped");
387 }
388}