use alloc::vec::Vec;
use embedded_io::ErrorType;
use embedded_io_async::{Read, Write};
use crate::base::channel::Channel;
use crate::base::connection::Connection;
use crate::base::error::Error;
use crate::shell::v2::{self as shell_v2, CommandOutput, Shell};
pub struct Logcat<
'a,
'b,
T,
const MAX_CHANNELS: usize = { crate::base::connection::DEFAULT_MAX_CHANNELS },
const MAX_PROPERTIES: usize = { crate::base::connection::DEFAULT_MAX_PROPERTIES },
const MAX_FEATURES: usize = { crate::base::connection::DEFAULT_MAX_FEATURES },
> where
T: Read + Write,
{
channel: Channel<'a, T, MAX_CHANNELS, MAX_PROPERTIES, MAX_FEATURES>,
buf: &'b mut [u8],
acc_end: usize,
head: usize,
tail: usize,
}
impl<
'a,
'b,
T,
const MAX_CHANNELS: usize,
const MAX_PROPERTIES: usize,
const MAX_FEATURES: usize,
> Logcat<'a, 'b, T, MAX_CHANNELS, MAX_PROPERTIES, MAX_FEATURES>
where
T: Read + Write,
{
fn new(
channel: Channel<'a, T, MAX_CHANNELS, MAX_PROPERTIES, MAX_FEATURES>,
buf: &'b mut [u8],
) -> Self {
assert!(
buf.len() >= shell_v2::HEADER_SIZE,
"Logcat buffer must be at least {} bytes",
shell_v2::HEADER_SIZE,
);
Self {
channel,
buf,
acc_end: 0,
head: 0,
tail: 0,
}
}
fn compact_raw(&mut self) {
if self.acc_end < self.head {
self.buf.copy_within(self.head..self.tail, self.acc_end);
self.tail -= self.head - self.acc_end;
self.head = self.acc_end;
}
}
async fn fill_raw(&mut self, n: usize) -> Result<(), Error<<T as ErrorType>::Error>> {
while self.tail - self.head < n {
if self.tail >= self.buf.len() {
self.compact_raw();
if self.tail >= self.buf.len() {
return Err(Error::ReceiveBufferFull);
}
}
let read = self.channel.read(&mut self.buf[self.tail..]).await?;
self.tail += read;
}
Ok(())
}
fn absorb_stdout(&mut self, payload_len: usize) {
self.compact_raw();
let payload_start = self.head + shell_v2::HEADER_SIZE;
let payload_end = payload_start + payload_len;
self.buf.copy_within(payload_start..payload_end, self.head);
self.acc_end = self.head + payload_len;
self.head = payload_end;
}
pub async fn read_entry(&mut self) -> Result<LogEntry, Error<<T as ErrorType>::Error>> {
loop {
if let Some((entry, consumed)) =
parse_entry(&self.buf[..self.acc_end]).map_err(Error::Logcat)?
{
self.buf.copy_within(consumed..self.acc_end, 0);
self.acc_end -= consumed;
return Ok(entry);
}
loop {
match self.fill_raw(shell_v2::HEADER_SIZE).await {
Ok(()) => {}
Err(Error::ChannelClosed) => return self.drain_acc_or_close(),
Err(e) => return Err(e),
}
let hdr: [u8; shell_v2::HEADER_SIZE] = self.buf
[self.head..self.head + shell_v2::HEADER_SIZE]
.try_into()
.unwrap();
let (id, payload_len) = shell_v2::parse_header(&hdr);
let frame_size = shell_v2::HEADER_SIZE + payload_len as usize;
match self.fill_raw(frame_size).await {
Ok(()) => {}
Err(Error::ChannelClosed) => return self.drain_acc_or_close(),
Err(e) => return Err(e),
}
match id {
shell_v2::STDOUT => {
self.absorb_stdout(payload_len as usize);
break;
}
shell_v2::EXIT => return self.drain_acc_or_close(),
_ => self.head += frame_size,
}
}
}
}
fn drain_acc_or_close(&mut self) -> Result<LogEntry, Error<<T as ErrorType>::Error>> {
if let Some((entry, consumed)) =
parse_entry(&self.buf[..self.acc_end]).map_err(Error::Logcat)?
{
self.buf.copy_within(consumed..self.acc_end, 0);
self.acc_end -= consumed;
return Ok(entry);
}
Err(Error::ChannelClosed)
}
pub async fn close(self) -> Result<(), Error<<T as ErrorType>::Error>> {
self.channel.close().await
}
}
fn write_destination(buf: &mut [u8], prefix: &[u8], args: &[&str]) -> Option<usize> {
crate::base::destination::write_destination(buf, &[b"shell,v2,raw:", prefix], args)
}
async fn open_shell_channel<'a, T, const MC: usize, const MP: usize, const MF: usize>(
conn: &'a mut Connection<T, MC, MP, MF>,
prefix: &[u8],
args: &[&str],
buf: &mut [u8],
) -> Result<Channel<'a, T, MC, MP, MF>, Error<<T as ErrorType>::Error>>
where
T: Read + Write,
{
conn.require_feature(crate::base::protocol::features::Feature::ShellV2)?;
let dest_len = write_destination(buf, prefix, args).ok_or(Error::ReceiveBufferFull)?;
conn.open(&buf[..dest_len]).await
}
pub async fn open<'a, 'b, T, const MC: usize, const MP: usize, const MF: usize>(
conn: &'a mut Connection<T, MC, MP, MF>,
args: &[&str],
buf: &'b mut [u8],
) -> Result<Logcat<'a, 'b, T, MC, MP, MF>, Error<<T as ErrorType>::Error>>
where
T: Read + Write,
{
let channel = open_shell_channel(conn, b"logcat -B", args, buf).await?;
Ok(Logcat::new(channel, buf))
}
pub async fn dump<T, const MC: usize, const MP: usize, const MF: usize>(
conn: &mut Connection<T, MC, MP, MF>,
args: &[&str],
buf: &mut [u8],
) -> Result<Vec<LogEntry>, Error<<T as ErrorType>::Error>>
where
T: Read + Write,
{
let channel = open_shell_channel(conn, b"logcat -B -d", args, buf).await?;
let mut logcat = Logcat::new(channel, buf);
let mut entries = Vec::new();
loop {
match logcat.read_entry().await {
Ok(entry) => entries.push(entry),
Err(Error::ChannelClosed) => break,
Err(e) => return Err(e),
}
}
Ok(entries)
}
pub async fn open_text<'a, 'b, T, const MC: usize, const MP: usize, const MF: usize>(
conn: &'a mut Connection<T, MC, MP, MF>,
args: &[&str],
rx: &'b mut [u8],
) -> Result<Shell<'a, 'b, T, MC, MP, MF>, Error<<T as ErrorType>::Error>>
where
T: Read + Write,
{
let channel = open_shell_channel(conn, b"logcat", args, rx).await?;
Ok(Shell::new(channel, rx))
}
pub async fn exec_text<T, const MC: usize, const MP: usize, const MF: usize>(
conn: &mut Connection<T, MC, MP, MF>,
args: &[&str],
rx: &mut [u8],
) -> Result<CommandOutput, Error<<T as ErrorType>::Error>>
where
T: Read + Write,
{
let channel = open_shell_channel(conn, b"logcat", args, rx).await?;
let mut shell = Shell::new(channel, rx);
shell.close_stdin().await?;
shell.collect().await
}
mod format;
pub use format::*;
#[cfg(test)]
mod tests;