Krolyxon
Commit 4276e2b

Branches

Refs →

budctlcratesbudctl-clisrcmain.rs

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