at_parser_rs/lib.rs
1/***************************************************************************
2 *
3 * AT Command Parser
4 * Copyright (C) 2026 Antonio Salsi <passy.linux@zresa.it>
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <https://www.gnu.org/licenses/>.
18 *
19 ***************************************************************************/
20
21//! AT Command Parser Library
22//!
23//! This library provides a flexible parser for AT commands, commonly used in
24//! embedded systems and communication devices. It supports `no_std` environments.
25//!
26//! # Architecture
27//!
28//! The library is built around three core components:
29//!
30//! - **[`AtParser`](parser::AtParser)** - The main parser that processes AT command strings
31//! - **[`AtContext`](context::AtContext)** - Trait for implementing command handlers
32//! - **[`Args`]** - Structure for accessing command arguments
33//!
34//! # Command Forms
35//!
36//! Supports all standard AT command forms:
37//! - `AT+CMD` - Execute (action without parameters)
38//! - `AT+CMD?` - Query (get current value/state)
39//! - `AT+CMD=?` - Test (get supported values/ranges)
40//! - `AT+CMD=<args>` - Set (configure with parameters)
41//!
42//! # Quick Start
43//!
44//! ```rust,no_run
45//! use at_parser_rs::context::AtContext;
46//! use at_parser_rs::parser::AtParser;
47//! use at_parser_rs::{Args, AtResult, AtError, Bytes};
48//!
49//! const SIZE: usize = 64;
50//!
51//! // 1. Define a command handler
52//! struct EchoModule { echo: bool }
53//!
54//! impl AtContext<SIZE> for EchoModule {
55//! fn query(&mut self) -> AtResult<SIZE> {
56//! if self.echo { Ok(Bytes::from_str("1")) } else { Ok(Bytes::from_str("0")) }
57//! }
58//!
59//! fn set(&mut self, args: Args) -> AtResult<SIZE> {
60//! match args.get(0) {
61//! Some("0") => { self.echo = false; Ok(Bytes::from_str("OK")) }
62//! Some("1") => { self.echo = true; Ok(Bytes::from_str("OK")) }
63//! _ => Err(AtError::InvalidArgs),
64//! }
65//! }
66//! }
67//!
68//! // 2. Create parser and register commands
69//! let mut echo = EchoModule { echo: false };
70//! let mut parser: AtParser<EchoModule, SIZE> = AtParser::new();
71//!
72//! let commands: &mut [(&str, &mut dyn AtContext<SIZE>)] = &mut [
73//! ("AT+ECHO", &mut echo),
74//! ];
75//! parser.set_commands(commands);
76//!
77//! // 3. Execute commands
78//! parser.execute("AT+ECHO=1"); // Set echo on
79//! parser.execute("AT+ECHO?"); // Query current state
80//! ```
81//!
82//! # Features
83//!
84//! - **`freertos`** (default) - Enable FreeRTOS support via osal-rs
85//! - **`posix`** - Enable POSIX support via osal-rs
86//! - **`std`** - Enable standard library support via osal-rs
87//! - **`disable_panic`** - Pass-through feature to osal-rs for panic handling
88//!
89//! # Thread Safety
90//!
91//! The library can be used in single-threaded (bare-metal) or multi-threaded (RTOS)
92//! environments. For RTOS, use appropriate synchronization primitives around
93//! command handlers (e.g., `Mutex<RefCell<Handler>>`).
94
95#![no_std]
96
97extern crate alloc;
98extern crate osal_rs;
99
100use core::iter::Iterator;
101use core::option::Option;
102use core::result::Result;
103
104use alloc::string::String;
105use osal_rs::utils::Bytes;
106
107pub mod context;
108pub mod parser;
109
110
111/// Error types that can occur during AT command processing
112#[derive(Debug)]
113pub enum AtError<'a> {
114 /// The command is not recognized
115 UnknownCommand,
116 /// The command is recognized but not supported
117 NotSupported,
118 /// The command arguments are invalid
119 InvalidArgs,
120 /// Unhandled error with description
121 Unhandled(&'a str),
122 /// Unhandled error with description owned
123 UnhandledOwned(String)
124}
125
126/// Result type for AT command operations
127/// Returns either a `Bytes<SIZE>` response buffer or an `AtError`
128pub type AtResult<'a, const SIZE: usize> = Result<Bytes<SIZE>, AtError<'a>>;
129
130/// Structure holding the arguments passed to an AT command
131pub struct Args<'a> {
132 /// Raw argument string (comma-separated values)
133 pub raw: &'a str,
134}
135
136impl<'a> Args<'a> {
137 /// Get an argument by index (0-based)
138 /// Arguments are separated by commas
139 pub fn get(&self, index: usize) -> Option<&'a str> {
140 self.raw.split(',').nth(index)
141 }
142}
143
144
145/// Macro to define AT command modules
146///
147/// Creates a static array of command names and their associated context handlers.
148///
149/// # Warning
150///
151/// This macro uses `unsafe` to create mutable references to static data.
152/// It is only suitable for single-threaded embedded contexts.
153///
154/// # Limitations
155///
156/// - **Unsafe**: Requires `unsafe` blocks to use
157/// - **Single-threaded only**: Not safe for RTOS or multi-threaded environments
158/// - **Limited flexibility**: Cannot mix different handler types
159///
160/// # Example
161///
162/// ```rust,no_run
163/// use at_parser_rs::at_modules;
164/// use at_parser_rs::context::AtContext;
165///
166/// const SIZE: usize = 64;
167///
168/// static mut ECHO: EchoModule = EchoModule { echo: false };
169/// static mut RESET: ResetModule = ResetModule;
170///
171/// at_modules! {
172/// SIZE;
173/// "AT+ECHO" => ECHO,
174/// "AT+RST" => RESET,
175/// }
176/// ```
177///
178/// # Recommended Alternative
179///
180/// For most use cases, prefer the manual approach:
181///
182/// ```rust,no_run
183/// const SIZE: usize = 64;
184/// let commands: &mut [(&str, &mut dyn AtContext<SIZE>)] = &mut [
185/// ("AT+ECHO", &mut echo_handler),
186/// ("AT+RST", &mut reset_handler),
187/// ];
188/// parser.set_commands(commands);
189/// ```
190/// Macro to format an AT response with 1–6 comma-separated parameters.
191///
192/// # Syntax
193///
194/// ```rust,ignore
195/// at_response!(SIZE, AT_RESP; arg1, arg2, ..., arg6)
196/// ```
197///
198/// - `SIZE` — const usize for the response buffer capacity
199/// - `AT_RESP` — the AT response prefix string
200/// - `arg1..arg6` — values to append, comma-separated
201#[macro_export]
202macro_rules! at_response {
203 ($size:expr, $at_resp:expr; $a1:expr) => {{
204 let mut response = osal_rs::utils::Bytes::<{$size}>::new();
205 response.format(format_args!("{}{}", $at_resp, $a1));
206 response
207 }};
208 ($size:expr, $at_resp:expr; $a1:expr, $a2:expr) => {{
209 let mut response = osal_rs::utils::Bytes::<{$size}>::new();
210 response.format(format_args!("{}{},{}", $at_resp, $a1, $a2));
211 response
212 }};
213 ($size:expr, $at_resp:expr; $a1:expr, $a2:expr, $a3:expr) => {{
214 let mut response = osal_rs::utils::Bytes::<{$size}>::new();
215 response.format(format_args!("{}{},{},{}", $at_resp, $a1, $a2, $a3));
216 response
217 }};
218 ($size:expr, $at_resp:expr; $a1:expr, $a2:expr, $a3:expr, $a4:expr) => {{
219 let mut response = osal_rs::utils::Bytes::<{$size}>::new();
220 response.format(format_args!("{}{},{},{},{}", $at_resp, $a1, $a2, $a3, $a4));
221 response
222 }};
223 ($size:expr, $at_resp:expr; $a1:expr, $a2:expr, $a3:expr, $a4:expr, $a5:expr) => {{
224 let mut response = osal_rs::utils::Bytes::<{$size}>::new();
225 response.format(format_args!("{}{},{},{},{},{}", $at_resp, $a1, $a2, $a3, $a4, $a5));
226 response
227 }};
228 ($size:expr, $at_resp:expr; $a1:expr, $a2:expr, $a3:expr, $a4:expr, $a5:expr, $a6:expr) => {{
229 let mut response = osal_rs::utils::Bytes::<{$size}>::new();
230 response.format(format_args!("{}{},{},{},{},{},{}", $at_resp, $a1, $a2, $a3, $a4, $a5, $a6));
231 response
232 }};
233}
234
235#[macro_export]
236macro_rules! at_modules {
237 (
238 $size:expr;
239 $( $name:expr => $module:ident ),* $(,)?
240 ) => {
241 static COMMANDS: &[(&'static str, &mut dyn AtContext<$size>)] = unsafe {
242 &[
243 $(
244 ($name, &mut $module),
245 )*
246 ]
247 };
248 };
249}