use alloc::vec::Vec;
use embedded_io::ErrorType;
use embedded_io_async::{Read, Write};
use crate::abb;
use crate::base::connection::Connection;
use crate::base::destination::{self, DestinationError};
use crate::base::error::Error;
use crate::base::protocol::features::Feature;
use crate::shell::v2::Shell;
fn write_shell_destination(buf: &mut [u8], args: &[&str]) -> Result<usize, DestinationError> {
destination::write_destination(buf, &[b"shell,v2,raw:cmd"], args)
}
fn has_feature<T, const MC: usize, const MP: usize, const MF: usize>(
conn: &Connection<T, MC, MP, MF>,
feature: &Feature,
) -> bool
where
T: Read + Write,
{
conn.device_banner_parsed()
.is_some_and(|b| b.has_feature(feature))
}
pub async fn exec<T, const MC: usize, const MP: usize, const MF: usize>(
conn: &mut Connection<T, MC, MP, MF>,
args: &[&str],
rx: &mut [u8],
) -> Result<Vec<u8>, Error<<T as ErrorType>::Error>>
where
T: Read + Write,
{
if has_feature(conn, &Feature::AbbExec) {
return abb::exec(conn, args, rx).await;
}
let dest_len = write_shell_destination(rx, args)?;
let channel = conn.open(&rx[..dest_len]).await?;
let shell = Shell::new(channel, rx);
let output = shell.collect().await?;
Ok(output.stdout)
}
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],
rx: &'b mut [u8],
) -> Result<Shell<'a, 'b, T, MC, MP, MF>, Error<<T as ErrorType>::Error>>
where
T: Read + Write,
{
if has_feature(conn, &Feature::Abb) {
return abb::open(conn, args, rx).await;
}
let dest_len = write_shell_destination(rx, args)?;
let channel = conn.open(&rx[..dest_len]).await?;
Ok(Shell::new(channel, rx))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shell_destination_multiple_args() {
let mut buf = [0u8; 128];
let len = write_shell_destination(&mut buf, &["package", "list", "packages"]).unwrap();
assert_eq!(&buf[..len], b"shell,v2,raw:cmd package list packages\0");
}
#[test]
fn shell_destination_single_arg() {
let mut buf = [0u8; 128];
let len = write_shell_destination(&mut buf, &["connectivity"]).unwrap();
assert_eq!(&buf[..len], b"shell,v2,raw:cmd connectivity\0");
}
#[test]
fn shell_destination_no_args() {
let mut buf = [0u8; 128];
let len = write_shell_destination(&mut buf, &[]).unwrap();
assert_eq!(&buf[..len], b"shell,v2,raw:cmd\0");
}
#[test]
fn shell_destination_buffer_too_small() {
let mut buf = [0u8; 10];
assert_eq!(
write_shell_destination(&mut buf, &["package"]),
Err(DestinationError::TooLong)
);
}
}