Krolyxon
Commit 56c56d4

Branches

Refs →

budctlcratesbudctl-guisrcworker.rs

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