Krolyxon
Commit 4276e2b

Branches

Refs →

budctlcratesbudctl-guisrcworker.rs

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