basic_parser/
basic_parser.rs

1//! Example using the AtParser with proper type handling
2
3use at_parser_rs::context::AtContext;
4use at_parser_rs::parser::AtParser;
5use at_parser_rs::{Args, AtError, AtResult};
6
7/// Simple command module for testing
8pub struct TestCommand {
9    pub value: u32,
10}
11
12impl AtContext for TestCommand {
13    fn exec(&self) -> AtResult<'static> {
14        Ok("Test command executed")
15    }
16
17    fn query(&mut self) -> AtResult<'static> {
18        // In a real scenario, you would format the value dynamically
19        // For this example, we use static strings
20        if self.value == 0 {
21            Ok("0")
22        } else if self.value < 10 {
23            Ok("1-9")
24        } else {
25            Ok("10+")
26        }
27    }
28
29    fn test(&mut self) -> AtResult<'static> {
30        Ok("Test: 0-100")
31    }
32
33    fn set(&mut self, args: Args) -> AtResult<'static> {
34        let val_str = args.get(0).ok_or(AtError::InvalidArgs)?;
35        self.value = val_str.parse().map_err(|_| AtError::InvalidArgs)?;
36        Ok("OK")
37    }
38}
39
40fn main() {
41    println!("=== AtParser Example ===\n");
42
43    // Create command instances
44    let mut cmd1 = TestCommand { value: 0 };
45    let mut cmd2 = TestCommand { value: 5 };
46    let mut cmd3 = TestCommand { value: 10 };
47
48    // Create parser instance
49    let mut parser = AtParser::new();
50    
51    // Register commands
52    let commands: &mut [(&str, &mut TestCommand)] = &mut [
53        ("AT+CMD1", &mut cmd1),
54        ("AT+CMD2", &mut cmd2),
55        ("AT+CMD3", &mut cmd3),
56    ];
57
58    parser.set_commands(commands);
59
60    println!("Registered commands: AT+CMD1, AT+CMD2, AT+CMD3\n");
61
62    // Test cases
63    let test_cases = vec![
64        ("AT+CMD1", "Execute CMD1"),
65        ("AT+CMD1?", "Query CMD1 value"),
66        ("AT+CMD1=?", "Test CMD1"),
67        ("AT+CMD1=42", "Set CMD1 to 42"),
68        ("AT+CMD1?", "Query CMD1 after set"),
69        ("AT+CMD2", "Execute CMD2"),
70        ("AT+CMD2?", "Query CMD2 value"),
71        ("AT+CMD3=100", "Set CMD3 to 100"),
72        ("AT+CMD3?", "Query CMD3"),
73        ("AT+UNKNOWN", "Unknown command error"),
74        ("AT+CMD1=abc", "Invalid argument error"),
75    ];
76
77    for (cmd, description) in test_cases {
78        println!("Test: {}", description);
79        println!("  Command: {}", cmd);
80        match parser.execute(cmd) {
81            Ok(response) => println!("  Response: {}", response),
82            Err(AtError::UnknownCommand) => println!("  Error: Unknown command"),
83            Err(AtError::NotSupported) => println!("  Error: Not supported"),
84            Err(AtError::InvalidArgs) => println!("  Error: Invalid arguments"),
85        }
86        println!();
87    }
88
89    println!("=== Example completed ===");
90}