Krolyxon
Commit 2476af5

Branches

Refs →

budctlcratesbudctl-clisrcmain.rs

418 lines · 13.4 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.
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}
134
135#[derive(Subcommand)]
136enum TouchCommand {
137 /// Set the noise-control modes a hold steps through (both buds), then read it back.
138 ///
139 /// At least two modes. The buds step through them in their own order.
140 Cycle {
141 #[arg(value_enum, required = true, num_args = 2..=3, value_name = "MODE")]
142 modes: Vec<CycleMode>,
143 },
144}
145
146#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)]
147enum CycleMode {
148 Off,
149 Transparency,
150 /// Noise cancelling.
151 Anc,
152}
153
154impl CycleMode {
155 fn name(self) -> &'static str {
156 match self {
157 CycleMode::Off => "off",
158 CycleMode::Transparency => "transparency",
159 CycleMode::Anc => "anc",
160 }
161 }
162}
163
164#[derive(Clone, Copy, ValueEnum)]
165enum Side {
166 Left,
167 Right,
168 /// The left and the right bud.
169 Both,
170}
171
172impl Side {
173 fn name(self) -> &'static str {
174 match self {
175 Side::Left => "left",
176 Side::Right => "right",
177 Side::Both => "both",
178 }
179 }
180}
181
182#[derive(Clone, Copy, ValueEnum)]
183enum OnOff {
184 On,
185 Off,
186}
187
188#[derive(Clone, Copy, ValueEnum)]
189enum AncArg {
190 Off,
191 Transparency,
192 /// Noise cancelling at the deep level (the buds use the same value for both).
193 On,
194 Light,
195 Medium,
196 Deep,
197}
198
199impl From<AncArg> for NoiseMode {
200 fn from(arg: AncArg) -> Self {
201 match arg {
202 AncArg::Off => NoiseMode::Off,
203 AncArg::On | AncArg::Deep => NoiseMode::Anc(AncLevel::Deep),
204 AncArg::Light => NoiseMode::Anc(AncLevel::Light),
205 AncArg::Medium => NoiseMode::Anc(AncLevel::Medium),
206 AncArg::Transparency => NoiseMode::Transparency,
207 }
208 }
209}
210
211fn main() -> ExitCode {
212 let cli = match Cli::try_parse() {
213 Ok(cli) => cli,
214 Err(error) => {
215 // Help and version are not errors; everything else is a usage error (exit 1).
216 let code = if error.use_stderr() { 1 } else { 0 };
217 // Nothing useful can be done if printing the usage message fails.
218 let _ = error.print();
219 return ExitCode::from(code);
220 }
221 };
222 if cli.debug {
223 budctl_core::debug::enable();
224 }
225
226 let mut stdout = io::stdout().lock();
227 let result = run(&cli, &mut stdout).and_then(|()| stdout.flush().map_err(output::Failure::Io));
228 match result {
229 Ok(()) => ExitCode::SUCCESS,
230 // `budctl status | head -1` is fine.
231 Err(output::Failure::Io(e)) if e.kind() == io::ErrorKind::BrokenPipe => ExitCode::SUCCESS,
232 Err(output::Failure::Io(e)) => {
233 eprintln!("budctl: cannot write output: {e}");
234 ExitCode::from(1)
235 }
236 Err(output::Failure::Budctl(e)) => {
237 eprintln!("budctl: {e}");
238 ExitCode::from(exit_code(&e))
239 }
240 }
241}
242
243fn run(cli: &Cli, out: &mut impl Write) -> Result<(), output::Failure> {
244 // Checked before connecting: ringing is loud. Spec: realme_t310.md#find
245 if let Command::Find {
246 action: FindAction::Start,
247 yes: false,
248 } = cli.command
249 {
250 return Err(Error::Usage(
251 "this rings the buds loudly; take them out of your ears, then run `budctl find start --yes`".to_owned(),
252 )
253 .into());
254 }
255 let found = budctl_core::scan()?;
256 if let Command::List = cli.command {
257 return output::list(out, &found, cli.json);
258 }
259
260 let (device, model) = budctl_core::select(found, cli.device)?;
261 let mut session = budctl_core::connect(&device, model)?;
262 match cli.command {
263 Command::List => Ok(()),
264 Command::Status => {
265 let status = session.status()?;
266 output::status(out, &device, model, &status, cli.json)
267 }
268 Command::Touch {
269 cycle: Some(TouchCommand::Cycle { ref modes }),
270 ..
271 } => {
272 let names: Vec<&str> = modes.iter().map(|m| m.name()).collect();
273 let now = session.set_hold_cycle(&names)?;
274 output::hold_cycle(out, &device, model, &now, cli.json)
275 }
276 Command::Touch {
277 side: Some(side),
278 gesture: Some(ref gesture),
279 action: Some(ref action),
280 dry_run,
281 ..
282 } => {
283 let change = session.set_touch(side.name(), gesture, action, dry_run)?;
284 output::touch_change(out, &device, model, &change, cli.json)
285 }
286 Command::Touch { .. } => {
287 let touch = session.touch_controls()?;
288 output::touch(out, &device, model, &touch, cli.json)
289 }
290 Command::Anc { mode } => {
291 let now = session.set_noise_control(mode.into())?;
292 output::noise_control(out, &device, model, &now, cli.json)
293 }
294 Command::Eq {
295 action: Some(EqCommand::New { ref name }),
296 ..
297 } => {
298 let created = session.create_custom_eq(name)?;
299 output::created_eq(out, &device, model, &created, cli.json)
300 }
301 Command::Eq {
302 action: Some(EqCommand::Rename { ref preset, ref name }),
303 ..
304 } => {
305 let now = session.rename_custom_eq(preset, name)?;
306 output::renamed_eq(out, &device, model, &now, cli.json)
307 }
308 Command::Eq { preset: None, .. } => {
309 let presets = session.eq_presets()?;
310 output::eq_presets(out, &device, model, &presets, cli.json)
311 }
312 Command::Eq {
313 preset: Some(ref preset),
314 ref bands,
315 ..
316 } if !bands.is_empty() => {
317 let now = session.set_custom_eq(preset, bands)?;
318 output::custom_eq(out, &device, model, &now, cli.json)
319 }
320 Command::Eq {
321 preset: Some(ref preset),
322 ..
323 } => {
324 let now = session.set_eq(preset)?;
325 output::eq(out, &device, model, &now, cli.json)
326 }
327 Command::Set { ref switch, state } => {
328 let now = session.set_switch(switch, matches!(state, OnOff::On))?;
329 output::switch(out, &device, model, &now, cli.json)
330 }
331 Command::Bass { level } => {
332 session.set_bass_level(level)?;
333 output::bass_level(out, &device, model, level, cli.json)
334 }
335 Command::Find { action, .. } => {
336 let ring = matches!(action, FindAction::Start);
337 session.find(ring)?;
338 output::find(out, &device, model, ring, cli.json)
339 }
340 Command::Game { state } => {
341 let now = session.set_switch("game", matches!(state, OnOff::On))?;
342 output::switch(out, &device, model, &now, cli.json)
343 }
344 }
345}
346
347/// A preset name, checked before connecting: not empty, no spaces around it, no control
348/// characters. The buds' own limits are checked once their list is read.
349fn parse_name(text: &str) -> Result<String, String> {
350 if text.is_empty() || text.trim() != text {
351 return Err("a preset name cannot be empty, or start or end with a space".to_owned());
352 }
353 if text.chars().any(char::is_control) {
354 return Err("a preset name cannot hold control characters".to_owned());
355 }
356 Ok(text.to_owned())
357}
358
359/// `50=+3` → 50 Hz at +3 dB.
360fn parse_band(text: &str) -> Result<EqBand, String> {
361 let (hz, gain) = text
362 .split_once('=')
363 .ok_or_else(|| format!("{text} is not <hz>=<gain>, e.g. 50=+3"))?;
364 Ok(EqBand {
365 hz: hz.parse().map_err(|_| format!("{hz} is not a frequency in Hz"))?,
366 gain: gain.parse().map_err(|_| format!("{gain} is not a gain in whole dB"))?,
367 })
368}
369
370/// Exit codes from CLAUDE.md: 1 usage, 2 not found, 3 busy, 4 rejected or timed out.
371fn exit_code(error: &Error) -> u8 {
372 match error.kind() {
373 Kind::Usage => 1,
374 Kind::NotFound => 2,
375 Kind::Busy => 3,
376 Kind::Failed => 4,
377 }
378}
379
380#[cfg(test)]
381mod tests {
382 use super::*;
383
384 fn parse(args: &[&str]) -> Command {
385 Cli::try_parse_from(std::iter::once("budctl").chain(args.iter().copied()))
386 .unwrap()
387 .command
388 }
389
390 #[test]
391 fn eq_takes_a_preset_bands_or_new() {
392 assert!(matches!(
393 parse(&["eq"]),
394 Command::Eq {
395 action: None,
396 preset: None,
397 ..
398 }
399 ));
400 assert!(matches!(
401 parse(&["eq", "custom-4", "50=+3", "16000=-2"]),
402 Command::Eq { action: None, preset: Some(p), bands } if p == "custom-4" && bands.len() == 2
403 ));
404 assert!(matches!(
405 parse(&["eq", "deep-bass"]),
406 Command::Eq { action: None, preset: Some(p), .. } if p == "deep-bass"
407 ));
408 assert!(matches!(
409 parse(&["eq", "new", "Gym mix"]),
410 Command::Eq { action: Some(EqCommand::New { name }), .. } if name == "Gym mix"
411 ));
412 assert!(matches!(
413 parse(&["eq", "rename", "custom-5", "Gym"]),
414 Command::Eq { action: Some(EqCommand::Rename { preset, name }), .. }
415 if preset == "custom-5" && name == "Gym"
416 ));
417 }
418}