Krolyxon
Commit 9500e1e

Branches

Refs →

budctlcratesbudctl-clisrcmain.rs

457 lines · 14.9 KB · Rust

1//! `budctl`: control wireless earbuds from Linux.
2//!
3//! A thin layer over budctl-core: parse the command line, run one command, print the result,
4//! turn errors into the exit codes listed in CLAUDE.md.
5
6mod output;
7
8use std::io::{self, Write};
9use std::process::ExitCode;
10
11use budctl_core::bt::BdAddr;
12use budctl_core::status::{AncLevel, EqBand, NoiseMode};
13use budctl_core::{Error, Kind};
14use clap::{Parser, Subcommand, ValueEnum};
15
16/// Control wireless earbuds from Linux, without the vendor app.
17#[derive(Parser)]
18#[command(name = "budctl", version)]
19struct Cli {
20 /// The buds to use, when more than one supported pair is paired. Default: "device" in
21 /// ~/.config/budctl/config.json.
22 #[arg(long, global = true, value_name = "MAC")]
23 device: Option<BdAddr>,
24
25 /// Machine-readable output (JSON with "schema": 1).
26 #[arg(long, global = true)]
27 json: bool,
28
29 /// Hex-dump every frame sent and received on stderr.
30 #[arg(long, global = true)]
31 debug: bool,
32
33 #[command(subcommand)]
34 command: Command,
35}
36
37#[derive(Subcommand)]
38enum Command {
39 /// Paired devices and whether budctl recognizes them.
40 List,
41 /// Battery, noise control, EQ and switches.
42 Status,
43 /// Touch controls (gesture table) of each bud, or give one gesture a new action.
44 ///
45 /// Gestures: double-tap, triple-tap, hold. Actions: none, play-pause, next, previous,
46 /// voice-assistant, volume-up, volume-down, noise-cycle, game-mode (not every gesture takes
47 /// every action). `budctl touch cycle …` sets what a hold steps through.
48 #[command(args_conflicts_with_subcommands = true)]
49 Touch {
50 #[command(subcommand)]
51 cycle: Option<TouchCommand>,
52 /// The bud to change: left, right, or both.
53 #[arg(value_enum, requires = "gesture")]
54 side: Option<Side>,
55 /// The gesture to change.
56 #[arg(requires = "action")]
57 gesture: Option<String>,
58 /// Its new action.
59 action: Option<String>,
60 /// Read the table and show the write, but send nothing.
61 #[arg(long, requires = "side")]
62 dry_run: bool,
63 },
64 /// Set noise control, then read it back.
65 Anc {
66 #[arg(value_enum)]
67 mode: AncArg,
68 },
69 /// List the EQ presets, or select one (pure-raw, deep-bass, pure-vocals, pure-bass, custom-<id>) and read it back.
70 ///
71 /// For a custom preset, `<hz>=<gain>` pairs change those bands' gains (dB), then save and
72 /// select it: `budctl eq custom-4 50=+3 16000=-2`. `budctl eq new <name>` creates a preset,
73 /// `budctl eq rename custom-<id> <name>` renames one, `budctl eq delete custom-<id>` deletes one.
74 #[command(args_conflicts_with_subcommands = true)]
75 Eq {
76 #[command(subcommand)]
77 action: Option<EqCommand>,
78 preset: Option<String>,
79 /// Bands to change, as `<hz>=<gain>`. Custom presets only.
80 #[arg(requires = "preset", value_parser = parse_band, allow_negative_numbers = true)]
81 bands: Vec<EqBand>,
82 },
83 /// Turn an on/off setting on or off, then read it back. Switches: game, bass-boost, spatial (3D sound), wind, dual.
84 Set {
85 /// The switch's name, as `status --json` lists it.
86 switch: String,
87 #[arg(value_enum)]
88 state: OnOff,
89 },
90 /// Set the bass level, -5 to +5. The buds cannot report it back, so only their ack is checked.
91 Bass {
92 /// Checked here, before connecting; core checks it again.
93 #[arg(allow_negative_numbers = true, value_parser = clap::value_parser!(i8).range(-5..=5))]
94 level: i8,
95 },
96 /// Ring the buds so you can find them (loud: take them out of your ears first).
97 Find {
98 #[arg(value_enum)]
99 action: FindAction,
100 /// Confirm that the buds are out of your ears. Needed to start ringing.
101 #[arg(long)]
102 yes: bool,
103 },
104 /// Turn game mode (low latency) on or off, then read it back.
105 Game {
106 #[arg(value_enum)]
107 state: OnOff,
108 },
109 /// The phones and computers the buds keep for dual connection, and which are connected.
110 Dual,
111}
112
113#[derive(Clone, Copy, ValueEnum)]
114enum FindAction {
115 Start,
116 Stop,
117}
118
119#[derive(Subcommand)]
120enum EqCommand {
121 /// Create a custom preset, flat, with the bands of the buds' custom presets, then read it back.
122 New {
123 /// Its name, 1 to 16 bytes.
124 #[arg(value_parser = parse_name)]
125 name: String,
126 },
127 /// Give a custom preset a new name, then read it back. The buds save it, which also selects
128 /// it.
129 Rename {
130 /// The preset, as `budctl eq` lists it: custom-<id>.
131 preset: String,
132 /// Its new name, 1 to 16 bytes.
133 #[arg(value_parser = parse_name)]
134 name: String,
135 },
136 /// Delete a custom preset, then read the list back. Its bands are lost.
137 Delete {
138 /// The preset, as `budctl eq` lists it: custom-<id>.
139 preset: String,
140 },
141}
142
143#[derive(Subcommand)]
144enum TouchCommand {
145 /// Set the noise-control modes a hold steps through (both buds), then read it back.
146 ///
147 /// At least two modes. The buds step through them in their own order.
148 Cycle {
149 #[arg(value_enum, required = true, num_args = 2..=3, value_name = "MODE")]
150 modes: Vec<CycleMode>,
151 },
152}
153
154#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)]
155enum CycleMode {
156 Off,
157 Transparency,
158 /// Noise cancelling.
159 Anc,
160}
161
162impl CycleMode {
163 fn name(self) -> &'static str {
164 match self {
165 CycleMode::Off => "off",
166 CycleMode::Transparency => "transparency",
167 CycleMode::Anc => "anc",
168 }
169 }
170}
171
172#[derive(Clone, Copy, ValueEnum)]
173enum Side {
174 Left,
175 Right,
176 /// The left and the right bud.
177 Both,
178}
179
180impl Side {
181 fn name(self) -> &'static str {
182 match self {
183 Side::Left => "left",
184 Side::Right => "right",
185 Side::Both => "both",
186 }
187 }
188}
189
190#[derive(Clone, Copy, ValueEnum)]
191enum OnOff {
192 On,
193 Off,
194}
195
196#[derive(Clone, Copy, ValueEnum)]
197enum AncArg {
198 Off,
199 Transparency,
200 /// Noise cancelling at the deep level (the buds use the same value for both).
201 On,
202 Light,
203 Medium,
204 Deep,
205}
206
207impl From<AncArg> for NoiseMode {
208 fn from(arg: AncArg) -> Self {
209 match arg {
210 AncArg::Off => NoiseMode::Off,
211 AncArg::On | AncArg::Deep => NoiseMode::Anc(AncLevel::Deep),
212 AncArg::Light => NoiseMode::Anc(AncLevel::Light),
213 AncArg::Medium => NoiseMode::Anc(AncLevel::Medium),
214 AncArg::Transparency => NoiseMode::Transparency,
215 }
216 }
217}
218
219fn main() -> ExitCode {
220 let cli = match Cli::try_parse() {
221 Ok(cli) => cli,
222 Err(error) => {
223 // Help and version are not errors; everything else is a usage error (exit 1).
224 let code = if error.use_stderr() { 1 } else { 0 };
225 // Nothing useful can be done if printing the usage message fails.
226 let _ = error.print();
227 return ExitCode::from(code);
228 }
229 };
230 if cli.debug {
231 budctl_core::debug::enable();
232 }
233
234 let mut stdout = io::stdout().lock();
235 let result = run(&cli, &mut stdout).and_then(|()| stdout.flush().map_err(output::Failure::Io));
236 match result {
237 Ok(()) => ExitCode::SUCCESS,
238 // `budctl status | head -1` is fine.
239 Err(output::Failure::Io(e)) if e.kind() == io::ErrorKind::BrokenPipe => ExitCode::SUCCESS,
240 Err(output::Failure::Io(e)) => {
241 eprintln!("budctl: cannot write output: {e}");
242 ExitCode::from(1)
243 }
244 Err(output::Failure::Budctl(e)) => {
245 eprintln!("budctl: {e}");
246 ExitCode::from(exit_code(&e))
247 }
248 }
249}
250
251/// The config's default device. A config that cannot be used is reported and left out, so it
252/// never stops a command.
253fn default_device() -> Option<BdAddr> {
254 let (config, problem) = budctl_core::config::load();
255 if let Some(problem) = problem {
256 eprintln!("budctl: {problem}; ignoring it");
257 }
258 config.device().unwrap_or_default()
259}
260
261fn run(cli: &Cli, out: &mut impl Write) -> Result<(), output::Failure> {
262 // Checked before connecting: ringing is loud. Spec: realme_t310.md#find
263 if let Command::Find {
264 action: FindAction::Start,
265 yes: false,
266 } = cli.command
267 {
268 return Err(Error::Usage(
269 "this rings the buds loudly; take them out of your ears, then run `budctl find start --yes`".to_owned(),
270 )
271 .into());
272 }
273 let found = budctl_core::scan()?;
274 if let Command::List = cli.command {
275 return output::list(out, &found, cli.json);
276 }
277
278 let (device, model) = budctl_core::select(found, cli.device.or_else(default_device))?;
279 let mut session = budctl_core::connect(&device, model)?;
280 match cli.command {
281 Command::List => Ok(()),
282 Command::Status => {
283 let status = session.status()?;
284 output::status(out, &device, model, &status, cli.json)
285 }
286 Command::Touch {
287 cycle: Some(TouchCommand::Cycle { ref modes }),
288 ..
289 } => {
290 let names: Vec<&str> = modes.iter().map(|m| m.name()).collect();
291 let now = session.set_hold_cycle(&names)?;
292 output::hold_cycle(out, &device, model, &now, cli.json)
293 }
294 Command::Touch {
295 side: Some(side),
296 gesture: Some(ref gesture),
297 action: Some(ref action),
298 dry_run,
299 ..
300 } => {
301 let change = session.set_touch(side.name(), gesture, action, dry_run)?;
302 output::touch_change(out, &device, model, &change, cli.json)
303 }
304 Command::Touch { .. } => {
305 let touch = session.touch_controls()?;
306 output::touch(out, &device, model, &touch, cli.json)
307 }
308 Command::Anc { mode } => {
309 let now = session.set_noise_control(mode.into())?;
310 output::noise_control(out, &device, model, &now, cli.json)
311 }
312 Command::Eq {
313 action: Some(EqCommand::New { ref name }),
314 ..
315 } => {
316 let created = session.create_custom_eq(name)?;
317 output::created_eq(out, &device, model, &created, cli.json)
318 }
319 Command::Eq {
320 action: Some(EqCommand::Rename { ref preset, ref name }),
321 ..
322 } => {
323 let now = session.rename_custom_eq(preset, name)?;
324 output::renamed_eq(out, &device, model, &now, cli.json)
325 }
326 Command::Eq {
327 action: Some(EqCommand::Delete { ref preset }),
328 ..
329 } => {
330 let left = session.delete_custom_eq(preset)?;
331 output::deleted_eq(out, &device, model, preset, &left, cli.json)
332 }
333 Command::Eq { preset: None, .. } => {
334 let presets = session.eq_presets()?;
335 output::eq_presets(out, &device, model, &presets, cli.json)
336 }
337 Command::Eq {
338 preset: Some(ref preset),
339 ref bands,
340 ..
341 } if !bands.is_empty() => {
342 let now = session.set_custom_eq(preset, bands)?;
343 output::custom_eq(out, &device, model, &now, cli.json)
344 }
345 Command::Eq {
346 preset: Some(ref preset),
347 ..
348 } => {
349 let now = session.set_eq(preset)?;
350 output::eq(out, &device, model, &now, cli.json)
351 }
352 Command::Set { ref switch, state } => {
353 let now = session.set_switch(switch, matches!(state, OnOff::On))?;
354 output::switch(out, &device, model, &now, cli.json)
355 }
356 Command::Bass { level } => {
357 session.set_bass_level(level)?;
358 output::bass_level(out, &device, model, level, cli.json)
359 }
360 Command::Find { action, .. } => {
361 let ring = matches!(action, FindAction::Start);
362 session.find(ring)?;
363 output::find(out, &device, model, ring, cli.json)
364 }
365 Command::Game { state } => {
366 let now = session.set_switch("game", matches!(state, OnOff::On))?;
367 output::switch(out, &device, model, &now, cli.json)
368 }
369 Command::Dual => {
370 let devices = session.dual_devices()?;
371 output::dual_devices(out, &device, model, &devices, cli.json)
372 }
373 }
374}
375
376/// A preset name, checked before connecting: not empty, no spaces around it, no control
377/// characters. The buds' own limits are checked once their list is read.
378fn parse_name(text: &str) -> Result<String, String> {
379 if text.is_empty() || text.trim() != text {
380 return Err("a preset name cannot be empty, or start or end with a space".to_owned());
381 }
382 if text.chars().any(char::is_control) {
383 return Err("a preset name cannot hold control characters".to_owned());
384 }
385 Ok(text.to_owned())
386}
387
388/// `50=+3` → 50 Hz at +3 dB.
389fn parse_band(text: &str) -> Result<EqBand, String> {
390 let (hz, gain) = text
391 .split_once('=')
392 .ok_or_else(|| format!("{text} is not <hz>=<gain>, e.g. 50=+3"))?;
393 Ok(EqBand {
394 hz: hz.parse().map_err(|_| format!("{hz} is not a frequency in Hz"))?,
395 gain: gain.parse().map_err(|_| format!("{gain} is not a gain in whole dB"))?,
396 })
397}
398
399/// Exit codes from CLAUDE.md: 1 usage, 2 not found, 3 busy, 4 rejected or timed out.
400fn exit_code(error: &Error) -> u8 {
401 match error.kind() {
402 Kind::Usage => 1,
403 Kind::NotFound => 2,
404 Kind::Busy => 3,
405 Kind::Failed => 4,
406 }
407}
408
409#[cfg(test)]
410mod tests {
411 use super::*;
412
413 fn parse(args: &[&str]) -> Command {
414 Cli::try_parse_from(std::iter::once("budctl").chain(args.iter().copied()))
415 .unwrap()
416 .command
417 }
418
419 #[test]
420 fn dual_takes_nothing() {
421 assert!(matches!(parse(&["dual"]), Command::Dual));
422 assert!(Cli::try_parse_from(["budctl", "dual", "off"]).is_err());
423 }
424
425 #[test]
426 fn eq_takes_a_preset_bands_or_new() {
427 assert!(matches!(
428 parse(&["eq"]),
429 Command::Eq {
430 action: None,
431 preset: None,
432 ..
433 }
434 ));
435 assert!(matches!(
436 parse(&["eq", "custom-4", "50=+3", "16000=-2"]),
437 Command::Eq { action: None, preset: Some(p), bands } if p == "custom-4" && bands.len() == 2
438 ));
439 assert!(matches!(
440 parse(&["eq", "deep-bass"]),
441 Command::Eq { action: None, preset: Some(p), .. } if p == "deep-bass"
442 ));
443 assert!(matches!(
444 parse(&["eq", "new", "Gym mix"]),
445 Command::Eq { action: Some(EqCommand::New { name }), .. } if name == "Gym mix"
446 ));
447 assert!(matches!(
448 parse(&["eq", "delete", "custom-5"]),
449 Command::Eq { action: Some(EqCommand::Delete { preset }), .. } if preset == "custom-5"
450 ));
451 assert!(matches!(
452 parse(&["eq", "rename", "custom-5", "Gym"]),
453 Command::Eq { action: Some(EqCommand::Rename { preset, name }), .. }
454 if preset == "custom-5" && name == "Gym"
455 ));
456 }
457}