config: add persistent flash-backed configuration with a HID command interface and CLI management
Build and Release Firmware / firmware (ak4490) (push) Successful in 50s
Build and Release Firmware / firmware (cs4398) (push) Successful in 44s
Build and Release Firmware / firmware (evk) (push) Successful in 43s
Build and Release Firmware / cli (aarch64-unknown-linux-musl) (push) Successful in 1m8s
Build and Release Firmware / cli (x86_64-pc-windows-gnu) (push) Successful in 1m32s
Build and Release Firmware / cli (x86_64-unknown-linux-musl) (push) Successful in 1m6s
Build and Release Firmware / release (push) Successful in 7s
Build and Release Firmware / firmware (ak4490) (push) Successful in 50s
Build and Release Firmware / firmware (cs4398) (push) Successful in 44s
Build and Release Firmware / firmware (evk) (push) Successful in 43s
Build and Release Firmware / cli (aarch64-unknown-linux-musl) (push) Successful in 1m8s
Build and Release Firmware / cli (x86_64-pc-windows-gnu) (push) Successful in 1m32s
Build and Release Firmware / cli (x86_64-unknown-linux-musl) (push) Successful in 1m6s
Build and Release Firmware / release (push) Successful in 7s
This commit is contained in:
23 files changed
+3483
-148
No files matched your search
+603
-26
@@ -6,18 +6,27 @@ use std::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use async_hid::{
|
||||
AsyncHidRead, AsyncHidWrite, Device, DeviceReader, HidBackend, HidError, HidResult,
|
||||
AsyncHidFeatureHandle, AsyncHidRead, Device, DeviceFeatureHandle, 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},
|
||||
AudioTelemetrySnapshot,
|
||||
config::{ConfigBytes, ConfigSnapshot, ConfigTag, DeviceConfig, Tlv, TlvList, tags},
|
||||
hardware::HardwareInfo,
|
||||
hid::{
|
||||
AudioTelemetryReport, USAGE_COMMAND, USAGE_TELEMETRY,
|
||||
command::{
|
||||
COMMAND_PAYLOAD_LEN, COMMAND_REPORT_SIZE, CommandKind, HEADER_LEN, Header,
|
||||
IN_PAYLOAD_LEN, IN_REPORT_SIZE, NackCode, ResponseKind,
|
||||
},
|
||||
},
|
||||
};
|
||||
use smol_timeout::TimeoutExt;
|
||||
|
||||
@@ -51,7 +60,38 @@ impl FromStr for UsbVidPid {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Clone, Copy, Debug)]
|
||||
#[derive(clap::Args, Clone, Debug)]
|
||||
struct ConfigArgs {
|
||||
/// Restore the built-in default configuration
|
||||
#[arg(
|
||||
long,
|
||||
conflicts_with_all = ["vendor_id", "product_id", "manufacturer", "product", "serial"]
|
||||
)]
|
||||
reset: bool,
|
||||
|
||||
/// USB vendor ID, in hex
|
||||
#[arg(long, value_parser = parse_hex_u16)]
|
||||
vendor_id: Option<u16>,
|
||||
/// USB product ID, in hex
|
||||
#[arg(long, value_parser = parse_hex_u16)]
|
||||
product_id: Option<u16>,
|
||||
/// USB manufacturer string
|
||||
#[arg(long)]
|
||||
manufacturer: Option<String>,
|
||||
/// USB product string
|
||||
#[arg(long)]
|
||||
product: Option<String>,
|
||||
/// USB serial string
|
||||
#[arg(long)]
|
||||
serial: Option<String>,
|
||||
}
|
||||
|
||||
fn parse_hex_u16(value: &str) -> Result<u16, String> {
|
||||
u16::from_str_radix(value.trim_start_matches("0x"), 16)
|
||||
.map_err(|_| "expected a 16-bit hex value".to_string())
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Clone, Debug)]
|
||||
enum Command {
|
||||
/// Continuously print statistics from the connected device
|
||||
Monitor {
|
||||
@@ -70,6 +110,12 @@ enum Command {
|
||||
#[arg(short, long, default_value_t = false)]
|
||||
bootloader: bool,
|
||||
},
|
||||
/// Update configuration values
|
||||
Config(ConfigArgs),
|
||||
/// Show the device configuration
|
||||
Show,
|
||||
/// Show device hardware information
|
||||
Hardware,
|
||||
}
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
@@ -172,14 +218,56 @@ impl<W: io::Write> Drop for JsonEmitter<W> {
|
||||
}
|
||||
}
|
||||
|
||||
fn usage_name(usage: u16) -> &'static str {
|
||||
match usage {
|
||||
USAGE_TELEMETRY => "telemetry",
|
||||
USAGE_COMMAND => "command",
|
||||
_ => "unknown",
|
||||
}
|
||||
}
|
||||
|
||||
/// 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()
|
||||
async fn try_find_device(vidpid: &UsbVidPid, usage_id: u16) -> HidResult<Option<Device>> {
|
||||
log::debug!(
|
||||
"searching for {:04x}:{:04x} {} interface",
|
||||
vidpid.vid,
|
||||
vidpid.pid,
|
||||
usage_name(usage_id)
|
||||
);
|
||||
|
||||
let device = 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?)"))
|
||||
.await;
|
||||
|
||||
if let Some(device) = &device {
|
||||
log::info!(
|
||||
"found {} interface: {:04x}:{:04x} {}",
|
||||
usage_name(usage_id),
|
||||
device.vendor_id,
|
||||
device.product_id,
|
||||
device.name
|
||||
);
|
||||
}
|
||||
|
||||
Ok(device)
|
||||
}
|
||||
|
||||
async fn find_device(vidpid: &UsbVidPid, usage_id: u16) -> HidResult<Device> {
|
||||
try_find_device(vidpid, usage_id).await?.ok_or_else(|| {
|
||||
log::error!(
|
||||
"{:04x}:{:04x} {} interface not found",
|
||||
vidpid.vid,
|
||||
vidpid.pid,
|
||||
usage_name(usage_id)
|
||||
);
|
||||
HidError::Message(
|
||||
"GUAC device not found or not accessible (try as root?)"
|
||||
.to_string()
|
||||
.into(),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
async fn read_telemetry_report(
|
||||
@@ -196,7 +284,7 @@ async fn read_telemetry_report(
|
||||
match AudioTelemetryReport::from_bytes((buf, 0)) {
|
||||
Ok((_, r)) => Ok(r),
|
||||
Err(e) => {
|
||||
eprintln!("Unable to parse report: {:?}", e);
|
||||
log::error!("unable to parse telemetry report: {:?}", e);
|
||||
Err(HidError::Message("Unable to parse report".into()))
|
||||
}
|
||||
}
|
||||
@@ -212,11 +300,484 @@ async fn emit_telemetry_reports(
|
||||
let mut i = 0;
|
||||
while i < c && !stop.load(Ordering::Relaxed) {
|
||||
let Ok(r) = read_telemetry_report(&mut reader).await else {
|
||||
log::warn!("telemetry stream ended");
|
||||
break;
|
||||
};
|
||||
writer.emit(&r.into());
|
||||
i += count.map_or(0, |_| 1)
|
||||
}
|
||||
|
||||
log::info!("telemetry complete");
|
||||
}
|
||||
|
||||
async fn send_command(
|
||||
handle: &mut DeviceFeatureHandle,
|
||||
seq: u8,
|
||||
kind: CommandKind,
|
||||
payload: &[u8],
|
||||
) -> HidResult<()> {
|
||||
let total_len = payload.len();
|
||||
let mut offset = 0;
|
||||
|
||||
log::info!(
|
||||
"sending {:?} seq={} ({} payload bytes)",
|
||||
kind,
|
||||
seq,
|
||||
total_len
|
||||
);
|
||||
|
||||
loop {
|
||||
let len = (total_len - offset).min(COMMAND_PAYLOAD_LEN);
|
||||
// hidraw strips the leading report ID byte, which is 0 for an unnumbered report.
|
||||
let mut report = [0u8; 1 + COMMAND_REPORT_SIZE];
|
||||
|
||||
Header {
|
||||
kind: kind as u8,
|
||||
seq,
|
||||
total_len: total_len as u16,
|
||||
offset: offset as u16,
|
||||
len: len as u8,
|
||||
}
|
||||
.encode(&mut report[1..1 + HEADER_LEN]);
|
||||
|
||||
report[1 + HEADER_LEN..1 + HEADER_LEN + len]
|
||||
.copy_from_slice(&payload[offset..offset + len]);
|
||||
|
||||
log::debug!(
|
||||
"tx seq={} offset={}/{} len={}: {:02x?}",
|
||||
seq,
|
||||
offset,
|
||||
total_len,
|
||||
len,
|
||||
&report[1..]
|
||||
);
|
||||
|
||||
handle.write_feature_report(&report).await?;
|
||||
offset += len;
|
||||
|
||||
if offset >= total_len {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn read_header_report(
|
||||
reader: &mut DeviceReader,
|
||||
) -> HidResult<([u8; IN_REPORT_SIZE], Header)> {
|
||||
let mut report = [0u8; IN_REPORT_SIZE];
|
||||
let len = reader
|
||||
.read_input_report(&mut report)
|
||||
.timeout(Duration::from_secs(2))
|
||||
.await
|
||||
.ok_or_else(|| HidError::message("timed out waiting for device response"))??;
|
||||
|
||||
let header =
|
||||
Header::parse(&report[..len]).ok_or_else(|| HidError::message("invalid HID response"))?;
|
||||
|
||||
log::debug!("rx {:?}: {:02x?}", header, &report[..len]);
|
||||
|
||||
if HEADER_LEN + usize::from(header.len) > len {
|
||||
log::error!(
|
||||
"invalid response length: header {} in {} bytes",
|
||||
header.len,
|
||||
len
|
||||
);
|
||||
return Err(HidError::message("invalid HID response length"));
|
||||
}
|
||||
|
||||
Ok((report, header))
|
||||
}
|
||||
|
||||
fn nack_error(code: Option<NackCode>) -> HidError {
|
||||
HidError::message(match code {
|
||||
Some(code) => format!("device rejected command: {code:?}"),
|
||||
None => "device rejected command".to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn wait_ack(reader: &mut DeviceReader, seq: u8) -> HidResult<()> {
|
||||
log::debug!("waiting for ACK seq={}", seq);
|
||||
|
||||
loop {
|
||||
let (report, header) = read_header_report(reader).await?;
|
||||
|
||||
if header.seq != seq {
|
||||
log::debug!("ignoring stale response for seq={}", header.seq);
|
||||
continue;
|
||||
}
|
||||
|
||||
match ResponseKind::try_from(header.kind) {
|
||||
Ok(ResponseKind::Ack) => {
|
||||
log::info!("acknowledged seq={}", seq);
|
||||
return Ok(());
|
||||
}
|
||||
Ok(ResponseKind::Nack) => {
|
||||
let code = report
|
||||
.get(HEADER_LEN)
|
||||
.copied()
|
||||
.and_then(|byte| NackCode::try_from(byte).ok());
|
||||
log::error!("nack seq={} code={:?}", seq, code);
|
||||
return Err(nack_error(code));
|
||||
}
|
||||
Ok(ResponseKind::Noop) => continue,
|
||||
Ok(ResponseKind::ConfigData) | Ok(ResponseKind::Hardware) => {
|
||||
log::error!("expected ACK seq={} but got data", seq);
|
||||
return Err(HidError::message("unexpected data"));
|
||||
}
|
||||
Err(_) => {
|
||||
log::error!("invalid response kind {}", header.kind);
|
||||
return Err(HidError::message("invalid response kind"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_message(
|
||||
reader: &mut DeviceReader,
|
||||
seq: u8,
|
||||
expected: ResponseKind,
|
||||
) -> HidResult<Vec<u8>> {
|
||||
let mut data = Vec::new();
|
||||
let mut total_len = None;
|
||||
|
||||
loop {
|
||||
let (report, header) = read_header_report(reader).await?;
|
||||
|
||||
if header.seq != seq {
|
||||
continue;
|
||||
}
|
||||
|
||||
match ResponseKind::try_from(header.kind) {
|
||||
Ok(kind) if kind == expected => {
|
||||
let offset = usize::from(header.offset);
|
||||
let len = usize::from(header.len);
|
||||
let total = usize::from(header.total_len);
|
||||
|
||||
if len > IN_PAYLOAD_LEN || offset != data.len() || data.len() + len > total {
|
||||
log::error!(
|
||||
"invalid chunk: offset={} len={} total={} received={}",
|
||||
offset,
|
||||
len,
|
||||
total,
|
||||
data.len()
|
||||
);
|
||||
return Err(HidError::message("invalid response chunk"));
|
||||
}
|
||||
|
||||
if let Some(existing) = total_len
|
||||
&& existing != total
|
||||
{
|
||||
log::error!("inconsistent response length: {} != {}", existing, total);
|
||||
return Err(HidError::message("inconsistent response length"));
|
||||
}
|
||||
total_len = Some(total);
|
||||
|
||||
log::debug!(
|
||||
"rx chunk seq={} offset={}/{} len={}",
|
||||
seq,
|
||||
offset,
|
||||
total,
|
||||
len
|
||||
);
|
||||
|
||||
data.extend_from_slice(&report[HEADER_LEN..HEADER_LEN + len]);
|
||||
|
||||
if data.len() == total {
|
||||
log::info!("received {} bytes seq={}", data.len(), seq);
|
||||
return Ok(data);
|
||||
}
|
||||
}
|
||||
Ok(ResponseKind::Nack) => {
|
||||
let code = report
|
||||
.get(HEADER_LEN)
|
||||
.copied()
|
||||
.and_then(|byte| NackCode::try_from(byte).ok());
|
||||
log::error!("nack seq={} code={:?}", seq, code);
|
||||
return Err(nack_error(code));
|
||||
}
|
||||
Ok(ResponseKind::Ack) | Ok(ResponseKind::Noop) => continue,
|
||||
Ok(kind) => {
|
||||
log::error!("unexpected response {:?}, wanted {:?}", kind, expected);
|
||||
return Err(HidError::message("unexpected response"));
|
||||
}
|
||||
Err(_) => {
|
||||
log::error!("invalid response kind {}", header.kind);
|
||||
return Err(HidError::message("invalid response kind"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_config(
|
||||
reader: &mut DeviceReader,
|
||||
handle: &mut DeviceFeatureHandle,
|
||||
seq: u8,
|
||||
) -> HidResult<ConfigSnapshot> {
|
||||
send_command(handle, seq, CommandKind::ReadConfig, &[]).await?;
|
||||
let data = read_message(reader, seq, ResponseKind::ConfigData).await?;
|
||||
|
||||
let snapshot = ConfigSnapshot::parse(&data)
|
||||
.map_err(|error| HidError::message(format!("invalid config: {error}")))?;
|
||||
|
||||
log::info!(
|
||||
"config from slot {} ({} tags)",
|
||||
snapshot.active_slot,
|
||||
snapshot.config.tlvs.len()
|
||||
);
|
||||
log::debug!("config tlvs: {:?}", snapshot.config.tlvs);
|
||||
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
async fn replace_tlv(
|
||||
reader: &mut DeviceReader,
|
||||
handle: &mut DeviceFeatureHandle,
|
||||
seq: u8,
|
||||
tag: ConfigTag,
|
||||
value: &[u8],
|
||||
) -> HidResult<()> {
|
||||
let mut payload = Vec::with_capacity(2 + value.len());
|
||||
payload.extend_from_slice(&tag.0.to_le_bytes());
|
||||
payload.extend_from_slice(value);
|
||||
|
||||
log::info!("setting {:?} ({} bytes)", tag, value.len());
|
||||
log::debug!("value for {:?}: {:02x?}", tag, value);
|
||||
|
||||
send_command(handle, seq, CommandKind::ReplaceTlv, &payload).await?;
|
||||
wait_ack(reader, seq).await
|
||||
}
|
||||
|
||||
async fn read_hardware(
|
||||
reader: &mut DeviceReader,
|
||||
handle: &mut DeviceFeatureHandle,
|
||||
) -> HidResult<HardwareInfo> {
|
||||
send_command(handle, 0, CommandKind::Hardware, &[])
|
||||
.await
|
||||
.map_err(|error| HidError::message(format!("hardware command write failed: {error}")))?;
|
||||
let data = read_message(reader, 0, ResponseKind::Hardware)
|
||||
.await
|
||||
.map_err(|error| HidError::message(format!("hardware data failed: {error}")))?;
|
||||
|
||||
let info = HardwareInfo::parse(&data)
|
||||
.map_err(|error| HidError::message(format!("invalid hardware info: {error}")))?;
|
||||
|
||||
log::debug!(
|
||||
"hardware: uuid={:02x?} dac={:?} firmware={:?}",
|
||||
&info.uuid[..],
|
||||
info.dac.as_str(),
|
||||
info.version.as_str()
|
||||
);
|
||||
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
/// Commands are written as feature reports over the control pipe; replies arrive on the interrupt
|
||||
/// IN endpoint.
|
||||
async fn open_command(dev: &Device) -> HidResult<(DeviceReader, DeviceFeatureHandle)> {
|
||||
log::debug!("opening command interface");
|
||||
|
||||
Ok((dev.open_readable().await?, dev.open_feature_handle().await?))
|
||||
}
|
||||
|
||||
fn tlv_u16(tlvs: &TlvList, tag: ConfigTag) -> Option<u16> {
|
||||
let value = tlvs.find(tag)?.value.as_slice();
|
||||
(value.len() == 2).then(|| u16::from_le_bytes([value[0], value[1]]))
|
||||
}
|
||||
|
||||
fn print_hex(name: &str, tag: ConfigTag, value: &[u8]) {
|
||||
print!("{name} (0x{:04x}):", tag.0);
|
||||
|
||||
for byte in value {
|
||||
print!(" {byte:02x}");
|
||||
}
|
||||
|
||||
println!();
|
||||
}
|
||||
|
||||
fn print_config(snapshot: &ConfigSnapshot) {
|
||||
println!("Active slot: {}", snapshot.active_slot);
|
||||
|
||||
for tlv in snapshot.config.tlvs.iter() {
|
||||
let name = tlv.tag.name().unwrap_or("Unknown");
|
||||
let value = tlv.value.as_slice();
|
||||
|
||||
if tlv.tag == tags::VENDOR_ID || tlv.tag == tags::PRODUCT_ID {
|
||||
match value {
|
||||
[lo, hi] => println!(
|
||||
"{name} (0x{:04x}): 0x{:04x}",
|
||||
tlv.tag.0,
|
||||
u16::from_le_bytes([*lo, *hi])
|
||||
),
|
||||
_ => print_hex(name, tlv.tag, value),
|
||||
}
|
||||
} else if tlv.tag == tags::MANUF_STRING
|
||||
|| tlv.tag == tags::PRODUCT_STRING
|
||||
|| tlv.tag == tags::SERIAL_STRING
|
||||
{
|
||||
match core::str::from_utf8(value) {
|
||||
Ok(value) => println!("{name} (0x{:04x}): {value:?}", tlv.tag.0),
|
||||
Err(_) => print_hex(name, tlv.tag, value),
|
||||
}
|
||||
} else {
|
||||
print_hex(name, tlv.tag, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn show_config(device: &UsbVidPid) -> HidResult<()> {
|
||||
let dev = find_device(device, USAGE_COMMAND).await?;
|
||||
let (mut reader, mut handle) = open_command(&dev).await?;
|
||||
let snapshot = read_config(&mut reader, &mut handle, 0).await?;
|
||||
|
||||
log::info!("printing configuration");
|
||||
print_config(&snapshot);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn show_hardware(device: &UsbVidPid) -> HidResult<()> {
|
||||
let dev = find_device(device, USAGE_COMMAND).await?;
|
||||
let (mut reader, mut handle) = open_command(&dev).await?;
|
||||
let info = read_hardware(&mut reader, &mut handle).await?;
|
||||
|
||||
log::info!("printing hardware info");
|
||||
print!("UUID: ");
|
||||
for byte in info.uuid {
|
||||
print!("{byte:02X}");
|
||||
}
|
||||
println!();
|
||||
println!("DAC: {}", info.dac.as_str());
|
||||
println!("Firmware: {}", info.version.as_str());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn apply_config(device: &UsbVidPid, args: &ConfigArgs) -> HidResult<()> {
|
||||
if args.reset {
|
||||
return reset_config(device).await;
|
||||
}
|
||||
|
||||
let dev = find_device(device, USAGE_COMMAND).await?;
|
||||
let (mut reader, mut handle) = open_command(&dev).await?;
|
||||
|
||||
let current = read_config(&mut reader, &mut handle, 0).await?;
|
||||
let mut expected = current.config.tlvs.clone();
|
||||
let mut replacements: Vec<(ConfigTag, Vec<u8>)> = Vec::new();
|
||||
|
||||
if let Some(value) = args.vendor_id {
|
||||
replacements.push((tags::VENDOR_ID, value.to_le_bytes().to_vec()));
|
||||
}
|
||||
if let Some(value) = args.product_id {
|
||||
replacements.push((tags::PRODUCT_ID, value.to_le_bytes().to_vec()));
|
||||
}
|
||||
if let Some(value) = &args.manufacturer {
|
||||
replacements.push((tags::MANUF_STRING, value.as_bytes().to_vec()));
|
||||
}
|
||||
if let Some(value) = &args.product {
|
||||
replacements.push((tags::PRODUCT_STRING, value.as_bytes().to_vec()));
|
||||
}
|
||||
if let Some(value) = &args.serial {
|
||||
replacements.push((tags::SERIAL_STRING, value.as_bytes().to_vec()));
|
||||
}
|
||||
|
||||
for (tag, value) in &replacements {
|
||||
let value = ConfigBytes::from_slice(value)
|
||||
.map_err(|error| HidError::message(format!("invalid value for {tag:?}: {error}")))?;
|
||||
expected
|
||||
.upsert(Tlv { tag: *tag, value })
|
||||
.map_err(|error| HidError::message(format!("config too large: {error}")))?;
|
||||
}
|
||||
|
||||
DeviceConfig::from_tlvs(&expected)
|
||||
.map_err(|error| HidError::message(format!("invalid configuration: {error}")))?;
|
||||
|
||||
log::info!("applying {} change(s)", replacements.len());
|
||||
|
||||
let mut seq = 1u8;
|
||||
for (tag, value) in &replacements {
|
||||
replace_tlv(&mut reader, &mut handle, seq, *tag, value).await?;
|
||||
seq = seq.wrapping_add(1);
|
||||
}
|
||||
|
||||
log::info!("committing configuration to flash");
|
||||
send_command(&mut handle, seq, CommandKind::CommitConfig, &[]).await?;
|
||||
wait_ack(&mut reader, seq).await?;
|
||||
|
||||
drop(reader);
|
||||
drop(handle);
|
||||
drop(dev);
|
||||
|
||||
let expected_device = device_for(&expected)?;
|
||||
let slot = await_config(expected_device, &expected).await?;
|
||||
|
||||
println!("Configuration updated successfully (active slot {slot}).");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn reset_config(device: &UsbVidPid) -> HidResult<()> {
|
||||
let dev = find_device(device, USAGE_COMMAND).await?;
|
||||
let (mut reader, mut handle) = open_command(&dev).await?;
|
||||
|
||||
let info = read_hardware(&mut reader, &mut handle).await?;
|
||||
let defaults = DeviceConfig::with_defaults(DeviceConfig::serial_from_uuid(&info.uuid))
|
||||
.map_err(|error| HidError::message(format!("invalid default configuration: {error}")))?;
|
||||
let expected = defaults
|
||||
.to_tlvs()
|
||||
.map_err(|error| HidError::message(format!("invalid default configuration: {error}")))?;
|
||||
|
||||
log::info!("restoring default configuration");
|
||||
send_command(&mut handle, 0, CommandKind::ResetConfig, &[]).await?;
|
||||
wait_ack(&mut reader, 0).await?;
|
||||
|
||||
drop(reader);
|
||||
drop(handle);
|
||||
drop(dev);
|
||||
|
||||
let expected_device = device_for(&expected)?;
|
||||
let slot = await_config(expected_device, &expected).await?;
|
||||
|
||||
println!("Configuration reset to defaults (active slot {slot}).");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn device_for(tlvs: &TlvList) -> HidResult<UsbVidPid> {
|
||||
Ok(UsbVidPid {
|
||||
vid: tlv_u16(tlvs, tags::VENDOR_ID)
|
||||
.ok_or_else(|| HidError::message("missing vendor id"))?,
|
||||
pid: tlv_u16(tlvs, tags::PRODUCT_ID)
|
||||
.ok_or_else(|| HidError::message("missing product id"))?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Waits for the device to come back with `expected_device` and report exactly `expected`.
|
||||
async fn await_config(expected_device: UsbVidPid, expected: &TlvList) -> HidResult<u8> {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
|
||||
log::info!(
|
||||
"waiting for device to restart as {:04x}:{:04x}",
|
||||
expected_device.vid,
|
||||
expected_device.pid
|
||||
);
|
||||
|
||||
loop {
|
||||
if let Some(dev) = try_find_device(&expected_device, USAGE_COMMAND).await?
|
||||
&& let Ok((mut reader, mut handle)) = open_command(&dev).await
|
||||
&& let Ok(snapshot) = read_config(&mut reader, &mut handle, 0).await
|
||||
&& snapshot.config.tlvs == *expected
|
||||
{
|
||||
log::info!("configuration verified in slot {}", snapshot.active_slot);
|
||||
return Ok(snapshot.active_slot);
|
||||
}
|
||||
|
||||
if Instant::now() >= deadline {
|
||||
log::error!("configuration verification timed out");
|
||||
return Err(HidError::message("configuration verification failed"));
|
||||
}
|
||||
|
||||
log::debug!("device not ready yet, retrying");
|
||||
smol::Timer::after(Duration::from_millis(200)).await;
|
||||
}
|
||||
}
|
||||
|
||||
main! {
|
||||
@@ -226,6 +787,7 @@ async fn main() -> HidResult<()> {
|
||||
|
||||
match &args.command {
|
||||
Some(Command::Monitor { format, count }) => {
|
||||
log::info!("monitoring telemetry");
|
||||
let dev = find_device(&args.device, USAGE_TELEMETRY).await?;
|
||||
let reader = dev.open_readable().await?;
|
||||
let writer: Box<dyn StateEmitter> = match format {
|
||||
@@ -238,12 +800,13 @@ async fn main() -> HidResult<()> {
|
||||
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}");
|
||||
log::warn!("unable to install Ctrl-C handler: {e}");
|
||||
}
|
||||
|
||||
emit_telemetry_reports(reader, writer, count, &stop).await
|
||||
}
|
||||
Some(Command::Status { format }) => {
|
||||
log::info!("reading telemetry");
|
||||
let dev = find_device(&args.device, USAGE_TELEMETRY).await?;
|
||||
let reader = dev.open_readable().await?;
|
||||
let writer: Box<dyn StateEmitter> = match format {
|
||||
@@ -256,24 +819,38 @@ async fn main() -> HidResult<()> {
|
||||
}
|
||||
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
|
||||
let mut handle = dev.open_feature_handle().await?;
|
||||
let kind = if *bootloader {
|
||||
CommandKind::Bootloader
|
||||
} else {
|
||||
print!("Rebooting...");
|
||||
AudioDeviceCommand::Reset
|
||||
CommandKind::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"),
|
||||
|
||||
if let Err(error) = send_command(&mut handle, 0, kind, &[]).await
|
||||
&& !matches!(error, HidError::Disconnected | HidError::NotConnected)
|
||||
{
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
if *bootloader {
|
||||
log::info!("requested bootloader reboot");
|
||||
println!("Rebooting into bootloader...");
|
||||
} else {
|
||||
log::info!("requested reboot");
|
||||
println!("Rebooting...");
|
||||
}
|
||||
}
|
||||
Some(Command::Config(config)) => {
|
||||
log::info!("updating configuration");
|
||||
apply_config(&args.device, config).await?;
|
||||
}
|
||||
Some(Command::Show) => {
|
||||
log::info!("reading configuration");
|
||||
show_config(&args.device).await?;
|
||||
}
|
||||
Some(Command::Hardware) => {
|
||||
log::info!("reading hardware info");
|
||||
show_hardware(&args.device).await?;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user