Krolyxon
Commit 54dede1

Branches

Refs →

budctlcratesbudctl-clisrcmain.rs

291 lines · 8.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, 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) and read it back.
69 Eq { preset: Option<String> },
70 /// Turn an on/off setting on or off, then read it back. Switches: game, bass-boost, spatial (3D sound), wind, dual.
71 Set {
72 /// The switch's name, as `status --json` lists it.
73 switch: String,
74 #[arg(value_enum)]
75 state: OnOff,
76 },
77 /// Ring the buds so you can find them (loud: take them out of your ears first).
78 Find {
79 #[arg(value_enum)]
80 action: FindAction,
81 /// Confirm that the buds are out of your ears. Needed to start ringing.
82 #[arg(long)]
83 yes: bool,
84 },
85 /// Turn game mode (low latency) on or off, then read it back.
86 Game {
87 #[arg(value_enum)]
88 state: OnOff,
89 },
90}
91
92#[derive(Clone, Copy, ValueEnum)]
93enum FindAction {
94 Start,
95 Stop,
96}
97
98#[derive(Subcommand)]
99enum TouchCommand {
100 /// Set the noise-control modes a hold steps through (both buds), then read it back.
101 ///
102 /// At least two modes. The buds step through them in their own order.
103 Cycle {
104 #[arg(value_enum, required = true, num_args = 2..=3, value_name = "MODE")]
105 modes: Vec<CycleMode>,
106 },
107}
108
109#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)]
110enum CycleMode {
111 Off,
112 Transparency,
113 /// Noise cancelling.
114 Anc,
115}
116
117impl CycleMode {
118 fn name(self) -> &'static str {
119 match self {
120 CycleMode::Off => "off",
121 CycleMode::Transparency => "transparency",
122 CycleMode::Anc => "anc",
123 }
124 }
125}
126
127#[derive(Clone, Copy, ValueEnum)]
128enum Side {
129 Left,
130 Right,
131 /// The left and the right bud.
132 Both,
133}
134
135impl Side {
136 fn name(self) -> &'static str {
137 match self {
138 Side::Left => "left",
139 Side::Right => "right",
140 Side::Both => "both",
141 }
142 }
143}
144
145#[derive(Clone, Copy, ValueEnum)]
146enum OnOff {
147 On,
148 Off,
149}
150
151#[derive(Clone, Copy, ValueEnum)]
152enum AncArg {
153 Off,
154 Transparency,
155 /// Noise cancelling at the deep level (the buds use the same value for both).
156 On,
157 Light,
158 Medium,
159 Deep,
160}
161
162impl From<AncArg> for NoiseMode {
163 fn from(arg: AncArg) -> Self {
164 match arg {
165 AncArg::Off => NoiseMode::Off,
166 AncArg::On | AncArg::Deep => NoiseMode::Anc(AncLevel::Deep),
167 AncArg::Light => NoiseMode::Anc(AncLevel::Light),
168 AncArg::Medium => NoiseMode::Anc(AncLevel::Medium),
169 AncArg::Transparency => NoiseMode::Transparency,
170 }
171 }
172}
173
174fn main() -> ExitCode {
175 let cli = match Cli::try_parse() {
176 Ok(cli) => cli,
177 Err(error) => {
178 // Help and version are not errors; everything else is a usage error (exit 1).
179 let code = if error.use_stderr() { 1 } else { 0 };
180 // Nothing useful can be done if printing the usage message fails.
181 let _ = error.print();
182 return ExitCode::from(code);
183 }
184 };
185 if cli.debug {
186 budctl_core::debug::enable();
187 }
188
189 let mut stdout = io::stdout().lock();
190 let result = run(&cli, &mut stdout).and_then(|()| stdout.flush().map_err(output::Failure::Io));
191 match result {
192 Ok(()) => ExitCode::SUCCESS,
193 // `budctl status | head -1` is fine.
194 Err(output::Failure::Io(e)) if e.kind() == io::ErrorKind::BrokenPipe => ExitCode::SUCCESS,
195 Err(output::Failure::Io(e)) => {
196 eprintln!("budctl: cannot write output: {e}");
197 ExitCode::from(1)
198 }
199 Err(output::Failure::Budctl(e)) => {
200 eprintln!("budctl: {e}");
201 ExitCode::from(exit_code(&e))
202 }
203 }
204}
205
206fn run(cli: &Cli, out: &mut impl Write) -> Result<(), output::Failure> {
207 // Checked before connecting: ringing is loud. Spec: realme_t310.md#find
208 if let Command::Find {
209 action: FindAction::Start,
210 yes: false,
211 } = cli.command
212 {
213 return Err(Error::Usage(
214 "this rings the buds loudly; take them out of your ears, then run `budctl find start --yes`".to_owned(),
215 )
216 .into());
217 }
218 let found = budctl_core::scan()?;
219 if let Command::List = cli.command {
220 return output::list(out, &found, cli.json);
221 }
222
223 let (device, model) = budctl_core::select(found, cli.device)?;
224 let mut session = budctl_core::connect(&device, model)?;
225 match cli.command {
226 Command::List => Ok(()),
227 Command::Status => {
228 let status = session.status()?;
229 output::status(out, &device, model, &status, cli.json)
230 }
231 Command::Touch {
232 cycle: Some(TouchCommand::Cycle { ref modes }),
233 ..
234 } => {
235 let names: Vec<&str> = modes.iter().map(|m| m.name()).collect();
236 let now = session.set_hold_cycle(&names)?;
237 output::hold_cycle(out, &device, model, &now, cli.json)
238 }
239 Command::Touch {
240 side: Some(side),
241 gesture: Some(ref gesture),
242 action: Some(ref action),
243 dry_run,
244 ..
245 } => {
246 let change = session.set_touch(side.name(), gesture, action, dry_run)?;
247 output::touch_change(out, &device, model, &change, cli.json)
248 }
249 Command::Touch { .. } => {
250 let touch = session.touch_controls()?;
251 output::touch(out, &device, model, &touch, cli.json)
252 }
253 Command::Anc { mode } => {
254 let now = session.set_noise_control(mode.into())?;
255 output::noise_control(out, &device, model, &now, cli.json)
256 }
257 Command::Eq { preset: None } => {
258 let presets = session.eq_presets()?;
259 output::eq_presets(out, &device, model, &presets, cli.json)
260 }
261 Command::Eq {
262 preset: Some(ref preset),
263 } => {
264 let now = session.set_eq(preset)?;
265 output::eq(out, &device, model, &now, cli.json)
266 }
267 Command::Set { ref switch, state } => {
268 let now = session.set_switch(switch, matches!(state, OnOff::On))?;
269 output::switch(out, &device, model, &now, cli.json)
270 }
271 Command::Find { action, .. } => {
272 let ring = matches!(action, FindAction::Start);
273 session.find(ring)?;
274 output::find(out, &device, model, ring, cli.json)
275 }
276 Command::Game { state } => {
277 let now = session.set_switch("game", matches!(state, OnOff::On))?;
278 output::switch(out, &device, model, &now, cli.json)
279 }
280 }
281}
282
283/// Exit codes from CLAUDE.md: 1 usage, 2 not found, 3 busy, 4 rejected or timed out.
284fn exit_code(error: &Error) -> u8 {
285 match error.kind() {
286 Kind::Usage => 1,
287 Kind::NotFound => 2,
288 Kind::Busy => 3,
289 Kind::Failed => 4,
290 }
291}