use std::{fs::OpenOptions, io::Write, thread, time::Duration}; use anyhow::{Result, Context}; use tracing::{info, warn}; #[derive(Clone)] pub struct UsbGadget { udc_file: &'static str, } impl UsbGadget { pub fn new(name: &'static str) -> Self { // /sys/kernel/config/usb_gadget//UDC Self { udc_file: Box::leak( format!("/sys/kernel/config/usb_gadget/{name}/UDC").into_boxed_str()) } } /// Force the host to re‑enumerate our HID gadget. pub fn cycle(&self) -> Result<()> { info!("UDC‑cycle: detaching gadget"); OpenOptions::new().write(true).open(self.udc_file)?.write_all(b"")?; thread::sleep(Duration::from_millis(200)); let udc_name = std::fs::read_dir("/sys/class/udc")? .next() .transpose()? .context("no UDC present")? .file_name(); info!("UDC‑cycle: re‑attaching to {}", udc_name.to_string_lossy()); OpenOptions::new().write(true).open(self.udc_file)? .write_all(udc_name.to_str().unwrap().as_bytes())?; info!("USB‑gadget cycled"); Ok(()) } }