Move usb clas loop to private function

Move const to the outside of the logger
This commit is contained in:
Jomer.Dev 2024-02-12 19:01:22 +01:00
parent 2c6b475f4e
commit 16ed0b1e37

View file

@ -6,7 +6,7 @@ use core::fmt::Write as _;
use embassy_futures::join::join;
use embassy_sync::pipe::Pipe;
use embassy_usb::class::cdc_acm::{CdcAcmClass, State};
use embassy_usb::class::cdc_acm::{CdcAcmClass, Receiver, Sender, State};
use embassy_usb::driver::Driver;
use embassy_usb::{Builder, Config};
use log::{Metadata, Record};
@ -37,6 +37,9 @@ impl<'d> LoggerState<'d> {
}
}
/// The packet size used in the usb logger, to be used with `create_future_from_class`
pub const MAX_PACKET_SIZE: u8 = 64;
/// The logger handle, which contains a pipe with configurable size for buffering log messages.
pub struct UsbLogger<const N: usize> {
buffer: Pipe<CS, N>,
@ -54,7 +57,6 @@ impl<const N: usize> UsbLogger<N> {
D: Driver<'d>,
Self: 'd,
{
const MAX_PACKET_SIZE: u8 = 64;
let mut config = Config::new(0xc0de, 0xcafe);
config.manufacturer = Some("Embassy");
config.product = Some("USB-serial logger");
@ -87,6 +89,15 @@ impl<const N: usize> UsbLogger<N> {
let mut device = builder.build();
loop {
let run_fut = device.run();
let class_fut = self.run_logger_class(&mut sender, &mut receiver);
join(run_fut, class_fut).await;
}
}
async fn run_logger_class<'d, D>(&self, sender: &mut Sender<'d, D>, receiver: &mut Receiver<'d, D>)
where
D: Driver<'d>,
{
let log_fut = async {
let mut rx: [u8; MAX_PACKET_SIZE as usize] = [0; MAX_PACKET_SIZE as usize];
sender.wait_connection().await;
@ -105,8 +116,8 @@ impl<const N: usize> UsbLogger<N> {
let _ = receiver.read_packet(&mut discard_buf).await;
}
};
join(run_fut, join(log_fut, discard_fut)).await;
}
join(log_fut, discard_fut).await;
}
/// Creates the futures needed for the logger from a given class
@ -115,29 +126,9 @@ impl<const N: usize> UsbLogger<N> {
where
D: Driver<'d>,
{
const MAX_PACKET_SIZE: u8 = 64;
let (mut sender, mut receiver) = class.split();
loop {
let log_fut = async {
let mut rx: [u8; MAX_PACKET_SIZE as usize] = [0; MAX_PACKET_SIZE as usize];
sender.wait_connection().await;
loop {
let len = self.buffer.read(&mut rx[..]).await;
let _ = sender.write_packet(&rx[..len]).await;
if len as u8 == MAX_PACKET_SIZE {
let _ = sender.write_packet(&[]).await;
}
}
};
let discard_fut = async {
let mut discard_buf: [u8; MAX_PACKET_SIZE as usize] = [0; MAX_PACKET_SIZE as usize];
receiver.wait_connection().await;
loop {
let _ = receiver.read_packet(&mut discard_buf).await;
}
};
join(log_fut, discard_fut).await;
self.run_logger_class(&mut sender, &mut receiver).await;
}
}
}