Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce stack usage #190

Merged
merged 24 commits into from
Dec 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 7 additions & 9 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -97,16 +97,14 @@ jobs:
[
"",
"derive",
"derive, log",
"derive, defmt",
"async",
"derive,async",
]
include:
- target: "x86_64-unknown-linux-gnu"
features: "derive"
std: ", std"
- target: "x86_64-unknown-linux-gnu"
features: "derive, log"
std: ", std"
extra_features: "std,log"
- target: "thumbv6m-none-eabi"
extra_features: "embedded,defmt"
steps:
- name: Checkout source code
uses: actions/checkout@v2
Expand All @@ -123,7 +121,7 @@ jobs:
uses: actions-rs/cargo@v1
with:
command: build
args: --all --target '${{ matrix.target }}' --features '${{ matrix.features }}${{ matrix.std }}'
args: --workspace --target '${{ matrix.target }}' --features '${{ matrix.features }},${{ matrix.extra_features }}'

test:
name: Test
Expand All @@ -142,4 +140,4 @@ jobs:
uses: actions-rs/cargo@v1
with:
command: test
args: --all --features std
args: --workspace --features std,heapless
3 changes: 3 additions & 0 deletions atat/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ defmt = { version = "^0.3", optional = true }
[dev-dependencies]
embassy-time = { version = "0.2", features = ["std", "generic-queue"] }
critical-section = { version = "1.1", features = ["std"] }
serde_at = { path = "../serde_at", version = "^0.20.0", features = [
"heapless",
] }
tokio = { version = "1", features = ["macros", "rt"] }

[features]
Expand Down
103 changes: 47 additions & 56 deletions atat/src/asynch/client.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use super::AtatClient;
use crate::{
helpers::LossyStr, response_channel::ResponseChannel, AtatCmd, Config, Error, Response,
helpers::LossyStr,
response_slot::{ResponseSlot, ResponseSlotGuard},
AtatCmd, Config, Error, Response,
};
use embassy_time::{Duration, Instant, TimeoutError, Timer};
use embedded_io_async::Write;
Expand All @@ -11,63 +13,58 @@ use futures::{

pub struct Client<'a, W: Write, const INGRESS_BUF_SIZE: usize> {
writer: W,
res_channel: &'a ResponseChannel<INGRESS_BUF_SIZE>,
res_slot: &'a ResponseSlot<INGRESS_BUF_SIZE>,
buf: &'a mut [u8],
config: Config,
cooldown_timer: Option<Timer>,
}

impl<'a, W: Write, const INGRESS_BUF_SIZE: usize> Client<'a, W, INGRESS_BUF_SIZE> {
pub fn new(
writer: W,
res_channel: &'a ResponseChannel<INGRESS_BUF_SIZE>,
res_slot: &'a ResponseSlot<INGRESS_BUF_SIZE>,
buf: &'a mut [u8],
config: Config,
) -> Self {
Self {
writer,
res_channel,
res_slot,
buf,
config,
cooldown_timer: None,
}
}

async fn send_command(&mut self, cmd: &[u8]) -> Result<(), Error> {
self.wait_cooldown_timer().await;

self.send_inner(cmd).await?;

self.start_cooldown_timer();
Ok(())
}
async fn send_request(&mut self, len: usize) -> Result<(), Error> {
if len < 50 {
debug!("Sending command: {:?}", LossyStr(&self.buf[..len]));
} else {
debug!("Sending command with long payload ({} bytes)", len);
}

async fn send_request(
&mut self,
cmd: &[u8],
timeout: Duration,
) -> Result<Response<INGRESS_BUF_SIZE>, Error> {
self.wait_cooldown_timer().await;

let mut response_subscription = self.res_channel.subscriber().unwrap();
self.send_inner(cmd).await?;
// Clear any pending response signal
self.res_slot.reset();

let response = self
.with_timeout(timeout, response_subscription.next_message_pure())
// Write request
self.writer
.write_all(&self.buf[..len])
.await
.map_err(|_| Error::Timeout);
.map_err(|_| Error::Write)?;
self.writer.flush().await.map_err(|_| Error::Write)?;

self.start_cooldown_timer();
response
Ok(())
}

async fn send_inner(&mut self, cmd: &[u8]) -> Result<(), Error> {
if cmd.len() < 50 {
debug!("Sending command: {:?}", LossyStr(cmd));
} else {
debug!("Sending command with long payload ({} bytes)", cmd.len(),);
}

self.writer.write_all(cmd).await.map_err(|_| Error::Write)?;
self.writer.flush().await.map_err(|_| Error::Write)?;
Ok(())
async fn wait_response<'guard>(
&'guard mut self,
timeout: Duration,
) -> Result<ResponseSlotGuard<'guard, INGRESS_BUF_SIZE>, Error> {
self.with_timeout(timeout, self.res_slot.get())
.await
.map_err(|_| Error::Timeout)
}

async fn with_timeout<F: Future>(
Expand Down Expand Up @@ -107,20 +104,17 @@ impl<'a, W: Write, const INGRESS_BUF_SIZE: usize> Client<'a, W, INGRESS_BUF_SIZE
}

impl<W: Write, const INGRESS_BUF_SIZE: usize> AtatClient for Client<'_, W, INGRESS_BUF_SIZE> {
async fn send<Cmd: AtatCmd<LEN>, const LEN: usize>(
&mut self,
cmd: &Cmd,
) -> Result<Cmd::Response, Error> {
let cmd_vec = cmd.as_bytes();
let cmd_slice = cmd.get_slice(&cmd_vec);
async fn send<Cmd: AtatCmd>(&mut self, cmd: &Cmd) -> Result<Cmd::Response, Error> {
let len = cmd.write(&mut self.buf);
self.send_request(len).await?;
if !Cmd::EXPECTS_RESPONSE_CODE {
self.send_command(cmd_slice).await?;
cmd.parse(Ok(&[]))
} else {
let response = self
.send_request(cmd_slice, Duration::from_millis(Cmd::MAX_TIMEOUT_MS.into()))
.wait_response(Duration::from_millis(Cmd::MAX_TIMEOUT_MS.into()))
.await?;
cmd.parse((&response).into())
let response: &Response<INGRESS_BUF_SIZE> = &response.borrow();
cmd.parse(response.into())
}
}
}
Expand All @@ -130,7 +124,7 @@ mod tests {
use super::*;
use crate as atat;
use crate::atat_derive::{AtatCmd, AtatEnum, AtatResp};
use crate::{Error, Response};
use crate::Error;
use core::sync::atomic::{AtomicU64, Ordering};
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::pubsub::PubSubChannel;
Expand Down Expand Up @@ -178,16 +172,13 @@ mod tests {
($config:expr) => {{
static TX_CHANNEL: PubSubChannel<CriticalSectionRawMutex, String<64>, 1, 1, 1> =
PubSubChannel::new();
static RES_CHANNEL: ResponseChannel<TEST_RX_BUF_LEN> = ResponseChannel::new();
static RES_SLOT: ResponseSlot<TEST_RX_BUF_LEN> = ResponseSlot::new();
static mut BUF: [u8; 1000] = [0; 1000];

let tx_mock = crate::tx_mock::TxMock::new(TX_CHANNEL.publisher().unwrap());
let client: Client<crate::tx_mock::TxMock, TEST_RX_BUF_LEN> =
Client::new(tx_mock, &RES_CHANNEL, $config);
(
client,
TX_CHANNEL.subscriber().unwrap(),
RES_CHANNEL.publisher().unwrap(),
)
Client::new(tx_mock, &RES_SLOT, unsafe { BUF.as_mut() }, $config);
(client, TX_CHANNEL.subscriber().unwrap(), &RES_SLOT)
}};
}

Expand All @@ -206,7 +197,7 @@ mod tests {
sent + Duration::from_millis(100)
}

let (mut client, mut tx, _rx) =
let (mut client, mut tx, _slot) =
setup!(Config::new().get_response_timeout(custom_response_timeout));

let cmd = SetModuleFunctionality {
Expand All @@ -219,7 +210,7 @@ mod tests {
// Do not emit a response effectively causing a timeout
});

let send = tokio::task::spawn(async move {
let send = tokio::spawn(async move {
assert_eq!(Err(Error::Timeout), client.send(&cmd).await);
});

Expand Down Expand Up @@ -248,11 +239,11 @@ mod tests {
sent + Duration::from_millis(200)
} else {
// Extended timeout
sent + Duration::from_millis(500)
sent + Duration::from_millis(50000)
}
}

let (mut client, mut tx, rx) =
let (mut client, mut tx, slot) =
setup!(Config::new().get_response_timeout(custom_response_timeout));

let cmd = SetModuleFunctionality {
Expand All @@ -264,10 +255,10 @@ mod tests {
tx.next_message_pure().await;
// Emit response in the extended timeout timeframe
Timer::after(Duration::from_millis(300)).await;
rx.try_publish(Response::default()).unwrap();
slot.signal_response(Ok(&[])).unwrap();
});

let send = tokio::task::spawn(async move {
let send = tokio::spawn(async move {
assert_eq!(Ok(NoResponse), client.send(&cmd).await);
});

Expand Down
10 changes: 2 additions & 8 deletions atat/src/asynch/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,9 @@ pub trait AtatClient {
/// This function will also make sure that at least `self.config.cmd_cooldown`
/// has passed since the last response or URC has been received, to allow
/// the slave AT device time to deliver URC's.
async fn send<Cmd: AtatCmd<LEN>, const LEN: usize>(
&mut self,
cmd: &Cmd,
) -> Result<Cmd::Response, Error>;
async fn send<Cmd: AtatCmd>(&mut self, cmd: &Cmd) -> Result<Cmd::Response, Error>;

async fn send_retry<Cmd: AtatCmd<LEN>, const LEN: usize>(
&mut self,
cmd: &Cmd,
) -> Result<Cmd::Response, Error> {
async fn send_retry<Cmd: AtatCmd>(&mut self, cmd: &Cmd) -> Result<Cmd::Response, Error> {
for attempt in 1..=Cmd::ATTEMPTS {
if attempt > 1 {
debug!("Attempt {}:", attempt);
Expand Down
Loading
Loading