cli: add more options, refactor, switch to smol runtime
This commit is contained in:
1 parent
fabacf0a04
commit
7b49f116d4
6 files changed
+753
-316
No files matched your search
@@ -124,8 +124,8 @@ jobs:
|
||||
|
||||
- name: Package
|
||||
run: |
|
||||
bin=cli
|
||||
[[ "${{ matrix.target }}" == *windows* ]] && bin=cli.exe
|
||||
bin=guac-cli
|
||||
[[ "${{ matrix.target }}" == *windows* ]] && bin=guac-cli.exe
|
||||
mkdir -p dist
|
||||
zip -j "dist/guac-cli-${{ matrix.target }}.zip" "target/${{ matrix.target }}/release/$bin"
|
||||
shell: bash
|
||||
|
||||
@@ -3,7 +3,7 @@ repos:
|
||||
hooks:
|
||||
- id: cargo-check-host
|
||||
name: Cargo check (host)
|
||||
entry: cargo check -p cli -p shared
|
||||
entry: cargo check -p guac-cli -p shared
|
||||
pass_filenames: false
|
||||
types: [file, rust]
|
||||
language: system
|
||||
|
||||
Generated
+561
-277
File diff suppressed because it is too large.
Load diff
+7
-3
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "cli"
|
||||
version = "0.3.0"
|
||||
name = "guac-cli"
|
||||
version = "0.3.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
@@ -8,8 +8,12 @@ async-hid = "0.5.1"
|
||||
clap = { version = "4.6.1", features = ["derive"] }
|
||||
colog = "1.4.0"
|
||||
csv = "1.4.0"
|
||||
ctrlc = "3.5.2"
|
||||
deku = "0.20.3"
|
||||
futures-lite = "2.6.1"
|
||||
log = { version = "0.4.29", features = ["std"] }
|
||||
pollster = { version = "0.4.0", features = ["macro"] }
|
||||
serde_json = "1.0.154"
|
||||
shared = { path = "../shared", features = ["serde", "std"] }
|
||||
smol = "2.0.2"
|
||||
smol-macros = "0.1.1"
|
||||
smol-timeout = "0.6.1"
|
||||
+181
-32
@@ -1,6 +1,17 @@
|
||||
use std::io;
|
||||
use smol_macros::main;
|
||||
use std::{
|
||||
io,
|
||||
str::FromStr,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use async_hid::{AsyncHidRead, AsyncHidWrite, Device, HidBackend, HidResult};
|
||||
use async_hid::{
|
||||
AsyncHidRead, AsyncHidWrite, Device, DeviceReader, HidBackend, HidError, HidResult,
|
||||
};
|
||||
use clap::{Parser, Subcommand, ValueEnum};
|
||||
use deku::DekuContainerRead;
|
||||
use futures_lite::StreamExt;
|
||||
@@ -8,16 +19,53 @@ 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 {
|
||||
Monitor,
|
||||
/// 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,
|
||||
@@ -25,29 +73,35 @@ enum Command {
|
||||
}
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(version, about)]
|
||||
#[command(
|
||||
version,
|
||||
about = "Interact with GUAC UAC2 devices",
|
||||
arg_required_else_help = true
|
||||
)]
|
||||
struct Args {
|
||||
#[arg(short, long, default_value = "debug")]
|
||||
format: Format,
|
||||
#[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<W: io::Write> {
|
||||
fn from_writer(writer: W) -> Self
|
||||
where
|
||||
Self: Sized;
|
||||
trait StateEmitter {
|
||||
fn emit(&mut self, r: &AudioTelemetrySnapshot);
|
||||
fn close(&mut self) {}
|
||||
}
|
||||
|
||||
struct DebugEmitter<T: io::Write> {
|
||||
writer: T,
|
||||
}
|
||||
|
||||
impl<W: io::Write> StateEmitter<W> for DebugEmitter<W> {
|
||||
fn from_writer(writer: W) -> Self {
|
||||
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();
|
||||
}
|
||||
@@ -57,12 +111,15 @@ struct CsvEmitter<W: io::Write> {
|
||||
csv: csv::Writer<W>,
|
||||
}
|
||||
|
||||
impl<W: io::Write> StateEmitter<W> for CsvEmitter<W> {
|
||||
fn from_writer(writer: W) -> Self {
|
||||
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:?}");
|
||||
@@ -72,42 +129,133 @@ impl<W: io::Write> StateEmitter<W> for CsvEmitter<W> {
|
||||
}
|
||||
}
|
||||
|
||||
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(usage_id: u16) -> HidResult<Device> {
|
||||
async fn find_device(vidpid: &UsbVidPid, usage_id: u16) -> HidResult<Device> {
|
||||
Ok(HidBackend::default()
|
||||
.enumerate()
|
||||
.await?
|
||||
.find(|d| d.product_id == 0xcc1d && d.vendor_id == 0x1209 && d.usage_id == usage_id)
|
||||
.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?)"))
|
||||
}
|
||||
|
||||
#[pollster::main]
|
||||
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) => {
|
||||
let dev = find_device(USAGE_TELEMETRY).await?;
|
||||
let mut reader = dev.open_readable().await?;
|
||||
let mut writer: Box<dyn StateEmitter<_>> = match args.format {
|
||||
Format::Debug => Box::new(DebugEmitter::from_writer(io::stdout())),
|
||||
Format::Csv => Box::new(CsvEmitter::from_writer(io::stdout())),
|
||||
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 mut buf = [0u8; core::mem::size_of::<AudioTelemetryReport>()];
|
||||
while let Ok(r) = reader.read_input_report(&mut buf).await {
|
||||
log::debug!("read {}: {:?}", r, &buf[..r]);
|
||||
let buf = &buf[..r];
|
||||
match AudioTelemetryReport::from_bytes((buf, 0)) {
|
||||
Ok((_, r)) => writer.emit(&r.into()),
|
||||
Err(e) => eprintln!("Unable to parse report: {:?}", e),
|
||||
}
|
||||
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(USAGE_COMMAND).await?;
|
||||
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...");
|
||||
@@ -132,3 +280,4 @@ async fn main() -> HidResult<()> {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "guac"
|
||||
version = "0.3.0"
|
||||
version = "0.3.1"
|
||||
edition = "2024"
|
||||
|
||||
[features]
|
||||
|
||||
Reference in new issue
Block a user