embedded_error_handling/
embedded_error_handling.rs1#![allow(dead_code)]
27#![no_std]
28#![no_main]
29
30extern crate at_parser_rs;
31
32use at_parser_rs::context::AtContext;
33use at_parser_rs::parser::AtParser;
34use at_parser_rs::{Args, AtError, AtResult, at_response};
35
36const SIZE: usize = 64;
37
38struct DiagModule {
40 armed: bool,
41}
42
43impl AtContext<SIZE> for DiagModule {
44 fn exec(&mut self, at_response: &'static str) -> AtResult<'_, SIZE> {
45 if self.armed {
46 Ok(at_response!(SIZE, at_response; "TRIGGERED"))
47 } else {
48 Err((at_response, AtError::Unhandled("not armed")))
49 }
50 }
51
52 fn query(&mut self, at_response: &'static str) -> AtResult<'_, SIZE> {
53 Ok(at_response!(SIZE, at_response; if self.armed { 1u8 } else { 0u8 }))
54 }
55
56 fn test(&mut self, at_response: &'static str) -> AtResult<'_, SIZE> {
57 Ok(at_response!(SIZE, at_response; "(0,1)"))
58 }
59
60 fn set(&mut self, at_response: &'static str, args: Args) -> AtResult<'_, SIZE> {
61 let val = args.get(0).ok_or((at_response, AtError::InvalidArgs))?;
62 match val.as_ref() {
63 "0" => { self.armed = false; Ok(at_response!(SIZE, at_response; "OK")) }
64 "1" => { self.armed = true; Ok(at_response!(SIZE, at_response; "OK")) }
65 _ => Err((at_response, AtError::InvalidArgs)),
66 }
67 }
68}
69
70fn check_result(result: AtResult<SIZE>) -> u8 {
72 match result {
73 Ok((_, _)) => 0, Err((_, AtError::InvalidArgs)) => 1,
75 Err((_, AtError::NotSupported)) => 2,
76 Err((_, AtError::UnknownCommand)) => 3,
77 Err((_, AtError::Unhandled(_))) => 4,
78 Err((_, AtError::UnhandledOwned(_))) => 5,
79 }
80}
81
82#[unsafe(no_mangle)]
83pub extern "C" fn main() -> ! {
84 let mut diag = DiagModule { armed: false };
85
86 let mut parser: AtParser<DiagModule, SIZE> = AtParser::new();
87 let commands: &mut [(&str, &str, &mut DiagModule)] = &mut [
88 ("AT+DIAG", "+DIAG: ", &mut diag),
89 ];
90 parser.set_commands(commands);
91
92 let _s = check_result(parser.execute("AT+DIAG")); let _s = check_result(parser.execute("AT+DIAG=1")); let _s = check_result(parser.execute("AT+DIAG")); let _s = check_result(parser.execute("AT+DIAG?")); let _s = check_result(parser.execute("AT+DIAG=2")); let _s = check_result(parser.execute("AT+UNKNOWN")); loop {}
111}
112