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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
//! Currently only supports XBee S2C hardware running the 802.15.04 RF firmware

#![no_std]

extern crate arraydeque;
extern crate arrayvec;
#[macro_use]
extern crate bitflags;
extern crate embedded_hal;
#[macro_use]
extern crate nb;

pub mod api_frame;

use core::marker::PhantomData;

use api_frame::{ApiData, ApiUnpackError, FramePacker, TxOptions, TxRequestIter};

use arraydeque::ArrayDeque;
use arrayvec::{Array, ArrayVec};
use embedded_hal::blocking::delay::DelayMs;
use embedded_hal::blocking::serial::Write as BlockingWrite;
use embedded_hal::digital::{InputPin, OutputPin};
use embedded_hal::serial::{Read, Write};
use embedded_hal::spi::FullDuplex;

pub const BROADCAST_ADDR: u16 = 0xFFFF;
pub const COORDINATOR_ADDR: u16 = 0xFFFE;

trait XBeeQueue {
    fn remove_until_start(&mut self) -> Result<usize, ()>;
    fn remove_exact(&mut self, amount: usize) -> Result<(), ()>;
}

impl<A> XBeeQueue for ArrayVec<A>
where
    A: Array<Item = u8>,
{
    fn remove_until_start(&mut self) -> Result<usize, ()> {
        match self.iter().position(|c| c == &api_frame::START) {
            Some(size) => {
                self.remove_exact(size)?;
                Ok(size)
            }
            None => {
                let len = self.len();
                self.clear();
                Ok(len)
            }
        }
    }

    fn remove_exact(&mut self, amount: usize) -> Result<(), ()> {
        if amount == 0 {
            return Ok(());
        }

        if amount <= self.len() {
            self.drain(0..amount);
            Ok(())
        } else {
            Err(())
        }
    }
}

// TODO: builders

// TODO: maybe add broadcast
// TODO: maybe add coordinator
pub enum Addr {
    Short(u16),
    Long(u64),
}

// TODO: xbee reset pin
pub struct XBeeTransparent<'a, 'b, U: 'a, D: 'b> {
    serial: &'a mut U,
    timer: &'b mut D,
    cmd_char: u8,
    guard_time: u16,
}

#[derive(Copy, Clone, Debug)]
pub enum XBeeApiError {
    Unpack(ApiUnpackError),
    Parse(()),
}

// TODO: xbee reset pin
pub struct XBeeApiSpi<'a, 'b, 'c, S: 'a, C: 'b, A: 'c> {
    serial: &'a mut S,
    cs: Option<&'b mut C>,
    attn: &'c mut A,

    // TODO: make generic and allow passing in buffers
    tx_queue: ArrayDeque<[u8; 512]>,
    rx_queue: ArrayVec<[u8; 512]>,
}

impl<'a, 'b, E, U, D> XBeeTransparent<'a, 'b, U, D>
where
    U: Read<u8, Error = E> + BlockingWrite<u8, Error = E>,
    D: DelayMs<u16>,
{
    pub fn new(
        uart: &'a mut U,
        delay: &'b mut D,
        cmd_char: u8,
        guard_time: u16,
    ) -> XBeeTransparent<'a, 'b, U, D> {
        XBeeTransparent {
            serial: uart,
            timer: delay,
            cmd_char,
            guard_time,
        }
    }

    // TODO: maybe return result to show that the command has
    pub fn enter_command_mode(&mut self) -> Result<(), E> {
        // wait for guard time
        self.timer.delay_ms(self.guard_time);
        // send command character x3
        self.serial.bwrite_all(&[self.cmd_char; 3])?;
        // wait for "OK"
        loop {
            match self.serial.read() {
                Ok(b'O') => break,
                Ok(_) => panic!("Got other character while waiting for OK"), // TODO: error
                Err(nb::Error::WouldBlock) => {} // keep blocking
                Err(_) => panic!("Some error while waiting for OK"), // return Err(e.into()),
            }
        }
        loop {
            match self.serial.read() {
                Ok(b'K') => break,
                Ok(_) => panic!("Got other character while waiting for OK"), // TODO: error
                Err(nb::Error::WouldBlock) => {} // keep blocking
                Err(_) => panic!("Some error while waiting for OK"), // return Err(e.into()),
            }
        }
        Ok(())
    }
}

impl<'a, 'b, U, D> Read<u8> for XBeeTransparent<'a, 'b, U, D>
where
    U: Read<u8>,
{
    type Error = U::Error;

    fn read(&mut self) -> nb::Result<u8, Self::Error> {
        self.serial.read()
    }
}

impl<'a, 'b, U, D> Write<u8> for XBeeTransparent<'a, 'b, U, D>
where
    U: Write<u8>,
{
    type Error = U::Error;

    fn write(&mut self, word: u8) -> nb::Result<(), Self::Error> {
        self.serial.write(word)
    }

    fn flush(&mut self) -> nb::Result<(), Self::Error> {
        self.serial.flush()
    }
}

impl<'a, 'b, 'c, E, S, C, A> XBeeApiSpi<'a, 'b, 'c, S, C, A>
where
    S: FullDuplex<u8, Error = E>,
    C: OutputPin,
    A: InputPin,
{
    pub fn new(
        spi: &'a mut S,
        cs: Option<&'b mut C>,
        attn: &'c mut A,
    ) -> XBeeApiSpi<'a, 'b, 'c, S, C, A> {
        XBeeApiSpi {
            serial: spi,
            cs,
            attn,
            tx_queue: ArrayDeque::new(),
            rx_queue: ArrayVec::new(),
        }
    }

    pub fn tx_queue_empty(&self) -> bool {
        self.tx_queue.is_empty()
    }

    pub fn tx_queue_full(&self) -> bool {
        self.tx_queue.is_full()
    }

    pub fn rx_queue_empty(&self) -> bool {
        self.rx_queue.is_empty()
    }

    pub fn rx_queue_full(&self) -> bool {
        self.rx_queue.is_full()
    }

    // TODO: differentiate between errors from reading and writing
    pub fn transmit_and_receive(&mut self) -> Result<bool, E> {
        if let Some(ref mut cs) = self.cs {
            cs.set_low();
        }

        let ret = self.tx_rx_internal();

        if let Some(ref mut cs) = self.cs {
            cs.set_high();
        }

        ret
    }

    pub fn tx_rx_internal(&mut self) -> Result<bool, E> {
        let mut val_read = false;
        let mut attn_val;
        while {
            attn_val = self.attn.is_high();
            !self.tx_queue.is_empty() || !attn_val
        } {
            let tx = if !self.tx_queue.is_empty() {
                // TODO: don't unwrap, pass up error
                self.tx_queue.pop_front().unwrap()
            } else {
                0xFF
            };

            //write!(uart, "\r\nt {:02X}", tx).unwrap();
            // TODO: better error handling?
            block!(self.serial.send(tx))?;

            let rx = block!(self.serial.read())?;
            //write!(uart, "\r\nr {:02X}", rx).unwrap();
            if !attn_val {
                //write!(uart, " s").unwrap();
                // TODO: don't unwrap, pass up error
                self.rx_queue.try_push(rx).unwrap();
                val_read = true;
                if self.rx_queue.is_full() {
                    break;
                }
            }
        }

        Ok(val_read)
    }

    pub fn get_sender_receiver<'d>(&'d mut self) -> (XBeeApiSender<'d, E>, XBeeApiReceiver<'d, E>) {
        let tx_queue = &mut self.tx_queue;
        let rx_queue = &mut self.rx_queue;

        let sender = XBeeApiSender {
            tx_queue,
            _error: PhantomData,
        };
        let receiver = XBeeApiReceiver {
            rx_queue,
            _error: PhantomData,
        };

        (sender, receiver)
    }
}

#[derive(Debug)]
pub struct XBeeApiSender<'a, E> {
    // TODO: make generic
    tx_queue: &'a mut ArrayDeque<[u8; 512]>,
    _error: PhantomData<*const E>,
}

impl<'a, E> XBeeApiSender<'a, E> {
    pub fn queue_empty(&self) -> bool {
        self.tx_queue.is_empty()
    }

    pub fn queue_full(&self) -> bool {
        self.tx_queue.is_full()
    }

    pub fn send_data_raw(&mut self, data: &[u8]) -> Result<(), E> {
        // TODO: error handling if we do not have enough space
        self.tx_queue.extend(data.iter().map(|&x| x));
        Ok(())
    }

    pub fn send_data(&mut self, frame_id: u8, addr: Addr, data: &[u8]) -> Result<(), E> {
        let tx_request =
            TxRequestIter::new(frame_id, addr, TxOptions::empty(), data.iter().map(|v| *v));
        let frame = FramePacker::new(tx_request, false, false).expect("packing error"); // TODO:

        // TODO: error handling if we do not have enough space
        self.tx_queue.extend(frame);
        Ok(())
    }

    pub fn send_data_no_ack(&mut self, frame_id: u8, addr: Addr, data: &[u8]) -> Result<(), E> {
        let tx_request = TxRequestIter::new(
            frame_id,
            addr,
            TxOptions::DISABLE_ACK,
            data.iter().map(|v| *v),
        );
        let frame = FramePacker::new(tx_request, false, false).expect("packing error"); // TODO:

        // TODO: error handling if we do not have enough space
        self.tx_queue.extend(frame);
        Ok(())
    }

    pub fn at_command(&mut self, frame_id: u8, at_cmd: [u8; 2], params: &[u8]) {
        unimplemented!()
    }

    pub fn at_queue_param(&mut self, frame_id: u8, at_cmd: [u8; 2], params: &[u8]) {
        unimplemented!()
    }

    pub fn remote_at_command(&mut self, frame_id: u8, addr: Addr, at_cmd: [u8; 2], params: &[u8]) {
        unimplemented!()
    }
}

impl<'a, E> Drop for XBeeApiSender<'a, E> {
    fn drop(&mut self) {}
}

pub struct XBeeApiReceiver<'a, E> {
    // TODO: make generic
    rx_queue: &'a mut ArrayVec<[u8; 512]>,
    _error: PhantomData<*const E>,
}

impl<'a, E> XBeeApiReceiver<'a, E> {
    pub fn queue_empty(&self) -> bool {
        self.rx_queue.is_empty()
    }

    pub fn queue_full(&self) -> bool {
        self.rx_queue.is_full()
    }

    pub fn unpack_and_parse_buffer<'d>(&'d self) -> Result<ApiData<'d>, XBeeApiError> {
        let ret = match api_frame::unpack_frame(self.rx_queue.as_slice(), false, false) {
            Ok((frame, _rem)) => ApiData::parse(frame).map_err(|err| XBeeApiError::Parse(err)),
            Err(err) => Err(XBeeApiError::Unpack(err)),
        };

        ret
    }

    pub fn remove_until_packet(&mut self) -> Result<usize, ()> {
        self.rx_queue.remove_until_start()
    }

    pub fn remove_until_next_packet(&mut self) -> Result<usize, ()> {
        if let Some(_) = self.rx_queue.pop_at(0) {
            self.remove_until_packet().map(|len| len + 1)
        } else {
            Ok(0)
        }
    }

    pub fn as_slice(&self) -> &[u8] {
        self.rx_queue.as_slice()
    }
}

impl<'a, E> Drop for XBeeApiReceiver<'a, E> {
    fn drop(&mut self) {}
}