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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
#![no_std]
//!A network driver for a RAK811 attached via a UART.
//!
//!Currently requires the RAK811 to be flashed with a 2.x version of the AT firmware.
//!
//!At first, the UART must be configured and handed to the driver. The uart must implement the `embedded_hal::serial` traits.
//!
//!## Usage
//!
//!```rust
//!let (uarte_tx, uarte_rx) = uarte
//!    .split(ctx.resources.tx_buf, ctx.resources.rx_buf)
//!    .unwrap();
//!
//!
//!let driver = rak811::Rak811Driver::new(
//!    uarte_tx,
//!    uarte_rx,
//!    port1.p1_02.into_push_pull_output(Level::High).degrade(),
//!)
//!.unwrap();
//!```
//!
//!In order to connect to the gateway, the LoRa node needs to be configured with the following:
//!
//!* Frequency band - This depends on where you live.
//!* Mode of operation - This can either be LoRa P2P which allows the node to send and receive data directly from another LoRa node, or LoRaWAN which connects the node to a gateway.
//!
//!The driver can be used to configure the properties in this way:
//!
//!```rust
//!driver.set_band(rak811::LoraRegion::EU868).unwrap();
//!driver.set_mode(rak811::LoraMode::WAN).unwrap();
//!```
//!
//!In addition, the following settings from the TTN console must be set:
//!
//!* Device EUI
//!* Application EUI
//!* Application Key
//!
//!```rust
//!driver.set_device_eui(&[0x00, 0xBB, 0x7C, 0x95, 0xAD, 0xB5, 0x30, 0xB9]).unwrap();
//!driver.set_app_eui(&[0x70, 0xB3, 0xD5, 0x7E, 0xD0, 0x03, 0xB1, 0x84])
//!
//!// Secret generated by network provider
//!driver .set_app_key(&[0x00]).unwrap();
//!```
//!
//!To join the network and send packets:
//!
//!```rust
//!driver.join(rak811::ConnectMode::OTAA).unwrap();
//!
//!// Port number can be between 1 and 255
//!driver.send(rak811::QoS::Confirmed, 1, b"hello!").unwrap();
//!```

use embedded_hal::digital::v2::OutputPin;
use embedded_hal::{serial::Read, serial::Write};
mod buffer;
mod error;
mod parser;
mod protocol;

use buffer::*;
pub use error::*;
use heapless::consts;
use heapless::spsc::Queue;
pub use protocol::*;

const RECV_BUFFER_LEN: usize = 256;

pub struct Rak811Driver<W, R, RST>
where
    W: Write<u8>,
    R: Read<u8>,
    RST: OutputPin,
{
    tx: W,
    rx: R,
    parse_buffer: Buffer,
    rxq: Queue<Response, consts::U4>,
    connect_mode: ConnectMode,
    lora_mode: LoraMode,
    lora_band: LoraRegion,
    rst: RST,
}

impl<W, R, RST> Rak811Driver<W, R, RST>
where
    W: Write<u8>,
    R: Read<u8>,
    RST: OutputPin,
{
    /// Create a new instance of the driver. The driver will trigger a reset of the module
    /// and expect a response from the firmware.
    pub fn new(tx: W, rx: R, rst: RST) -> Result<Rak811Driver<W, R, RST>, DriverError> {
        let mut driver = Rak811Driver {
            tx,
            rx,
            rst,
            parse_buffer: Buffer::new(),
            connect_mode: ConnectMode::OTAA,
            lora_mode: LoraMode::WAN,
            lora_band: LoraRegion::EU868,
            rxq: Queue::new(),
        };

        driver.initialize()?;
        Ok(driver)
    }

    /// Initialize the driver. This will cause the RAK811 module to be reset.
    pub fn initialize(&mut self) -> Result<(), DriverError> {
        self.rst.set_high().ok();
        self.rst.set_low().ok();
        let response = self.recv_response()?;
        match response {
            Response::Initialized => Ok(()),
            _ => Err(DriverError::NotInitialized),
        }
    }

    /// Send reset command to lora module. Depending on the mode, this will restart
    /// the module or reload its configuration from EEPROM.
    pub fn reset(&mut self, mode: ResetMode) -> Result<(), DriverError> {
        let response = self.send_command(Command::Reset(mode))?;
        match response {
            Response::Ok => {
                let response = self.recv_response()?;
                match response {
                    Response::Initialized => Ok(()),
                    _ => Err(DriverError::NotInitialized),
                }
            }
            r => Err(DriverError::UnexpectedResponse(r)),
        }
    }

    /// Join a LoRa Network using the specified mode.
    pub fn join(&mut self, mode: ConnectMode) -> Result<(), DriverError> {
        self.connect_mode = mode;
        let response = self.send_command(Command::Join(mode))?;
        match response {
            Response::Ok => {
                let response = self.recv_response()?;
                match response {
                    Response::Recv(EventCode::JoinedSuccess, _, _, _) => Ok(()),
                    r => Err(DriverError::UnexpectedResponse(r)),
                }
            }
            r => Err(DriverError::UnexpectedResponse(r)),
        }
    }

    /// Set the frequency band based on the region.
    pub fn set_band(&mut self, band: LoraRegion) -> Result<(), DriverError> {
        self.lora_band = band;
        let response = self.send_command(Command::SetBand(band))?;
        match response {
            Response::Ok => Ok(()),
            r => Err(DriverError::UnexpectedResponse(r)),
        }
    }

    /// Set the mode of operation, peer to peer or network mode.
    pub fn set_mode(&mut self, mode: LoraMode) -> Result<(), DriverError> {
        self.lora_mode = mode;
        let response = self.send_command(Command::SetMode(mode))?;
        match response {
            Response::Ok => Ok(()),
            r => Err(DriverError::UnexpectedResponse(r)),
        }
    }

    pub fn set_device_address(&mut self, addr: &DevAddr) -> Result<(), DriverError> {
        let response = self.send_command(Command::SetConfig(ConfigOption::DevAddr(addr)))?;
        match response {
            Response::Ok => Ok(()),
            r => Err(DriverError::UnexpectedResponse(r)),
        }
    }
    pub fn set_device_eui(&mut self, eui: &EUI) -> Result<(), DriverError> {
        let response = self.send_command(Command::SetConfig(ConfigOption::DevEui(eui)))?;
        match response {
            Response::Ok => Ok(()),
            r => Err(DriverError::UnexpectedResponse(r)),
        }
    }
    pub fn set_app_eui(&mut self, eui: &EUI) -> Result<(), DriverError> {
        let response = self.send_command(Command::SetConfig(ConfigOption::AppEui(eui)))?;
        match response {
            Response::Ok => Ok(()),
            r => Err(DriverError::UnexpectedResponse(r)),
        }
    }

    pub fn set_app_key(&mut self, key: &AppKey) -> Result<(), DriverError> {
        let response = self.send_command(Command::SetConfig(ConfigOption::AppKey(key)))?;
        match response {
            Response::Ok => Ok(()),
            r => Err(DriverError::UnexpectedResponse(r)),
        }
    }

    /// Transmit data using the specified confirmation mode and given port.
    pub fn send(&mut self, qos: QoS, port: Port, data: &[u8]) -> Result<(), DriverError> {
        let response = self.send_command(Command::Send(qos, port, data))?;
        match response {
            Response::Ok => {
                let response = self.recv_response()?;
                let expected_code = match qos {
                    QoS::Unconfirmed => EventCode::TxUnconfirmed,
                    QoS::Confirmed => EventCode::TxConfirmed,
                };
                match response {
                    Response::Recv(c, 0, _, _) if expected_code == c => Ok(()),
                    r => Err(DriverError::UnexpectedResponse(r)),
                }
            }
            r => Err(DriverError::UnexpectedResponse(r)),
        }
    }

    /// Poll for any received data and copy it to the provided buffer. If data have been received,
    /// the length of the data is returned.
    pub fn try_recv(&mut self, port: Port, rx_buf: &mut [u8]) -> Result<usize, DriverError> {
        self.digest()?;
        let mut tries = self.rxq.len();
        while tries > 0 {
            match self.rxq.dequeue() {
                None => return Ok(0),
                Some(Response::Recv(EventCode::RecvData, p, len, Some(data))) if p == port => {
                    if len > rx_buf.len() {
                        self.rxq
                            .enqueue(Response::Recv(EventCode::RecvData, p, len, Some(data)))
                            .map_err(|_| DriverError::ReadError)?;
                    }

                    rx_buf[0..len].clone_from_slice(&data);
                    return Ok(len);
                }
                Some(event) => {
                    self.rxq
                        .enqueue(event)
                        .map_err(|_| DriverError::ReadError)?;
                }
            }
            tries -= 1;
        }
        Ok(0)
    }

    /// Attempt to read data from UART and store it in the parse buffer. This should
    /// be invoked whenever data should be read.
    pub fn process(&mut self) -> Result<(), DriverError> {
        loop {
            match self.rx.read() {
                Err(nb::Error::WouldBlock) => {
                    break;
                }
                Err(nb::Error::Other(_)) => return Err(DriverError::ReadError),
                Ok(b) => {
                    self.parse_buffer
                        .write(b)
                        .map_err(|_| DriverError::ReadError)?;
                }
            }
        }
        Ok(())
    }

    /// Attempt to parse the internal buffer and enqueue any response data found.
    pub fn digest(&mut self) -> Result<(), DriverError> {
        let result = self.parse_buffer.parse();
        if let Ok(response) = result {
            if !matches!(response, Response::None) {
                log::debug!("Got response: {:?}", response);
                self.rxq
                    .enqueue(response)
                    .map_err(|_| DriverError::ReadError)?;
            }
        }
        Ok(())
    }

    // Block until a response is received.
    fn recv_response(&mut self) -> Result<Response, DriverError> {
        loop {
            // Run processing to increase likelyhood we have something to parse.
            for _ in 0..1000 {
                self.process()?;
            }
            self.digest()?;
            if let Some(response) = self.rxq.dequeue() {
                return Ok(response);
            }
        }
    }

    fn do_write(&mut self, buf: &[u8]) -> Result<(), DriverError> {
        for b in buf.iter() {
            match self.tx.write(*b) {
                Err(nb::Error::WouldBlock) => {
                    nb::block!(self.tx.flush()).map_err(|_| DriverError::WriteError)?;
                }
                Err(_) => return Err(DriverError::WriteError),
                _ => {}
            }
        }
        nb::block!(self.tx.flush()).map_err(|_| DriverError::WriteError)?;
        Ok(())
    }

    /// Send an AT command to the lora module and await a response.
    pub fn send_command(&mut self, command: Command) -> Result<Response, DriverError> {
        let mut s = Command::buffer();
        command.encode(&mut s);
        log::debug!("Sending command {}", s.as_str());
        self.do_write(s.as_bytes())?;
        self.do_write(b"\r\n")?;

        let response = self.recv_response()?;
        Ok(response)
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}