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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
use base64;
use derive_builder::Builder;
use log::{debug, log_enabled, trace, Level::*};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serialport::prelude::*;
use serialport::SerialPortType::*;
use std::convert::{TryFrom, TryInto};
use std::io;
use std::str;
use std::time::{Duration as StdDuration, Instant};
use thiserror::Error;

const PROTOCOL_VERSION: u8 = 16;
const TIMEOUT: StdDuration = StdDuration::from_secs(1);

#[derive(Builder)]
#[builder(pattern = "owned", build_fn(skip))]
pub struct LoRaSerial {
    port: Box<dyn SerialPort>,
    timeout: StdDuration,
    instance_id: String,
    modem_address: u8,
}

impl LoRaSerialBuilder {
    /// convenience function to initialize a serial port based on the name
    pub fn port_name(mut self, name: &str) -> Result<Self, serialport::Error> {
        let settings = SerialPortSettings {
            baud_rate: 115200,
            data_bits: DataBits::Eight,
            flow_control: FlowControl::None,
            parity: Parity::None,
            stop_bits: StopBits::One,
            timeout: StdDuration::from_millis(1),
        };

        self.port = Some(serialport::open_with_settings(name, &settings)?);
        Ok(self)
    }

    pub fn build(self) -> Result<LoRaSerial, ErrorKind> {
        let mut new_self = LoRaSerial {
            port: self.port.ok_or(ErrorKind::InvalidInput {
                msg: "Port must be specified in builder".into(),
            })?,
            timeout: self.timeout.unwrap_or_else(|| TIMEOUT),
            instance_id: self.instance_id.unwrap_or_else(|| String::new()),
            modem_address: self.modem_address.unwrap_or(0),
        };

        let version = new_self.read_version()?;

        if version != PROTOCOL_VERSION {
            return Err(ErrorKind::VersionMismatch {
                actual: version,
                expected: PROTOCOL_VERSION,
            });
        }

        new_self.reset()?;

        Ok(new_self)
    }
}

impl LoRaSerial {
    /// Convenience method to connect to all detected USBSerial modems
    /// Modems that fail to initialize will be passed over
    /// Each instance will be given a unique id for logging, and each modem will get an address matching it's instance id
    pub fn init_all() -> Vec<LoRaSerial> {
        serialport::available_ports()
            .expect("Error enumerating ports")
            .into_iter()
            .filter(|port_info| match &port_info.port_type {
                UsbPort(_usb_info) => true,
                _ => false,
            })
            .enumerate()
            .filter_map(|(i, port_info)| {
                trace!("{:?}", port_info);
                let mut builder = LoRaSerialBuilder::default();

                // set the instance id
                builder = builder.instance_id(i.to_string());
                builder = builder
                    .modem_address(i.try_into().expect("Ran out of modem addresses to assign!"));

                // open the port
                match builder.port_name(&port_info.port_name) {
                    Err(e) => {
                        trace!("Error opening port {:?}", e);
                        return None;
                    }
                    Ok(new_builder) => builder = new_builder,
                };

                // bring it all together
                match builder.build() {
                    Err(e) => {
                        trace!("Error connecting to device {:?}", e);
                        return None;
                    }
                    Ok(lora_serial) => return Some(lora_serial),
                };
            })
            .collect()
    }

    /// Get the address assigned to the modem
    /// modem address is stored in the LoRaSerial struct so no communication with the modem takes place
    pub fn modem_address(&mut self) -> u8 {
        self.modem_address
    }

    /// read the protocol version in use by the modem
    fn read_version(&mut self) -> Result<u8, ErrorKind> {
        self.serial_fetch_json(&SerialRequest::ReadVersion)
    }

    /// reset the modem
    pub fn reset(&mut self) -> Result<(), ErrorKind> {
        self.init_modem()?;

        // reset all settings, to prevent flakiness
        self.set_frequency(915.0)?;
        self.set_radio_preset(Bw125Cr45Sf128)?;
        self.set_tx_power(0)?;
        self.set_modem_address(self.modem_address)?;

        Ok(())
    }

    /// Initialize the modem.  The modem will try to connect to the RFM95 chip via SPI and set up it's registers.
    fn init_modem(&mut self) -> Result<(), ErrorKind> {
        self.serial_fetch_json(&SerialRequest::Init)
    }

    /// Set the transmitter and receiver center frequency
    pub fn set_frequency(&mut self, new_freq: f32) -> Result<(), ErrorKind> {
        self.serial_fetch_json(&SerialRequest::SetFrequency { freq: new_freq })
    }
    /// Select a modem config preset
    pub fn set_radio_preset(&mut self, preset: RadioPreset) -> Result<(), ErrorKind> {
        self.serial_fetch_json(&SerialRequest::SetRadioPreset { preset })
    }

    /// set tx power
    pub fn set_tx_power(&mut self, power: i8) -> Result<(), ErrorKind> {
        self.serial_fetch_json(&SerialRequest::SetTxPower { power })
    }

    pub fn set_modem_address(&mut self, address: u8) -> Result<(), ErrorKind> {
        let echo: u8 = self.serial_fetch_json(&SerialRequest::SetModemAddress { address })?;
        if echo == address {
            self.modem_address = address;
            Ok(())
        } else {
            Err(ErrorKind::RoundtripIntegrityError {
                received: echo.to_string(),
                sent: address.to_string(),
                param: "modem address".into(),
            })
        }
    }

    /// send a packet
    pub fn tx_string(&mut self, msg: &str, dst: u8) -> Result<(), ErrorKind> {
        self.tx(msg.as_bytes(), dst)
    }

    pub fn tx(&mut self, msg: &[u8], dst: u8) -> Result<(), ErrorKind> {
        self.serial_fetch_json(&SerialRequest::Tx {
            msg: base64::encode(msg),
            dst,
        })
    }

    /// try to receive a packet
    /// (puts the radio into receive mode, if if's not there already)
    pub fn rx(&mut self) -> Result<Option<LoraMsg>, ErrorKind> {
        let response = self.serial_fetch_json(&SerialRequest::Rx)?;

        match response {
            RxResult::Packet(incoming_msg) => {
                let decoded_msg = LoraMsg::try_from(incoming_msg)?;

                Ok(Some(decoded_msg))
            }
            RxResult::NoPacket => Ok(None),
        }
    }

    pub fn rx_string(&mut self) -> Result<Option<LoraStringMsg>, ErrorKind> {
        let decoded_msg = self.rx()?;
        match decoded_msg {
            None => Ok(None),
            Some(decoded_msg) => {
                let utf8_msg =
                    LoraStringMsg::try_from(decoded_msg).map_err(|e| ErrorKind::EncodingError {
                        msg: format!("LoRa packet contents are not valid UTF-8 text: {:?}", e),
                    })?;

                Ok(Some(utf8_msg))
            }
        }
    }

    fn serial_fetch_json<T: DeserializeOwned>(
        &mut self,
        request: &SerialRequest,
    ) -> Result<T, ErrorKind> {
        trace!("serial_fetch_json");

        let response = self.serial_fetch_raw(request)?;

        let response: SerialResponse<T> = serde_json::from_slice(&response).map_err(|e| {
            trace!("Error deserializing serial response from slice, {:?}", e);
            ErrorKind::DeserializeError { inner: e }
        })?;
        response.into_result()
    }
    fn serial_fetch_raw(&mut self, request: &SerialRequest) -> Result<Vec<u8>, ErrorKind> {
        trace!("serial fetch");

        // Serialize the request
        let request =
            serde_json::to_string(request).map_err(|e| ErrorKind::SerializeError { inner: e })?;

        // log our message
        // we print directly to avoid the date/time headers
        if log_enabled!(Debug) {
            println!("->{} {}", self.instance_id, request);
        }

        // write the msg to the port
        self.port
            .write_all(request.as_bytes())
            .map_err(|e| ErrorKind::IoError {
                context: "Error writing message to port".into(),
                inner: e,
            })?;
        // write a newline (ASCII 10)
        self.port.write_all(b"\n").map_err(|e| ErrorKind::IoError {
            context: "Error writing newline to port".into(),
            inner: e,
        })?;

        // wait for a response
        let mut response_buffer: Vec<u8> = Vec::new();
        let start_time = Instant::now();

        let mut printed_leading_arrow = false;
        loop {
            if start_time.elapsed() > self.timeout {
                return Err(ErrorKind::Timeout {
                    msg: "Timed out waiting for response from modem.".into(),
                });
            }

            let mut char_buf = [0; 1];
            match self.port.read(&mut char_buf) {
                // no bytes available at this time
                Ok(bytes) if bytes == 0 => (),
                // another way of signaling no bytes available at this time
                Err(ref e) if e.kind() == io::ErrorKind::TimedOut => (),
                // we got a byte!
                Ok(_bytes) => {
                    if log_enabled!(Debug) {
                        if !printed_leading_arrow {
                            print!("<-{} ", self.instance_id);
                            printed_leading_arrow = true;
                        }
                        print!(
                            "{}",
                            String::from_utf8(char_buf.to_vec())
                                .unwrap_or_else(|_e| String::from("?"))
                        );
                    }
                    response_buffer.push(char_buf[0]);
                    if char_buf[0] == 10 {
                        return Ok(response_buffer);
                    }
                }
                // real error
                Err(e) => {
                    return Err(ErrorKind::IoError {
                        context: "reading from serial port".into(),
                        inner: e,
                    });
                }
            }
        }
    }
}

#[derive(Debug, Error)]
pub enum ErrorKind {
    #[error("The serial modem appears to be running an incompatible protocol version.  Local version = {expected}, remote version = {actual}.")]
    VersionMismatch { actual: u8, expected: u8 },
    #[error("IO Error ({context}): {inner}")]
    IoError {
        context: String,
        #[source]
        inner: std::io::Error,
    },
    #[error("There was an error deserializing the incoming message: {inner}")]
    DeserializeError {
        #[source]
        inner: serde_json::Error,
    },
    #[error("There was an error serializing the outgoing message: {inner}")]
    SerializeError { inner: serde_json::Error },
    #[error("Encoding error: {msg}")]
    EncodingError { msg: String },
    #[error("Remote modem returned an error: {msg}")]
    RemoteError { msg: String },
    #[error("Invalid Parameters: {msg}")]
    InvalidInput { msg: String },
    #[error("Operation timed out: {msg}")]
    Timeout { msg: String },
    #[error("Round-trip integrity check failed for {param}: Sent {sent}, received {received}")]
    RoundtripIntegrityError {
        param: String,
        sent: String,
        received: String,
    },
    #[error("Error while attempting to interact with the serial port ({context}): {inner}")]
    SerialPortError {
        context: String,
        #[source]
        inner: serialport::Error,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum RadioPreset {
    /// Medium Range (Bandwidth = 125 kHz, Coding Rate = 4/5, Spreading Factor = 128 chips/symbol)
    Bw125Cr45Sf128,
    /// Fast but with short range (Bandwidth = 500 kHz, Coding Rate = 4/5, Spreading Factor = 128 chips/symbol)
    Bw500Cr45Sf128,
    /// Slow with long range (Bandwidth = 31.25 kHz, Coding Rate = 4/8, Spreading Factor = 512 chips/symbol)
    Bw31_25Cr48Sf512,
    /// Slow with long range (Bandwidth = 125kHz, Coding Rate = 4/8, Spreading Factor = 4096 chips/symbol)
    Bw125Cr48Sf4096,
}
use RadioPreset::*;

#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
enum SerialRequest {
    ReadVersion,
    Init,
    SetFrequency { freq: f32 },
    SetRadioPreset { preset: RadioPreset },
    SetTxPower { power: i8 },
    Tx { msg: String, dst: u8 },
    SetModemAddress { address: u8 },
    Rx,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "status")]
enum SerialResponse<T> {
    Ok { body: T },
    Err { err_msg: String },
}

impl<T> SerialResponse<T> {
    fn into_result(self) -> Result<T, ErrorKind> {
        match self {
            Self::Ok { body } => Ok(body),
            Self::Err { err_msg } => Err(ErrorKind::RemoteError { msg: err_msg }),
        }
    }
}

#[derive(Deserialize, Debug, Clone, PartialEq)]
pub struct IncomingLoraMsg {
    src: u8,
    dst: u8,
    len: u8,
    data: String,
    id: u8,
    flags: u8,
}

#[derive(Clone, Deserialize, Debug)]
pub struct LoraMsg {
    pub src: u8,
    pub dst: u8,
    pub len: u8,
    pub data: Vec<u8>,
    pub id: u8,
    pub flags: u8,
}

impl TryFrom<IncomingLoraMsg> for LoraMsg {
    type Error = ErrorKind;
    fn try_from(msg: IncomingLoraMsg) -> Result<Self, Self::Error> {
        Ok(Self {
            src: msg.src,
            dst: msg.dst,
            len: msg.len,
            id: msg.id,
            flags: msg.flags,
            data: base64::decode(&msg.data).map_err(|e| ErrorKind::EncodingError {
                msg: format!("Error decoding packet ({}): {:?}", msg.data, e),
            })?,
        })
    }
}

#[derive(Clone, Deserialize, Debug)]
pub struct LoraStringMsg {
    pub src: u8,
    pub dst: u8,
    pub len: u8,
    pub data: String,
    pub id: u8,
    pub flags: u8,
}

impl TryFrom<LoraMsg> for LoraStringMsg {
    type Error = ErrorKind;
    fn try_from(msg: LoraMsg) -> Result<Self, Self::Error> {
        Ok(Self {
            src: msg.src,
            dst: msg.dst,
            len: msg.len,
            id: msg.id,
            flags: msg.flags,
            data: String::from_utf8(msg.data).map_err(|e| ErrorKind::EncodingError {
                msg: format!("Error reading bytes as utf-8\n{:?}", e),
            })?,
        })
    }
}

impl TryFrom<IncomingLoraMsg> for LoraStringMsg {
    type Error = ErrorKind;
    fn try_from(msg: IncomingLoraMsg) -> Result<Self, Self::Error> {
        Self::try_from(LoraMsg::try_from(msg)?)
    }
}

#[derive(Clone, Deserialize, Debug)]
#[serde(tag = "type")]
pub enum RxResult {
    Packet(IncomingLoraMsg),
    NoPacket,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn pre_test() -> Vec<LoRaSerial> {
        let _ = env_logger::from_env(env_logger::Env::default().default_filter_or("debug"))
            .is_test(true)
            .try_init();

        let instances = LoRaSerial::init_all();

        assert!(!instances.is_empty());

        instances
    }

    fn pre_test_pair() -> (LoRaSerial, LoRaSerial) {
        let mut ports = pre_test();

        assert!(
            ports.len() >= 2,
            "At least two ports are required for this test"
        );

        let mut a = ports.pop().unwrap();
        let mut b = ports.pop().unwrap();

        a.set_modem_address(1).unwrap();
        b.set_modem_address(2).unwrap();

        (a, b)
    }

    #[test]
    fn a_smoke_init_ok() {
        pre_test();
    }

    #[test]
    fn a_smoke_set_frequency() {
        let loras = pre_test();

        for mut lora in loras {
            lora.set_frequency(915.0).unwrap();
        }
    }

    #[test]
    fn a_smoke_set_radio_preset() {
        let loras = pre_test();

        for mut lora in loras {
            lora.set_radio_preset(Bw125Cr45Sf128).unwrap();
        }
    }

    #[test]
    fn a_smoke_set_modem_address() {
        let loras = pre_test();

        for mut lora in loras {
            lora.set_modem_address(0).unwrap();
            lora.set_modem_address(1).unwrap();
            lora.set_modem_address(2).unwrap();
            lora.set_modem_address(3).unwrap();
            lora.set_modem_address(4).unwrap();
        }
    }

    #[test]
    fn a_smoke_set_tx_power() {
        let loras = pre_test();

        for mut lora in loras {
            lora.set_tx_power(-1).unwrap();
            lora.set_tx_power(0).unwrap();
            lora.set_tx_power(5).unwrap();
        }
    }

    #[test]
    fn a_smoke_tx() {
        let loras = pre_test();

        for mut lora in loras {
            lora.tx_string("Hello, World!", 2).unwrap();
        }
    }
    #[test]
    fn a_smoke_rx() {
        let loras = pre_test();

        for mut lora in loras {
            lora.rx_string().unwrap();
        }
    }

    #[test]
    fn a_smoke_reset() {
        let loras = pre_test();
        for mut lora in loras {
            lora.tx_string("Hello, World!", 2).unwrap();
            lora.reset().unwrap();
        }
    }

    #[test]
    fn integration_tx_rx() {
        let (mut lora_a, mut lora_b) = pre_test_pair();

        // try five times
        for n in 1..6 {
            println!("Attempt {}/5", n);

            // put the radio into receive mode
            lora_a.rx_string().unwrap();

            // lora_a has address 1 by default
            lora_b.tx_string("Hello, World!", 1).unwrap();

            // now see if we've got anything
            let timeout = Instant::now();
            while timeout.elapsed() <= StdDuration::from_secs(1) {
                if let Some(packet) = lora_a.rx_string().unwrap() {
                    println!("{:?}", packet);
                    assert_eq!(packet.src, 2, "packet.src");
                    assert_eq!(packet.dst, 1, "packet.dst");
                    assert_eq!(packet.len, 13, "packet.len");
                    assert_eq!(packet.data, String::from("Hello, World!"), "packet.data");

                    return;
                }
            }
        }

        panic!("Didn't receive anything!");
    }

    #[test]
    /// test for a strange bug that only occurred when the device was left inactive for 1500 ms
    fn a_stress_delayed_action() {
        let mut lora = pre_test().pop().unwrap();

        std::thread::sleep(StdDuration::from_millis(1500));
        lora.read_version().unwrap();
    }

    #[test]
    fn stress_tx() {
        let mut loras = pre_test();

        let timeout = Instant::now();
        while timeout.elapsed() <= StdDuration::from_secs(5) {
            for lora in &mut loras {
                lora.tx_string("Hello, World!", 2).unwrap();
            }
        }
    }
    #[test]
    fn stress_init() {
        let timeout = Instant::now();
        while timeout.elapsed() <= StdDuration::from_secs(5) {
            let _lora = pre_test();
        }
    }
    #[test]
    fn stress_rx() {
        let mut lora = pre_test().pop().unwrap();

        let timeout = Instant::now();
        while timeout.elapsed() <= StdDuration::from_secs(5) {
            lora.rx_string().unwrap();
        }
    }

    #[test]
    fn stress_packet_loss() {
        let iterations = 10;

        let (mut lora_a, mut lora_b) = pre_test_pair();

        let mut success = 0;

        'outer: for n in 0..iterations {
            println!("test {}/{}", n, iterations);

            // put the radio into receive mode
            lora_a.rx_string().unwrap();

            // lora_a has address 1 by default
            lora_b.tx_string("Hello, World!", 1).unwrap();

            // now see if we've got anything
            let timeout = Instant::now();
            while timeout.elapsed() <= StdDuration::from_secs(1) {
                if let Some(packet) = lora_a.rx_string().unwrap() {
                    println!("{:?}", packet);
                    assert_eq!(packet.src, 2, "packet.src");
                    assert_eq!(packet.dst, 1, "packet.dst");
                    assert_eq!(packet.len, 13, "packet.len");
                    assert_eq!(packet.data, String::from("Hello, World!"), "packet.data");

                    success += 1;

                    continue 'outer;
                }
            }
        }

        let loss = iterations / success;
        println!("{}/{} packet loss", loss, iterations);
        assert!(
            loss <= iterations / 10,
            "{}/{} packet loss is unacceptably high",
            loss,
            iterations
        );
    }
}