From 9b515a042f1f76d3982d972965e9279c82f69063 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sat, 13 Sep 2025 15:37:08 +0800 Subject: [PATCH] add serial port library functions and handlers this creates hooks for applications to listen to the serial port, as well as to send and receive data. some improvements to code ordering for readability are bundled in this as well. very lightly tested, most of the code comes from other more tested code in the Precursor stack. the TRNG test stuff is not put into this stack because I think it belongs in the baremetal environment, as it's only ever run for characterization. We don't need to bog down the production stack with test code. --- services/usb-bao1x/src/api.rs | 10 +- services/usb-bao1x/src/hw.rs | 321 +++++++++++++++------------------ services/usb-bao1x/src/lib.rs | 36 ++-- services/usb-bao1x/src/main.rs | 254 ++++++++++++++++++++++++-- 4 files changed, 407 insertions(+), 214 deletions(-) diff --git a/services/usb-bao1x/src/api.rs b/services/usb-bao1x/src/api.rs index 945896aa7..8d00cd702 100644 --- a/services/usb-bao1x/src/api.rs +++ b/services/usb-bao1x/src/api.rs @@ -56,9 +56,12 @@ pub(crate) enum Opcode { SerialClearHooks = 517, /// TRNG send poll SerialTrngPoll = 518, + /// Send serial data + SerialSendData = 519, /// Interrupt-context USB stack messages IrqFidoRx = 768, + IrqSerialRx = 769, #[cfg(feature = "mass-storage")] SetBlockDevice = 1024, @@ -155,17 +158,16 @@ impl TryFrom for UsbDeviceType { } } -pub const SERIAL_BINARY_BUFLEN: usize = 128; +pub const SERIAL_BINARY_BUFLEN: usize = 3840; // save 256 bytes on the page for Rkyv overhead #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Clone)] pub struct UsbSerialAscii { pub s: String, pub delimiter: Option, } -#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] pub struct UsbSerialBinary { - pub d: [u8; SERIAL_BINARY_BUFLEN], - pub len: usize, + pub d: Vec, } pub const MAX_HID_REPORT_DESCRIPTOR_LEN: usize = 1024; diff --git a/services/usb-bao1x/src/hw.rs b/services/usb-bao1x/src/hw.rs index 78767066d..8d216d3d5 100644 --- a/services/usb-bao1x/src/hw.rs +++ b/services/usb-bao1x/src/hw.rs @@ -24,36 +24,150 @@ use xous_usb_hid::prelude::*; use crate::Opcode; -/* - 1. interrupt enters - 2. poll() is called in a loop - - this loop is the process_event_ring() "loop" - - the result of poll() is immediately passed on to the Class() handler *before* the Event is dequeued - - the read()/write() functions calls that would interact with the Transfer TRBs should all be called by now - - (so, the events are handled one-by-one even though "poll" natively wants to aggregate all simultaneous events) - 3. only after the loop is done, do we execute the post-amble Event DeQueue pointer update - 4. EP allocation simply manages some bookkeeping that allows the EpAddress to be passed on to read()/write() - call such that the handlers line up with the packet type. This virtually implements the function-pointer immediate - decode & dispatch of handlers within the framework of the USB crate - 5. interrupt exits +/// Maximum packet size for serial - tied to the speed of the port (HS) +pub const SERIAL_MAX_PACKET_SIZE: usize = 512; - I think this succeeds where the previous version fails because: - - the EventTRB is only dequeued after all the transfer pending data is handled - previously we would - dequeue the EventTRB, then potentially take arbitrarily long (due to interruptability) to handle the - TransferTRB, which could allow the TransferTRB to be overwritten because the existence of the EventTRB - is more of what stalls the packet engine - - The actual "set stall" handler thus might actually be nil, because the stall I believe is automatically - originated within the USB hardware itself, as it knows that a packet is pending and will NAK the packets. - The clearing of the stall is the only thing that might need an implementation, and that is equivalently - the enqueue ZLP function but we need to revisit this on a case by case basis - it might make sense for - the system to unstall right away based on the read of the TransferTRB instead of trying to split the - unstall call to work with the usb-device stack. +#[repr(align(32))] +pub struct CramiumUsb<'a> { + pub conn: xous::CID, + pub csr: AtomicCsr, + pub irq_csr: AtomicCsr, + pub fido_tx_queue: RefCell>, + pub kbd_tx_queue: RefCell>, + pub irq_req: Option, + pub wrapper: CorigineWrapper, + pub device: UsbDevice<'a, CorigineWrapper>, + pub class: UsbHidClass< + 'a, + CorigineWrapper, + frunk_core::hlist::HCons< + RawFido<'a, CorigineWrapper>, + frunk_core::hlist::HCons, frunk_core::hlist::HNil>, + >, + >, + // storage for hid_packets to expatriate from the interrupt handler + pub hid_packet: Option<[u8; 64]>, + pub serial_port: SerialPort<'a, CorigineWrapper, [u8; 1024], [u8; 1024]>, + // holds one HS packet - must be statically allocated in IRQ handler. Valid length is + // passed as part of the interrupt recovery message. + pub serial_rx: [u8; SERIAL_MAX_PACKET_SIZE], +} - Another option would be to just figure out how to abuse the usb-device stack to simply generate - a formatted device descriptor that we can feed into the state-machine based implementation provided - by the vendor as a reference. +impl<'a> CramiumUsb<'a> { + pub fn new( + csr: AtomicCsr, + irq_csr: AtomicCsr, + cid: xous::CID, + cw: CorigineWrapper, + usb_alloc: &'a UsbBusAllocator, + serial_number: &'a String, + ) -> Self { + let class = UsbHidClassBuilder::new() + .add_device(NKROBootKeyboardConfig::default()) + .add_device(RawFidoConfig::default()) + .build(usb_alloc); -*/ + let rx_buf = [0u8; SERIAL_MAX_PACKET_SIZE * 2]; + let tx_buf = [0u8; SERIAL_MAX_PACKET_SIZE * 2]; + let serial_port = SerialPort::new_with_store(&usb_alloc, rx_buf, tx_buf); + // HACK ALERT: due to a shortcoming in the usb-device implementation, inside the interrupt handler we + // have to catch and parse SETUP-OUT sequences. Basically the driver assumes that the OUT endpoint is + // always configured to trigger, but in our stack every time we have an OUT on EP0, we have to + // set it up with the correct length. See the "TrbType::SetupPkt" arm of handle_event_inner() + // for more details. + // + // In particular, Mass Storage has to handle a similar situation, so if adding a mass storage + // interface, this hack has to be dealt with (and btw, there are not enough endpoints availbale + // to concurrently add that in - you have to kick out one of the interfaces above to add mass + // storage!) + + let device = UsbDeviceBuilder::new(&usb_alloc, UsbVidPid(0x1209, 0x3613)) + .manufacturer("Baochip") + .product("Baosec") + .serial_number(&serial_number) + // this is *required* by the corigine stack + .max_packet_size_0(64) + .composite_with_iads() + .build(); + + CramiumUsb { + conn: cid, + // safety: we created iframrange to have the exact same P&V mappings + wrapper: cw, + device, + class, + csr, + irq_csr, + fido_tx_queue: RefCell::new(VecDeque::new()), + kbd_tx_queue: RefCell::new(VecDeque::new()), + irq_req: None, + hid_packet: None, + serial_port, + serial_rx: [0u8; SERIAL_MAX_PACKET_SIZE], + } + } + + pub fn init(&mut self) { + // this has to be done in `main` because we're passing a pointer to the Box'd structure, which + // the IRQ handler can freely and safely manipulate + xous::claim_interrupt( + utra::irqarray1::IRQARRAY1_IRQ, + composite_handler, + self as *mut CramiumUsb as *mut usize, + ) + .expect("couldn't claim irq"); + log::debug!("claimed IRQ with state at {:x}", self as *mut CramiumUsb as usize); + + // enable both the corigine core IRQ and the software IRQ bit + // software IRQ is used to initiate send/receive from software to the interrupt context + self.irq_csr.wo(utra::irqarray1::EV_SOFT, 0); + self.irq_csr.wo(utra::irqarray1::EV_EDGE_TRIGGERED, 0); + self.irq_csr.wo(utra::irqarray1::EV_POLARITY, 0); + + self.wrapper.hw.lock().unwrap().init(); + self.wrapper.hw.lock().unwrap().start(); + self.wrapper.hw.lock().unwrap().update_current_speed(); + + // irq must me enabled without dependency on the hw lock + self.irq_csr.wo(utra::irqarray1::EV_PENDING, 0xFFFF_FFFF); + self.irq_csr.wo(utra::irqarray1::EV_ENABLE, CORIGINE_IRQ_MASK | SW_IRQ_MASK); + } + + pub fn sw_irq(&mut self, request_type: UsbIrqReq) { + self.irq_req = Some(request_type); + self.irq_csr.wfo(utra::irqarray1::EV_SOFT_TRIGGER, SW_IRQ_MASK); + } + + /// Process an unplug event + pub fn unplug(&mut self) { + // disable all interrupts so we can safely go through initialization routines + self.irq_csr.wo(utra::irqarray1::EV_ENABLE, 0); + + self.wrapper.hw.lock().unwrap().reset(); + self.wrapper.hw.lock().unwrap().init(); + self.wrapper.hw.lock().unwrap().start(); + self.wrapper.hw.lock().unwrap().update_current_speed(); + + // reset all shared data structures + self.device.force_reset().ok(); + self.fido_tx_queue = RefCell::new(VecDeque::new()); + self.kbd_tx_queue = RefCell::new(VecDeque::new()); + self.irq_req = None; + self.wrapper.event = None; + self.wrapper.address_is_set.store(false, Ordering::SeqCst); + self.wrapper.ep_out_ready = (0..cramium_hal::usb::driver::CRG_EP_NUM + 1) + .map(|_| std::sync::Arc::new(core::sync::atomic::AtomicBool::new(false))) + .collect::>() + .into_boxed_slice(); + for ready in self.wrapper.ep_out_ready.iter() { + ready.store(false, Ordering::SeqCst); + } + + // re-enable IRQs + self.irq_csr.wo(utra::irqarray1::EV_PENDING, 0xFFFF_FFFF); + self.irq_csr.wo(utra::irqarray1::EV_ENABLE, CORIGINE_IRQ_MASK | SW_IRQ_MASK); + } +} #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum UsbIrqReq { @@ -126,17 +240,10 @@ pub(crate) fn composite_handler(_irq_no: usize, arg: *mut usize) { let class = usb.class.borrow_mut(); let serial = usb.serial_port.borrow_mut(); if device.poll(&mut [class, serial as &mut dyn UsbClass<_>]) { - let mut buf = [0u8; 512]; - if let Ok(count) = serial.read(&mut buf) { - for &d in buf[..count].iter() { - usb.serial_rx.push_back(d); - } - // crate::println!("serial read: {:x?}", &buf[..count]); - - // TODO: implement the actual Xous serial API instead of this stand-in routine + if let Ok(count) = serial.read(&mut usb.serial_rx) { xous::try_send_message( usb.conn, - Message::new_scalar(Opcode::SerialFlush.to_usize().unwrap(), 0, 0, 0, 0), + Message::new_scalar(Opcode::IrqSerialRx.to_usize().unwrap(), count, 0, 0, 0), ) .ok(); } @@ -227,145 +334,3 @@ pub(crate) fn composite_handler(_irq_no: usize, arg: *mut usize) { } } } - -#[repr(align(32))] -pub struct CramiumUsb<'a> { - pub conn: xous::CID, - pub csr: AtomicCsr, - pub irq_csr: AtomicCsr, - pub fido_tx_queue: RefCell>, - pub kbd_tx_queue: RefCell>, - pub irq_req: Option, - pub wrapper: CorigineWrapper, - pub device: UsbDevice<'a, CorigineWrapper>, - pub class: UsbHidClass< - 'a, - CorigineWrapper, - frunk_core::hlist::HCons< - RawFido<'a, CorigineWrapper>, - frunk_core::hlist::HCons, frunk_core::hlist::HNil>, - >, - >, - // storage for hid_packets to expatriate from the interrupt handler - pub hid_packet: Option<[u8; 64]>, - pub serial_port: SerialPort<'a, CorigineWrapper, [u8; 1024], [u8; 1024]>, - pub serial_rx: VecDeque, -} - -impl<'a> CramiumUsb<'a> { - pub fn new( - csr: AtomicCsr, - irq_csr: AtomicCsr, - cid: xous::CID, - cw: CorigineWrapper, - usb_alloc: &'a UsbBusAllocator, - serial_number: &'a String, - ) -> Self { - let class = UsbHidClassBuilder::new() - .add_device(NKROBootKeyboardConfig::default()) - .add_device(RawFidoConfig::default()) - .build(usb_alloc); - - // this buffer needs to be at least as big as the max packet size, ideally 2x as much. Set it to - // 1k. - let rx_buf = [0u8; 1024]; - let tx_buf = [0u8; 1024]; - let serial_port = SerialPort::new_with_store(&usb_alloc, rx_buf, tx_buf); - // HACK ALERT: due to a shortcoming in the usb-device implementation, inside the interrupt handler we - // have to catch and parse SETUP-OUT sequences. Basically the driver assumes that the OUT endpoint is - // always configured to trigger, but in our stack every time we have an OUT on EP0, we have to - // set it up with the correct length. See the "TrbType::SetupPkt" arm of handle_event_inner() - // for more details. - // - // In particular, Mass Storage has to handle a similar situation, so if adding a mass storage - // interface, this hack has to be dealt with (and btw, there are not enough endpoints availbale - // to concurrently add that in - you have to kick out one of the interfaces above to add mass - // storage!) - - let device = UsbDeviceBuilder::new(&usb_alloc, UsbVidPid(0x1209, 0x3613)) - .manufacturer("Baochip") - .product("Baosec") - .serial_number(&serial_number) - // this is *required* by the corigine stack - .max_packet_size_0(64) - .composite_with_iads() - .build(); - - CramiumUsb { - conn: cid, - // safety: we created iframrange to have the exact same P&V mappings - wrapper: cw, - device, - class, - csr, - irq_csr, - fido_tx_queue: RefCell::new(VecDeque::new()), - kbd_tx_queue: RefCell::new(VecDeque::new()), - irq_req: None, - hid_packet: None, - serial_port, - serial_rx: VecDeque::new(), - } - } - - pub fn init(&mut self) { - // this has to be done in `main` because we're passing a pointer to the Box'd structure, which - // the IRQ handler can freely and safely manipulate - xous::claim_interrupt( - utra::irqarray1::IRQARRAY1_IRQ, - composite_handler, - self as *mut CramiumUsb as *mut usize, - ) - .expect("couldn't claim irq"); - log::debug!("claimed IRQ with state at {:x}", self as *mut CramiumUsb as usize); - - // enable both the corigine core IRQ and the software IRQ bit - // software IRQ is used to initiate send/receive from software to the interrupt context - self.irq_csr.wo(utra::irqarray1::EV_SOFT, 0); - self.irq_csr.wo(utra::irqarray1::EV_EDGE_TRIGGERED, 0); - self.irq_csr.wo(utra::irqarray1::EV_POLARITY, 0); - - self.wrapper.hw.lock().unwrap().init(); - self.wrapper.hw.lock().unwrap().start(); - self.wrapper.hw.lock().unwrap().update_current_speed(); - - // irq must me enabled without dependency on the hw lock - self.irq_csr.wo(utra::irqarray1::EV_PENDING, 0xFFFF_FFFF); - self.irq_csr.wo(utra::irqarray1::EV_ENABLE, CORIGINE_IRQ_MASK | SW_IRQ_MASK); - } - - pub fn sw_irq(&mut self, request_type: UsbIrqReq) { - self.irq_req = Some(request_type); - self.irq_csr.wfo(utra::irqarray1::EV_SOFT_TRIGGER, SW_IRQ_MASK); - } - - /// Process an unplug event - pub fn unplug(&mut self) { - // disable all interrupts so we can safely go through initialization routines - self.irq_csr.wo(utra::irqarray1::EV_ENABLE, 0); - - self.wrapper.hw.lock().unwrap().reset(); - self.wrapper.hw.lock().unwrap().init(); - self.wrapper.hw.lock().unwrap().start(); - self.wrapper.hw.lock().unwrap().update_current_speed(); - - // reset all shared data structures - self.device.force_reset().ok(); - self.fido_tx_queue = RefCell::new(VecDeque::new()); - self.kbd_tx_queue = RefCell::new(VecDeque::new()); - self.irq_req = None; - self.wrapper.event = None; - self.wrapper.address_is_set.store(false, Ordering::SeqCst); - self.wrapper.ep_out_ready = (0..cramium_hal::usb::driver::CRG_EP_NUM + 1) - .map(|_| core::sync::atomic::AtomicBool::new(false)) - .collect::>() - .into_boxed_slice(); - for ready in self.wrapper.ep_out_ready.iter() { - ready.store(false, Ordering::SeqCst); - } - - // re-enable IRQs - self.irq_csr.wo(utra::irqarray1::EV_PENDING, 0xFFFF_FFFF); - self.irq_csr.wo(utra::irqarray1::EV_ENABLE, CORIGINE_IRQ_MASK | SW_IRQ_MASK); - } -} diff --git a/services/usb-bao1x/src/lib.rs b/services/usb-bao1x/src/lib.rs index 913ec9c78..e71a2fc6b 100644 --- a/services/usb-bao1x/src/lib.rs +++ b/services/usb-bao1x/src/lib.rs @@ -1,16 +1,10 @@ #![cfg_attr(target_os = "none", no_std)] -#[cfg(feature = "cramium-soc")] -use cram_hal_service::trng; -#[cfg(feature = "hosted-baosec")] -use cramium_emu::trng; - pub mod api; pub use api::*; use num_traits::*; use packed_struct::PackedStruct; use rkyv::option::ArchivedOption; -use trng::api::TrngTestMode; pub use usb_device::device::UsbDeviceState; use xous::{CID, Message, send_message}; use xous_ipc::Buffer; @@ -18,6 +12,7 @@ pub use xous_usb_hid::device::fido::RawFidoReport; pub use xous_usb_hid::device::keyboard::KeyboardLedsReport; pub use xous_usb_hid::page::Keyboard as UsbKeyCode; +// TODO: this object is misnamed, it also includes a serial handler #[derive(Debug)] pub struct UsbHid { conn: CID, @@ -239,13 +234,13 @@ impl UsbHid { /// Another thread can be used to call serial_flush() if we don't want to /// block forever and we're receiving small amounts of binary data. pub fn serial_wait_binary(&self) -> Vec { - let req = UsbSerialBinary { d: [0u8; SERIAL_BINARY_BUFLEN], len: 0 }; + let req = UsbSerialBinary { d: Vec::new() }; let mut buf = Buffer::into_buf(req).or(Err(xous::Error::InternalError)).expect("Internal error"); buf.lend_mut(self.conn, Opcode::SerialHookBinary.to_u32().unwrap()) .or(Err(xous::Error::InternalError)) .expect("Internal error"); let resp = buf.to_original::().unwrap(); - resp.d[..resp.len].to_vec() + resp.d } /// Non-blocking call that issues a serial flush command to the USB stack @@ -272,19 +267,18 @@ impl UsbHid { .unwrap(); } - /// Tries to set the serial port in TRNG mode. Will silently fail if already in console mode. - pub fn serial_set_trng_mode(&self, mode: TrngTestMode) { - send_message( - self.conn, - Message::new_scalar( - Opcode::SerialHookTrngSender.to_usize().unwrap(), - mode.to_usize().unwrap(), - 0, - 0, - 0, - ), - ) - .unwrap(); + /// Takes a slice-u8 and tries to send the data. Reports how many bytes were actually sent. + pub fn serial_send(&self, data: &[u8]) -> Result { + let mut sender = UsbSerialBinary { d: Vec::new() }; + // sendable length is limited by the size of a page of memory, e.g. how much we can map + // into the receiving process in a single go + let sendable_len = data.len().min(SERIAL_BINARY_BUFLEN); + sender.d.extend_from_slice(data); + let buf = Buffer::into_buf(sender).or(Err(xous::Error::InternalError)).expect("Internal error"); + // NOTE: The send will not fail if the host receiver can't accept the characters (i.e. no host + // connected) + buf.send(self.conn, Opcode::SerialSendData.to_u32().unwrap()).ok(); + Ok(sendable_len) } pub fn register_u2f_observer(&self, server_name: &str, action_opcode: usize) { diff --git a/services/usb-bao1x/src/main.rs b/services/usb-bao1x/src/main.rs index d66febc6d..55a360d70 100644 --- a/services/usb-bao1x/src/main.rs +++ b/services/usb-bao1x/src/main.rs @@ -14,7 +14,7 @@ use std::collections::VecDeque; use std::panic; use std::sync::Arc; -use api::{HIDReport, LogLevel, Opcode, U2fCode, U2fMsgIpc, UsbListenerRegistration}; +use api::*; use cramium_api::keyboard::KeyMap; use cramium_hal::axp2101::VbusIrq; use cramium_hal::usb::driver::{CorigineUsb, CorigineWrapper}; @@ -35,11 +35,21 @@ enum TimeoutOp { Quit, } -/* - TODO: - - [ ] Reduce debug spew. This is left in place for now because we will definitely need it in the - future and it hasn't seemed to affect the stack operation like it did in the user-space implementation. -*/ +#[derive(Debug)] +enum SerialListenMode { + // this just causes data incoming to be printed to the debug log; it is the default + NoListener, + // this assumes there will be a CR/LF character to delimit lines (the `char` arg), and + // will buffer data until two conditions are met: 1) a listener is hooked and 2) a CR/LF is received. + // This will "infinitely" buffer incoming characters if no listener is hooked. + AsciiListener(Option), + // this will simply buffer the data until the `usize` argument is met and passes it back to + // hooked listener. If this mode is set and there is no listener, it will buffer data "indefinitely" + // (e.g. until local heap is exhausted and the system panics) + BinaryListener, + // this will take any serial input and pass it on as if one was typing at the console + ConsoleListener, +} fn main() -> ! { #[cfg(target_os = "xous")] @@ -145,6 +155,12 @@ pub(crate) fn main_hw() -> ! { let mut cu = Box::new(CramiumUsb::new(usb.clone(), irq_csr.clone(), cid, cw, &usb_alloc, &serial_number)); cu.init(); + // Serial driver variables + let mut serial_listener: Option = None; + let mut serial_listen_mode: SerialListenMode = SerialListenMode::NoListener; + let mut serial_buf = Vec::::new(); + let mut serial_rx_trigger = false; // when true, the condition was met to pass data to the listener (but the listener was not yet installed) + // under the theory that PIDs cannot be forged. // also if someone commandeers a process, all bets are off within that process (this is a general // statement) @@ -525,11 +541,227 @@ pub(crate) fn main_hw() -> ! { LogLevel::Err => log::set_max_level(log::LevelFilter::Error), } }), - Opcode::SerialFlush => { - // temporary code - let all_items: Vec = cu.serial_rx.drain(..).collect(); - log::info!("received: {:x?}", all_items); // echo back - let _ = cu.serial_port.write(&all_items); + Opcode::IrqSerialRx => msg_scalar_unpack!(msg, valid_bytes, _, _, _, { + serial_buf.extend_from_slice(&cu.serial_rx[..valid_bytes]); + match serial_listen_mode { + SerialListenMode::NoListener => { + match std::str::from_utf8(&serial_buf) { + Ok(s) => log::info!("No listener ascii: {}", s), + Err(_) => { + log::info!("No listener binary: {:x?}", &serial_buf); + } + } + serial_buf.clear(); + } + SerialListenMode::ConsoleListener => { + match std::str::from_utf8(&serial_buf) { + Ok(s) => { + for c in s.chars() { + native_kbd.inject_key(c); + } + } + Err(_) => { + log::info!("Non UTF-8 received on console: {:x?}", &serial_buf); + } + } + serial_buf.clear(); + } + SerialListenMode::AsciiListener(maybe_delimiter) => { + if let Some(delimiter) = maybe_delimiter { + if !delimiter.is_ascii() { + log::warn!( + "Chosen ASCII delimiter {} is not ASCII. Serial receive will not function properly.", + delimiter + ); + } + if !serial_rx_trigger { + // once true, sticks as true + serial_rx_trigger = + serial_buf.iter().find(|&&c| c == (delimiter as u8)).is_some(); + } + } else { + serial_rx_trigger = true; + } + // now see if we should pass it back to the listener (if it is hooked) + if serial_rx_trigger && serial_listener.is_some() { + let mut rx_msg = serial_listener.take().unwrap(); + let mut response = unsafe { + Buffer::from_memory_message_mut(rx_msg.body.memory_message_mut().unwrap()) + }; + let mut buf = response.to_original::().unwrap(); + use std::fmt::Write; // is this really the best way to do it? probably not. + write!(buf.s, "{}", std::string::String::from_utf8_lossy(&serial_buf)).ok(); + + response.replace(buf).unwrap(); + // the rx_msg will drop and respond to the listener + serial_rx_trigger = false; + serial_buf.clear(); + } + } + SerialListenMode::BinaryListener => { + match serial_listener.take() { + Some(mut rx_msg) => { + let mut response = unsafe { + Buffer::from_memory_message_mut(rx_msg.body.memory_message_mut().unwrap()) + }; + let mut buf = response.to_original::().unwrap(); + let n = serial_buf.len().min(SERIAL_BINARY_BUFLEN); + let at_most_one_page: Vec = serial_buf.drain(..n).collect(); + buf.d.extend_from_slice(&at_most_one_page); + response.replace(buf).unwrap(); + // the rx_msg will drop and respond to the listener + } + None => { + // do nothing, keep queuing data... + } + } + } + } + }), + Opcode::SerialHookAscii => { + let maybe_delimiter = { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let data = buffer.to_original::().unwrap(); + data.delimiter + }; + serial_listen_mode = SerialListenMode::AsciiListener(maybe_delimiter); + serial_listener = msg_opt.take(); + } + Opcode::SerialHookBinary => { + serial_listen_mode = SerialListenMode::BinaryListener; + serial_listener = msg_opt.take(); + } + Opcode::SerialHookConsole => msg_scalar_unpack!(msg, _, _, _, _, { + let log_conn = xous::connect(xous::SID::from_bytes(b"xous-log-server ").unwrap()).unwrap(); + match xous::send_message( + log_conn, + xous::Message::new_blocking_scalar( + log_server::api::Opcode::TryHookUsbMirror.to_usize().unwrap(), + 0, + 0, + 0, + 0, + ), + ) { + Ok(xous::Result::Scalar1(result)) => { + if result == 1 { + serial_listen_mode = SerialListenMode::ConsoleListener; + // unhook any previous pending listener + serial_listener.take(); + } else { + log::error!("Error trying to connect USB console."); + } + } + _ => { + log::error!("Could not connect USB console"); + } + } + }), + Opcode::SerialClearHooks => { + let log_conn = xous::connect(xous::SID::from_bytes(b"xous-log-server ").unwrap()).unwrap(); + // it is never harmful to double-unhook this + xous::send_message( + log_conn, + xous::Message::new_blocking_scalar( + log_server::api::Opcode::UnhookUsbMirror.to_usize().unwrap(), + 0, + 0, + 0, + 0, + ), + ) + .ok(); + + serial_listen_mode = SerialListenMode::NoListener; + serial_listener.take(); + } + Opcode::SerialFlush => msg_scalar_unpack!(msg, _, _, _, _, { + // this will hardware flush any pending items in usb_serial driver + cu.serial_port.flush().ok(); + // this tries to return any data that's pending within the main loop's buffers + match serial_listen_mode { + SerialListenMode::BinaryListener => { + match serial_listener.take() { + Some(mut rx_msg) => { + let mut response = unsafe { + Buffer::from_memory_message_mut(rx_msg.body.memory_message_mut().unwrap()) + }; + let mut buf = response.to_original::().unwrap(); + let chars_avail = serial_buf.len().min(SERIAL_BINARY_BUFLEN); + buf.d.copy_from_slice(serial_buf.drain(..chars_avail).as_slice()); + response.replace(buf).unwrap(); + // the rx_msg will drop and respond to the listener + } + None => { + // do nothing, keep queuing data... + } + } + } + SerialListenMode::AsciiListener(_) => { + match serial_listener.take() { + Some(mut rx_msg) => { + let mut response = unsafe { + Buffer::from_memory_message_mut(rx_msg.body.memory_message_mut().unwrap()) + }; + let mut buf = response.to_original::().unwrap(); + use std::fmt::Write; // is this really the best way to do it? probably not. + write!(buf.s, "{}", std::string::String::from_utf8_lossy(&serial_buf)).ok(); + + response.replace(buf).unwrap(); + // the rx_msg will drop and respond to the listener + serial_rx_trigger = false; + } + None => {} // do nothing + } + } + _ => {} + } + }), + Opcode::SerialSendData => { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let data = buffer.to_original::().unwrap(); + let mut total_sent = 0; + for chunk in data.d.chunks(crate::hw::SERIAL_MAX_PACKET_SIZE) { + match cu.serial_port.write(chunk) { + Ok(sent) => total_sent += sent, + Err(e) => { + log::error!("Error in SerialSendData: {:?}", e); + } + } + } + log::debug!("Serial sent {} bytes", total_sent); + } + Opcode::LogString => { + // the logger API is "best effort" only. Because retries and response codes can cause problems + // in the logger API, if anything goes wrong, we prefer to discard characters rather than get + // the whole subsystem stuck in some awful recursive error handling hell. + match msg.body.memory_message() { + Some(mem_msg) => { + let buffer = unsafe { Buffer::from_memory_message(mem_msg) }; + match buffer.to_original::() { + Ok(usb_send) => { + // this is implemented as a "blocking write": the routine will block until the + // data has all been written. + let send_data = usb_send.s.as_bytes(); + let to_send = usb_send.s.len(); + let mut sent = 0; + while sent < to_send { + match cu.serial_port.write(&send_data[sent..to_send]) { + Ok(written) => { + sent += written; + } + Err(_) => { + // just drop characters + } + } + cu.serial_port.flush().ok(); // just drop characters on error + } + } + _ => {} // silent errors + } + } + _ => {} // silent errors + } } Opcode::InvalidCall => { log::warn!("Illegal opcode received {:?}", msg);