aboutsummaryrefslogtreecommitdiff
path: root/embassy-net-nrf91/src/context.rs
blob: 9c67cbc9f639ca6f5adb011b8a5d804c8cb97b84 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
//! Helper utility to configure a specific modem context.
use core::net::IpAddr;
use core::str::FromStr;
use heapless::Vec;
use at_commands::{builder::CommandBuilder, parser::CommandParser};

/// Provides a higher level API for controlling a given context.
pub struct Control<'a> {
    control: crate::Control<'a>,
    cid: u8,
}

/// Configuration for a given context
pub struct Config<'a> {
    /// Desired APN address.
    pub apn: &'a str,
    /// Desired authentication protocol.
    pub auth_prot: AuthProt,
    /// Credentials.
    pub auth: Option<(&'a str, &'a str)>,
}

/// Authentication protocol.
#[repr(u8)]
pub enum AuthProt {
    /// No authentication.
    None = 0,
    /// PAP authentication.
    Pap = 1,
    /// CHAP authentication.
    Chap = 2,
}

/// Error returned by control.
#[derive(Clone, Copy, PartialEq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error {
    /// Not enough space for command.
    BufferTooSmall,
    /// Error parsing response from modem.
    AtParseError,
    /// Error parsing IP addresses.
    AddrParseError,
}

impl From<at_commands::parser::ParseError> for Error {
    fn from(_: at_commands::parser::ParseError) -> Self {
        Self::AtParseError
    }
}

/// Status of a given context.
#[derive(PartialEq, Debug)]
pub struct Status {
    /// Attached to APN or not.
    pub attached: bool,
    /// IP if assigned.
    pub ip: Option<IpAddr>,
    /// Gateway if assigned.
    pub gateway: Option<IpAddr>,
    /// DNS servers if assigned.
    pub dns: Vec<IpAddr, 2>,
}

#[cfg(feature = "defmt")]
impl defmt::Format for Status {
    fn format(&self, f: defmt::Formatter<'_>) {
        defmt::write!(f, "attached: {}", self.attached);
        if let Some(ip) = &self.ip {
            defmt::write!(f, ", ip: {}", defmt::Debug2Format(&ip));
        }
    }
}

impl<'a> Control<'a> {
    /// Create a new instance of a control handle for a given context.
    ///
    /// Will wait for the modem to be initialized if not.
    pub async fn new(control: crate::Control<'a>, cid: u8) -> Self {
        control.wait_init().await;
        Self { control, cid }
    }

    /// Configures the modem with the provided config.
    pub async fn configure(&self, config: Config<'_>) -> Result<(), Error> {
        let mut cmd: [u8; 256] = [0; 256];
        let mut buf: [u8; 256] = [0; 256];

        let op = CommandBuilder::create_set(&mut cmd, true)
            .named("+CGDCONT")
            .with_int_parameter(self.cid)
            .with_string_parameter("IP")
            .with_string_parameter(config.apn)
            .finish().map_err(|_| Error::BufferTooSmall)?;
        let n = self.control.at_command(op, &mut buf).await;
        CommandParser::parse(&buf[..n]).expect_identifier(b"OK").finish()?;

        let mut op = CommandBuilder::create_set(&mut cmd, true)
            .named("+CGAUTH")
            .with_int_parameter(self.cid)
            .with_int_parameter(config.auth_prot as u8);
        if let Some((username, password)) = config.auth {
            op = op.with_string_parameter(username).with_string_parameter(password);
        }
        let op = op.finish().map_err(|_| Error::BufferTooSmall)?;

        let n = self.control.at_command(op, &mut buf).await;
        CommandParser::parse(&buf[..n]).expect_identifier(b"OK").finish()?;

        let op = CommandBuilder::create_set(&mut cmd, true)
            .named("+CFUN")
            .with_int_parameter(1)
            .finish().map_err(|_| Error::BufferTooSmall)?;
        let n = self.control.at_command(op, &mut buf).await;
        CommandParser::parse(&buf[..n]).expect_identifier(b"OK").finish()?;

        Ok(())
    }

    /// Read current connectivity status for modem.
    pub async fn status(&self) -> Result<Status, Error> {
        let mut cmd: [u8; 256] = [0; 256];
        let mut buf: [u8; 256] = [0; 256];

        let op = CommandBuilder::create_query(&mut cmd, true)
            .named("+CGATT")
            .finish().map_err(|_| Error::BufferTooSmall)?;
        let n = self.control.at_command(op, &mut buf).await;
        let (res, ) = CommandParser::parse(&buf[..n])
            .expect_identifier(b"+CGATT: ")
            .expect_int_parameter()
            .expect_identifier(b"\r\nOK").finish()?;
        let attached = res == 1;
        if !attached {
            return Ok(Status { attached, ip: None, gateway: None, dns: Vec::new() })
        }

        let op = CommandBuilder::create_set(&mut cmd, true)
            .named("+CGPADDR")
            .with_int_parameter(self.cid)
            .finish().map_err(|_| Error::BufferTooSmall)?;
        let n = self.control.at_command(op, &mut buf).await;
        let (_, ip1, _ip2, ) = CommandParser::parse(&buf[..n])
            .expect_identifier(b"+CGPADDR: ")
            .expect_int_parameter()
            .expect_optional_string_parameter()
            .expect_optional_string_parameter()
            .expect_identifier(b"\r\nOK").finish()?;

        let ip = if let Some(ip) = ip1 {
            let ip = IpAddr::from_str(ip).map_err(|_| Error::AddrParseError)?;
            self.control.open_raw_socket().await;
            Some(ip)
        } else {
            None
        };

        let op = CommandBuilder::create_set(&mut cmd, true)
            .named("+CGCONTRDP")
            .with_int_parameter(self.cid)
            .finish().map_err(|_| Error::BufferTooSmall)?;
        let n = self.control.at_command(op, &mut buf).await;
        let (_cid, _bid, _apn, _mask, gateway, dns1, dns2, _, _, _, _, _mtu) = CommandParser::parse(&buf[..n])
            .expect_identifier(b"+CGCONTRDP: ")
            .expect_int_parameter()
            .expect_optional_int_parameter()
            .expect_optional_string_parameter()
            .expect_optional_string_parameter()
            .expect_optional_string_parameter()
            .expect_optional_string_parameter()
            .expect_optional_string_parameter()
            .expect_optional_int_parameter()
            .expect_optional_int_parameter()
            .expect_optional_int_parameter()
            .expect_optional_int_parameter()
            .expect_optional_int_parameter()
            .expect_identifier(b"\r\nOK").finish()?;

        let gateway = if let Some(ip) = gateway {
            if ip.is_empty() {
                None
            } else {
                Some(IpAddr::from_str(ip).map_err(|_| Error::AddrParseError)?)
            }
        } else {
            None
        };

        let mut dns = Vec::new();
        if let Some(ip) = dns1 {
            dns.push(IpAddr::from_str(ip).map_err(|_| Error::AddrParseError)?).unwrap();
        }

        if let Some(ip) = dns2 {
            dns.push(IpAddr::from_str(ip).map_err(|_| Error::AddrParseError)?).unwrap();
        }

        Ok(Status {
            attached,
            ip,
            gateway,
            dns,
        })
    }
}