Krolyxon
Commit a345a10

Branches

Refs →

budctlcratesbudctl-guisrcworker.rs

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