284 lines
8.2 KiB
Rust
284 lines
8.2 KiB
Rust
use smol_macros::main;
|
|
use std::{
|
|
io,
|
|
str::FromStr,
|
|
sync::{
|
|
Arc,
|
|
atomic::{AtomicBool, Ordering},
|
|
},
|
|
time::Duration,
|
|
};
|
|
|
|
use async_hid::{
|
|
AsyncHidRead, AsyncHidWrite, Device, DeviceReader, HidBackend, HidError, HidResult,
|
|
};
|
|
use clap::{Parser, Subcommand, ValueEnum};
|
|
use deku::DekuContainerRead;
|
|
use futures_lite::StreamExt;
|
|
use shared::{
|
|
AudioDeviceCommand, AudioTelemetrySnapshot,
|
|
hid::{AudioDeviceCommandReport, AudioTelemetryReport, USAGE_COMMAND, USAGE_TELEMETRY},
|
|
};
|
|
use smol_timeout::TimeoutExt;
|
|
|
|
#[derive(Clone, Copy, Debug, ValueEnum)]
|
|
enum Format {
|
|
Debug,
|
|
Csv,
|
|
Json,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug)]
|
|
struct UsbVidPid {
|
|
vid: u16,
|
|
pid: u16,
|
|
}
|
|
|
|
impl FromStr for UsbVidPid {
|
|
type Err = clap::Error;
|
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
|
let invalid = || {
|
|
clap::Error::raw(
|
|
clap::error::ErrorKind::ValueValidation,
|
|
"Format of USB device ID is `12ab:cd34` (vendor:product, hex)",
|
|
)
|
|
};
|
|
let (vid, pid) = s.split_once(':').ok_or_else(invalid)?;
|
|
Ok(Self {
|
|
vid: u16::from_str_radix(vid, 16).map_err(|_| invalid())?,
|
|
pid: u16::from_str_radix(pid, 16).map_err(|_| invalid())?,
|
|
})
|
|
}
|
|
}
|
|
|
|
#[derive(Subcommand, Clone, Copy, Debug)]
|
|
enum Command {
|
|
/// Continuously print statistics from the connected device
|
|
Monitor {
|
|
#[arg(short, long, default_value = "debug")]
|
|
format: Format,
|
|
#[arg(short, long, default_value = None)]
|
|
count: Option<usize>,
|
|
},
|
|
/// Print the current state of the connected device
|
|
Status {
|
|
#[arg(short, long, default_value = "debug")]
|
|
format: Format,
|
|
},
|
|
/// Reset the connected device or boot to bootloader for firmware upgrade
|
|
Reset {
|
|
#[arg(short, long, default_value_t = false)]
|
|
bootloader: bool,
|
|
},
|
|
}
|
|
|
|
#[derive(Parser, Debug)]
|
|
#[command(
|
|
version,
|
|
about = "Interact with GUAC UAC2 devices",
|
|
arg_required_else_help = true
|
|
)]
|
|
struct Args {
|
|
#[arg(short, long, default_value = "1209:cc1d")]
|
|
/// USB device ID to operate on, format `1209:cc1d` (vendor:product, hex)
|
|
device: UsbVidPid,
|
|
#[command(subcommand)]
|
|
command: Option<Command>,
|
|
}
|
|
|
|
trait StateEmitter {
|
|
fn emit(&mut self, r: &AudioTelemetrySnapshot);
|
|
fn close(&mut self) {}
|
|
}
|
|
|
|
struct DebugEmitter<T: io::Write> {
|
|
writer: T,
|
|
}
|
|
|
|
impl<W: io::Write> DebugEmitter<W> {
|
|
fn new(writer: W) -> Self {
|
|
Self { writer }
|
|
}
|
|
}
|
|
|
|
impl<W: io::Write> StateEmitter for DebugEmitter<W> {
|
|
fn emit(&mut self, r: &AudioTelemetrySnapshot) {
|
|
writeln!(self.writer, "{r:?}").ok();
|
|
}
|
|
}
|
|
|
|
struct CsvEmitter<W: io::Write> {
|
|
csv: csv::Writer<W>,
|
|
}
|
|
|
|
impl<W: io::Write> CsvEmitter<W> {
|
|
fn new(writer: W) -> Self {
|
|
Self {
|
|
csv: csv::Writer::from_writer(writer),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<W: io::Write> StateEmitter for CsvEmitter<W> {
|
|
fn emit(&mut self, r: &AudioTelemetrySnapshot) {
|
|
if let Err(e) = self.csv.serialize(r) {
|
|
eprintln!("Serialization error: {e:?}");
|
|
} else {
|
|
self.csv.flush().ok();
|
|
}
|
|
}
|
|
}
|
|
|
|
struct JsonEmitter<W: io::Write> {
|
|
writer: W,
|
|
first: bool,
|
|
}
|
|
impl<W: io::Write> JsonEmitter<W> {
|
|
fn new(mut writer: W) -> Self {
|
|
if let Err(e) = write!(writer, "[") {
|
|
eprintln!("Write error: {e:?}")
|
|
}
|
|
Self {
|
|
writer,
|
|
first: true,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<W: io::Write> StateEmitter for JsonEmitter<W> {
|
|
fn emit(&mut self, r: &AudioTelemetrySnapshot) {
|
|
if !self.first
|
|
&& let Err(e) = write!(&mut self.writer, ",")
|
|
{
|
|
eprintln!("Write error: {e:?}")
|
|
} else {
|
|
self.first = false
|
|
}
|
|
if let Err(e) = serde_json::to_writer(&mut self.writer, r) {
|
|
eprintln!("Serialization error: {e:?}")
|
|
}
|
|
self.writer.flush().ok();
|
|
}
|
|
fn close(&mut self) {
|
|
if let Err(e) = write!(&mut self.writer, "]") {
|
|
eprintln!("Write error: {e:?}")
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<W: io::Write> Drop for JsonEmitter<W> {
|
|
fn drop(&mut self) {
|
|
self.close()
|
|
}
|
|
}
|
|
|
|
/// The device exposes one vendor HID interface per usage; pick the one we need.
|
|
async fn find_device(vidpid: &UsbVidPid, usage_id: u16) -> HidResult<Device> {
|
|
Ok(HidBackend::default()
|
|
.enumerate()
|
|
.await?
|
|
.find(|d| d.product_id == vidpid.pid && d.vendor_id == vidpid.vid && d.usage_id == usage_id)
|
|
.await
|
|
.expect("GUAC device not found or not accessible (try as root?)"))
|
|
}
|
|
|
|
async fn read_telemetry_report(
|
|
reader: &mut DeviceReader,
|
|
) -> Result<AudioTelemetryReport, HidError> {
|
|
let mut buf = [0u8; core::mem::size_of::<AudioTelemetryReport>()];
|
|
let r = reader
|
|
.read_input_report(&mut buf)
|
|
.timeout(Duration::from_secs(1))
|
|
.await
|
|
.ok_or(HidError::Other("Timeout".into()))??;
|
|
log::debug!("read {}: {:?}", r, &buf[..r]);
|
|
let buf = &buf[..r];
|
|
match AudioTelemetryReport::from_bytes((buf, 0)) {
|
|
Ok((_, r)) => Ok(r),
|
|
Err(e) => {
|
|
eprintln!("Unable to parse report: {:?}", e);
|
|
Err(HidError::Message("Unable to parse report".into()))
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn emit_telemetry_reports(
|
|
mut reader: DeviceReader,
|
|
mut writer: Box<dyn StateEmitter>,
|
|
count: &Option<usize>,
|
|
stop: &AtomicBool,
|
|
) {
|
|
let c = count.unwrap_or(1);
|
|
let mut i = 0;
|
|
while i < c && !stop.load(Ordering::Relaxed) {
|
|
let Ok(r) = read_telemetry_report(&mut reader).await else {
|
|
break;
|
|
};
|
|
writer.emit(&r.into());
|
|
i += count.map_or(0, |_| 1)
|
|
}
|
|
}
|
|
|
|
main! {
|
|
async fn main() -> HidResult<()> {
|
|
colog::init();
|
|
let args = Args::parse();
|
|
|
|
match &args.command {
|
|
Some(Command::Monitor { format, count }) => {
|
|
let dev = find_device(&args.device, USAGE_TELEMETRY).await?;
|
|
let reader = dev.open_readable().await?;
|
|
let writer: Box<dyn StateEmitter> = match format {
|
|
Format::Debug => Box::new(DebugEmitter::new(io::stdout())),
|
|
Format::Csv => Box::new(CsvEmitter::new(io::stdout())),
|
|
Format::Json => Box::new(JsonEmitter::new(io::stdout())),
|
|
};
|
|
|
|
let stop = Arc::new(AtomicBool::new(false));
|
|
let handler_stop = Arc::clone(&stop);
|
|
if let Err(e) = ctrlc::set_handler(move || handler_stop.store(true, Ordering::Relaxed))
|
|
{
|
|
eprintln!("Unable to install Ctrl-C handler: {e}");
|
|
}
|
|
|
|
emit_telemetry_reports(reader, writer, count, &stop).await
|
|
}
|
|
Some(Command::Status { format }) => {
|
|
let dev = find_device(&args.device, USAGE_TELEMETRY).await?;
|
|
let reader = dev.open_readable().await?;
|
|
let writer: Box<dyn StateEmitter> = match format {
|
|
Format::Debug => Box::new(DebugEmitter::new(io::stdout())),
|
|
Format::Csv => Box::new(CsvEmitter::new(io::stdout())),
|
|
Format::Json => Box::new(JsonEmitter::new(io::stdout())),
|
|
};
|
|
|
|
emit_telemetry_reports(reader, writer, &Some(1), &AtomicBool::new(false)).await
|
|
}
|
|
Some(Command::Reset { bootloader }) => {
|
|
let dev = find_device(&args.device, USAGE_COMMAND).await?;
|
|
let mut dev_writer = dev.open_writeable().await?;
|
|
let cmd = if *bootloader {
|
|
print!("Rebooting into bootloader...");
|
|
AudioDeviceCommand::Bootloader
|
|
} else {
|
|
print!("Rebooting...");
|
|
AudioDeviceCommand::Reset
|
|
};
|
|
log::debug!("writing command: {:?}", &cmd);
|
|
let report: AudioDeviceCommandReport = cmd.into();
|
|
log::debug!(" report: {:?}", &report);
|
|
// Our descriptor has no report IDs, so hidraw expects a leading 0x00 that it strips
|
|
let mut buf = [0u8; 1 + core::mem::size_of::<AudioDeviceCommandReport>()];
|
|
buf[1..].copy_from_slice(&report.cmd);
|
|
match dev_writer.write_output_report(&buf).await {
|
|
Ok(_) => println!("write succeeded - reboot failed"),
|
|
Err(_) => println!("lost device - reboot successful"),
|
|
}
|
|
}
|
|
None => {}
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
}
|