1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
|
//! mmx150d — connection monitoring for the beyerdynamic MMX 150 wireless
//! dongle.
use std::process::{Child, ExitCode, Stdio};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use clap::{Parser, Subcommand};
use mmx150::hid::{find_mmx150, Hidraw};
use mmx150::protocol::{self, LinkState, StateTracker, Transition};
const AFTER_HELP: &str = "\
status exit codes: 0 connected, 1 disconnected, 2 dongle missing/error
example:
mmx150d daemon \\
--on-connect 'wpctl set-default <mmx150-sink-id>' \\
--on-disconnect 'wpctl set-default <speakers-sink-id>'
find sink ids with: wpctl status";
#[derive(Parser, Debug)]
#[command(
name = "mmx150d",
version,
about = "Connection monitoring for the beyerdynamic MMX 150 wireless dongle",
after_help = AFTER_HELP
)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand, Debug)]
enum Command {
/// Print the current headset link state
Status,
/// Run hooks when the headset connects or disconnects
Daemon {
/// Run CMD (via sh -c) when the headset connects
#[arg(long)]
on_connect: Option<String>,
/// Run CMD (via sh -c) when the headset disconnects
#[arg(long)]
on_disconnect: Option<String>,
/// Poll interval in seconds
#[arg(long, default_value_t = 2, value_parser = clap::value_parser!(u64).range(1..))]
interval: u64,
/// Do not fire a hook for the state found at startup
#[arg(long)]
no_initial: bool,
},
}
fn main() -> ExitCode {
let cli = Cli::parse();
match cli.command {
Command::Status => cmd_status(),
Command::Daemon {
on_connect,
on_disconnect,
interval,
no_initial,
} => cmd_daemon(
on_connect.as_deref(),
on_disconnect.as_deref(),
interval,
no_initial,
),
}
}
fn cmd_status() -> ExitCode {
let Some(dev) = find_mmx150().unwrap_or(None) else {
eprintln!("dongle not found");
return ExitCode::from(2);
};
let mut hid = match Hidraw::open(&dev.devnode) {
Ok(h) => h,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
match protocol::link_status(&mut hid) {
Ok(LinkState::Connected) => {
println!("connected");
ExitCode::SUCCESS
}
Ok(LinkState::Disconnected) => {
println!("disconnected");
ExitCode::from(1)
}
Err(e) => {
eprintln!("error: {e}");
ExitCode::from(2)
}
}
}
fn cmd_daemon(
on_connect: Option<&str>,
on_disconnect: Option<&str>,
interval_secs: u64,
no_initial: bool,
) -> ExitCode {
let interval = Duration::from_secs(interval_secs);
let mut hid: Option<Hidraw> = None;
let mut tracker = StateTracker::new(!no_initial);
let mut children: Vec<Child> = Vec::new();
loop {
let cycle = Instant::now();
reap_children(&mut children);
let link_up = poll(&mut hid);
match tracker.update(link_up) {
Some(Transition::ToConnected { initial }) => {
log_state("connected", initial);
if let Some(cmd) = on_connect {
spawn_hook(cmd, &mut children);
}
}
Some(Transition::ToDisconnected { initial }) => {
log_state("disconnected", initial);
if let Some(cmd) = on_disconnect {
spawn_hook(cmd, &mut children);
}
}
None => {}
}
let elapsed = cycle.elapsed();
if let Some(remaining) = interval.checked_sub(elapsed) {
std::thread::sleep(remaining);
}
}
}
/// One poll cycle: (re)open the dongle if needed, then query the link.
/// Returns `true` if the headset answered.
fn poll(hid: &mut Option<Hidraw>) -> bool {
if hid.is_none() {
match find_mmx150() {
Ok(Some(dev)) => match Hidraw::open(&dev.devnode) {
Ok(h) => *hid = Some(h),
Err(_) => return false,
},
_ => return false,
}
}
let Some(h) = hid.as_mut() else {
return false;
};
match protocol::link_status(h) {
Ok(LinkState::Connected) => true,
Ok(LinkState::Disconnected) => false,
Err(_) => {
*hid = None;
false
}
}
}
fn spawn_hook(cmd: &str, children: &mut Vec<Child>) {
match std::process::Command::new("sh")
.arg("-c")
.arg(cmd)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
{
Ok(child) => children.push(child),
Err(e) => eprintln!("[{}] hook spawn failed: {e}", timestamp()),
}
}
/// Reap finished hook processes so they don't linger as zombies.
fn reap_children(children: &mut Vec<Child>) {
children.retain_mut(|c| c.try_wait().map_or(true, |s| s.is_none()));
}
fn log_state(state: &str, initial: bool) {
println!(
"[{}] headset {}{}",
timestamp(),
state,
if initial { " (initial)" } else { "" }
);
}
fn timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn daemon_args_defaults() {
let cli = Cli::try_parse_from(["mmx150d", "daemon"]).unwrap();
let Command::Daemon {
on_connect,
on_disconnect,
interval,
no_initial,
} = cli.command
else {
panic!("expected daemon subcommand");
};
assert_eq!(interval, 2);
assert!(!no_initial);
assert_eq!(on_connect, None);
assert_eq!(on_disconnect, None);
}
#[test]
fn daemon_args_full_parse() {
let cli = Cli::try_parse_from([
"mmx150d",
"daemon",
"--on-connect",
"echo up",
"--on-disconnect",
"echo down",
"--interval",
"5",
"--no-initial",
])
.unwrap();
let Command::Daemon {
on_connect,
on_disconnect,
interval,
no_initial,
} = cli.command
else {
panic!("expected daemon subcommand");
};
assert_eq!(on_connect.as_deref(), Some("echo up"));
assert_eq!(on_disconnect.as_deref(), Some("echo down"));
assert_eq!(interval, 5);
assert!(no_initial);
}
#[test]
fn daemon_args_rejects_bad_interval() {
assert!(Cli::try_parse_from(["mmx150d", "daemon", "--interval", "0"]).is_err());
assert!(Cli::try_parse_from(["mmx150d", "daemon", "--interval", "x"]).is_err());
assert!(Cli::try_parse_from(["mmx150d", "daemon", "--interval", "1"]).is_ok());
}
#[test]
fn daemon_args_rejects_unknown_option() {
assert!(Cli::try_parse_from(["mmx150d", "daemon", "--wat"]).is_err());
}
#[test]
fn status_subcommand_parses() {
assert!(matches!(
Cli::try_parse_from(["mmx150d", "status"]).unwrap().command,
Command::Status
));
}
}
|