66 lines
2.2 KiB
Rust
66 lines
2.2 KiB
Rust
use std::{
|
|
error::Error,
|
|
io,
|
|
sync::mpsc::{self, RecvTimeoutError},
|
|
time::{Duration, Instant},
|
|
};
|
|
|
|
use fader_core::SurfaceId;
|
|
use midi::{LinuxIdentityCatalog, MidiInputCatalog};
|
|
|
|
fn main() -> Result<(), Box<dyn Error>> {
|
|
let mut arguments = std::env::args().skip(1);
|
|
let command = arguments.next().unwrap_or_else(|| "list".to_owned());
|
|
let catalog = MidiInputCatalog::new("fader_master monitor")?;
|
|
let ports = catalog.ports()?;
|
|
if command == "list" {
|
|
let identities = LinuxIdentityCatalog::new()?;
|
|
for (index, port) in ports.iter().enumerate() {
|
|
println!("index={index} identity={:?}", identities.inspect(port)?);
|
|
}
|
|
return Ok(());
|
|
}
|
|
if command != "watch" {
|
|
return Err(invalid_input(
|
|
"usage: midi_monitor [list|watch INDEX [SECONDS]]",
|
|
));
|
|
}
|
|
let index = arguments
|
|
.next()
|
|
.ok_or_else(|| invalid_input("missing port index"))?
|
|
.parse::<usize>()?;
|
|
let seconds = arguments.next().as_deref().unwrap_or("30").parse::<u64>()?;
|
|
let port = ports
|
|
.get(index)
|
|
.ok_or_else(|| invalid_input("port index is out of range"))?;
|
|
println!("watching id={:?} name={:?}", port.id(), port.name());
|
|
|
|
let (sender, receiver) = mpsc::sync_channel(128);
|
|
let connection = catalog.connect(
|
|
port,
|
|
"fader_master monitor input",
|
|
SurfaceId::new("monitor")?,
|
|
sender,
|
|
)?;
|
|
let deadline = Instant::now() + Duration::from_secs(seconds);
|
|
while let Some(remaining) = deadline.checked_duration_since(Instant::now()) {
|
|
match receiver.recv_timeout(remaining.min(Duration::from_millis(250))) {
|
|
Ok(event) => println!("{event:?}"),
|
|
Err(RecvTimeoutError::Timeout) => {}
|
|
Err(RecvTimeoutError::Disconnected) => {
|
|
return Err(invalid_input("MIDI input callback disconnected"));
|
|
}
|
|
}
|
|
}
|
|
if connection.overflowed() {
|
|
return Err(invalid_input(
|
|
"MIDI input queue overflowed; events require resync",
|
|
));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn invalid_input(message: &str) -> Box<dyn Error> {
|
|
Box::new(io::Error::new(io::ErrorKind::InvalidInput, message))
|
|
}
|