donglora-protocol 1.1.0

DongLoRa wire protocol types and COBS framing — shared between firmware and host crates
Documentation
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
//! Property tests against the DongLoRa Protocol v2 wire codec.
//!
//! - **Roundtrip** — encoding then decoding yields the original value,
//!   for frames, commands, LoRa/FSK/LR-FHSS/FLRC params, and `Info`.
//! - **No-panic** — `FrameDecoder::feed`, `Command::parse`, and the
//!   various payload decoders never panic on arbitrary byte input.
//! - **Bounded capacity** — encoders refuse oversized inputs with a
//!   typed error; no hidden allocation.

#![allow(clippy::unwrap_used, clippy::panic)]

use donglora_protocol::{
    Command, DeviceMessage, ErrorCode, FlrcBitrate, FlrcBt, FlrcCodingRate, FlrcConfig,
    FlrcPreambleLen, FrameDecoder, FrameResult, FskConfig, Info, LoRaBandwidth, LoRaCodingRate,
    LoRaConfig, LoRaHeaderMode, LrFhssBandwidth, LrFhssCodingRate, LrFhssConfig, LrFhssGrid,
    MAX_MCU_UID_LEN, MAX_OTA_PAYLOAD, MAX_PAYLOAD_FIELD, MAX_RADIO_UID_LEN, MAX_SYNC_WORD_LEN,
    MAX_WIRE_FRAME, Modulation, RadioChipId, RxOrigin, RxPayload, TxDonePayload, TxFlags, TxResult,
    commands, encode_frame, events,
};
use heapless::Vec as HVec;
use proptest::prelude::*;

// ── Strategies ──────────────────────────────────────────────────────

fn arb_lora() -> impl Strategy<Value = LoRaConfig> {
    (
        150_000_000u32..=960_000_000u32,
        5u8..=12u8,
        0u8..=13u8,
        0u8..=3u8,
        0u16..=1024u16,
        any::<u16>(),
        -20i8..=22i8,
        0u8..=1u8,
        any::<bool>(),
        any::<bool>(),
    )
        .prop_map(
            |(
                freq_hz,
                sf,
                bw_raw,
                cr_raw,
                preamble_len,
                sync_word,
                tx_power_dbm,
                header_raw,
                payload_crc,
                iq_invert,
            )| {
                LoRaConfig {
                    freq_hz,
                    sf,
                    bw: LoRaBandwidth::from_u8(bw_raw).unwrap(),
                    cr: LoRaCodingRate::from_u8(cr_raw).unwrap(),
                    preamble_len,
                    sync_word,
                    tx_power_dbm,
                    header_mode: LoRaHeaderMode::from_u8(header_raw).unwrap(),
                    payload_crc,
                    iq_invert,
                }
            },
        )
}

fn arb_fsk() -> impl Strategy<Value = FskConfig> {
    (
        any::<u32>(),
        any::<u32>(),
        any::<u32>(),
        any::<u8>(),
        any::<u16>(),
        0u8..=MAX_SYNC_WORD_LEN as u8,
        prop::array::uniform8(any::<u8>()),
    )
        .prop_map(
            |(freq_hz, bitrate_bps, freq_dev_hz, rx_bw, preamble_len, sync_word_len, sync)| {
                // Only the first `sync_word_len` bytes go on the wire;
                // trailing bytes must be canonicalised to zero so that
                // a wire round-trip is an identity.
                let mut sync_word = [0u8; MAX_SYNC_WORD_LEN];
                sync_word[..sync_word_len as usize]
                    .copy_from_slice(&sync[..sync_word_len as usize]);
                FskConfig {
                    freq_hz,
                    bitrate_bps,
                    freq_dev_hz,
                    rx_bw,
                    preamble_len,
                    sync_word_len,
                    sync_word,
                }
            },
        )
}

fn arb_lr_fhss() -> impl Strategy<Value = LrFhssConfig> {
    (
        any::<u32>(),
        0u8..=7u8,
        0u8..=3u8,
        0u8..=1u8,
        any::<bool>(),
        any::<i8>(),
    )
        .prop_map(
            |(freq_hz, bw, cr, grid, hopping, tx_power_dbm)| LrFhssConfig {
                freq_hz,
                bw: LrFhssBandwidth::from_u8(bw).unwrap(),
                cr: LrFhssCodingRate::from_u8(cr).unwrap(),
                grid: LrFhssGrid::from_u8(grid).unwrap(),
                hopping,
                tx_power_dbm,
            },
        )
}

fn arb_flrc() -> impl Strategy<Value = FlrcConfig> {
    (
        any::<u32>(),
        0u8..=7u8,
        0u8..=2u8,
        0u8..=2u8,
        0u8..=6u8,
        any::<u32>(),
        any::<i8>(),
    )
        .prop_map(
            |(freq_hz, br, cr, bt, pre, sync_word, tx_power_dbm)| FlrcConfig {
                freq_hz,
                bitrate: FlrcBitrate::from_u8(br).unwrap(),
                cr: FlrcCodingRate::from_u8(cr).unwrap(),
                bt: FlrcBt::from_u8(bt).unwrap(),
                preamble_len: FlrcPreambleLen::from_u8(pre).unwrap(),
                sync_word,
                tx_power_dbm,
            },
        )
}

fn arb_modulation() -> impl Strategy<Value = Modulation> {
    prop_oneof![
        arb_lora().prop_map(Modulation::LoRa),
        arb_fsk().prop_map(Modulation::FskGfsk),
        arb_lr_fhss().prop_map(Modulation::LrFhss),
        arb_flrc().prop_map(Modulation::Flrc),
    ]
}

fn arb_ota_payload() -> impl Strategy<Value = HVec<u8, MAX_OTA_PAYLOAD>> {
    prop::collection::vec(any::<u8>(), 1..=MAX_OTA_PAYLOAD).prop_map(|v| {
        let mut h = HVec::new();
        h.extend_from_slice(&v).unwrap();
        h
    })
}

fn arb_command() -> impl Strategy<Value = Command> {
    prop_oneof![
        Just(Command::Ping),
        Just(Command::GetInfo),
        Just(Command::RxStart),
        Just(Command::RxStop),
        arb_modulation().prop_map(Command::SetConfig),
        (any::<bool>(), arb_ota_payload()).prop_map(|(skip_cad, data)| Command::Tx {
            flags: TxFlags { skip_cad },
            data,
        }),
    ]
}

fn arb_tag() -> impl Strategy<Value = u16> {
    // DongLoRa Protocol hosts must never send tag=0. The frame codec still handles it
    // (tag=0 is the correct tag for async events), but for command
    // round-trips we use the non-zero range hosts actually emit.
    1u16..=u16::MAX
}

fn arb_rx_payload() -> impl Strategy<Value = RxPayload> {
    (
        any::<i16>(),
        any::<i16>(),
        any::<i32>(),
        any::<u64>(),
        any::<bool>(),
        any::<u16>(),
        0u8..=1u8,
        prop::collection::vec(any::<u8>(), 0..=MAX_OTA_PAYLOAD),
    )
        .prop_map(
            |(rssi, snr, freq_err, ts, crc_valid, drops, origin, data)| {
                let mut d = HVec::new();
                d.extend_from_slice(&data).unwrap();
                RxPayload {
                    rssi_tenths_dbm: rssi,
                    snr_tenths_db: snr,
                    freq_err_hz: freq_err,
                    timestamp_us: ts,
                    crc_valid,
                    packets_dropped: drops,
                    origin: RxOrigin::from_u8(origin).unwrap(),
                    data: d,
                }
            },
        )
}

fn arb_info() -> impl Strategy<Value = Info> {
    // Proptest tuples top out at 12 elements; Info needs 18 random
    // inputs, so pair two sub-tuples.
    let head = (
        any::<u8>(),
        any::<u8>(),
        any::<u8>(),
        any::<u8>(),
        any::<u8>(),
        any::<u16>(),
        any::<u64>(),
        any::<u16>(),
        any::<u16>(),
        any::<u16>(),
        any::<u16>(),
        any::<u16>(),
    );
    let tail = (
        any::<u32>(),
        any::<u32>(),
        any::<i8>(),
        any::<i8>(),
        prop::collection::vec(any::<u8>(), 0..=MAX_MCU_UID_LEN),
        prop::collection::vec(any::<u8>(), 0..=MAX_RADIO_UID_LEN),
    );
    (head, tail).prop_map(|(h, t)| {
        let (pma, pmi, fa, fi, fp, chip, capb, sf, bw, mpb, rxq, txq) = h;
        let (fmin, fmax, pmin, pmax, mcu_bytes, radio_bytes) = t;
        let mut mcu_uid = [0u8; MAX_MCU_UID_LEN];
        mcu_uid[..mcu_bytes.len()].copy_from_slice(&mcu_bytes);
        let mut radio_uid = [0u8; MAX_RADIO_UID_LEN];
        radio_uid[..radio_bytes.len()].copy_from_slice(&radio_bytes);
        Info {
            proto_major: pma,
            proto_minor: pmi,
            fw_major: fa,
            fw_minor: fi,
            fw_patch: fp,
            radio_chip_id: chip,
            capability_bitmap: capb,
            supported_sf_bitmap: sf,
            supported_bw_bitmap: bw,
            max_payload_bytes: mpb,
            rx_queue_capacity: rxq,
            tx_queue_capacity: txq,
            freq_min_hz: fmin,
            freq_max_hz: fmax,
            tx_power_min_dbm: pmin,
            tx_power_max_dbm: pmax,
            mcu_uid_len: mcu_bytes.len() as u8,
            mcu_uid,
            radio_uid_len: radio_bytes.len() as u8,
            radio_uid,
        }
    })
}

// ── Properties ──────────────────────────────────────────────────────

proptest! {
    #[test]
    fn command_roundtrip(cmd in arb_command(), tag in arb_tag()) {
        let mut payload_buf = [0u8; 320];
        let payload_len = cmd.encode_payload(&mut payload_buf).unwrap();
        let mut wire = [0u8; MAX_WIRE_FRAME];
        let n = encode_frame(cmd.type_id(), tag, &payload_buf[..payload_len], &mut wire).unwrap();

        let mut decoder = FrameDecoder::new();
        let mut got: Option<(u8, u16, HVec<u8, 320>)> = None;
        decoder.feed(&wire[..n], |res| match res {
            FrameResult::Ok { type_id, tag, payload } => {
                let mut p = HVec::new();
                p.extend_from_slice(payload).unwrap();
                got = Some((type_id, tag, p));
            }
            FrameResult::Err(e) => panic!("decode error: {:?}", e),
        });
        let (type_id, decoded_tag, payload) = got.unwrap();
        prop_assert_eq!(type_id, cmd.type_id());
        prop_assert_eq!(decoded_tag, tag);
        let parsed = Command::parse(type_id, &payload).unwrap();
        prop_assert_eq!(parsed, cmd);
    }

    #[test]
    fn lora_config_roundtrip(cfg in arb_lora()) {
        let mut buf = [0u8; 16];
        let n = cfg.encode(&mut buf).unwrap();
        let decoded = LoRaConfig::decode(&buf[..n]).unwrap();
        prop_assert_eq!(decoded, cfg);
    }

    #[test]
    fn fsk_config_roundtrip(cfg in arb_fsk()) {
        let mut buf = [0u8; 32];
        let n = cfg.encode(&mut buf).unwrap();
        let decoded = FskConfig::decode(&buf[..n]).unwrap();
        prop_assert_eq!(decoded, cfg);
    }

    #[test]
    fn lr_fhss_roundtrip(cfg in arb_lr_fhss()) {
        let mut buf = [0u8; 16];
        let n = cfg.encode(&mut buf).unwrap();
        let decoded = LrFhssConfig::decode(&buf[..n]).unwrap();
        prop_assert_eq!(decoded, cfg);
    }

    #[test]
    fn flrc_roundtrip(cfg in arb_flrc()) {
        let mut buf = [0u8; 16];
        let n = cfg.encode(&mut buf).unwrap();
        let decoded = FlrcConfig::decode(&buf[..n]).unwrap();
        prop_assert_eq!(decoded, cfg);
    }

    #[test]
    fn rx_payload_roundtrip(rx in arb_rx_payload()) {
        let mut buf = [0u8; MAX_PAYLOAD_FIELD];
        let n = rx.encode(&mut buf).unwrap();
        let decoded = RxPayload::decode(&buf[..n]).unwrap();
        prop_assert_eq!(decoded, rx);
    }

    #[test]
    fn tx_done_roundtrip(result_raw in 0u8..=2u8, airtime in any::<u32>()) {
        let td = TxDonePayload {
            result: TxResult::from_u8(result_raw).unwrap(),
            airtime_us: airtime,
        };
        let mut buf = [0u8; 8];
        let n = td.encode(&mut buf).unwrap();
        prop_assert_eq!(TxDonePayload::decode(&buf[..n]).unwrap(), td);
    }

    #[test]
    fn err_roundtrip(code_raw in any::<u16>()) {
        let code = ErrorCode::from_u16(code_raw);
        let mut buf = [0u8; 2];
        let n = events::encode_err_payload(code, &mut buf).unwrap();
        prop_assert_eq!(n, 2);
        let decoded = events::decode_err_payload(&buf).unwrap();
        prop_assert_eq!(decoded.as_u16(), code_raw);
    }

    #[test]
    fn info_roundtrip(info in arb_info()) {
        let mut buf = [0u8; 128];
        let n = info.encode(&mut buf).unwrap();
        let decoded = Info::decode(&buf[..n]).unwrap();
        prop_assert_eq!(decoded, info);
    }

    #[test]
    fn decoder_never_panics_on_arbitrary_bytes(bytes in prop::collection::vec(any::<u8>(), 0..1024)) {
        let mut decoder = FrameDecoder::new();
        decoder.feed(&bytes, |_res| {});
    }

    #[test]
    fn command_parse_never_panics(type_id in any::<u8>(), payload in prop::collection::vec(any::<u8>(), 0..320)) {
        let _ = Command::parse(type_id, &payload);
    }

    #[test]
    fn device_message_parse_never_panics(
        type_id in any::<u8>(),
        payload in prop::collection::vec(any::<u8>(), 0..320),
        cmd_type in prop::option::of(any::<u8>()),
    ) {
        let _ = DeviceMessage::parse(type_id, &payload, cmd_type);
    }

    #[test]
    fn tag_zero_still_encodes(payload in prop::collection::vec(any::<u8>(), 0..=MAX_PAYLOAD_FIELD)) {
        // The crate itself doesn't reject tag=0 — tag=0 is the correct
        // tag for async events. Host-level code enforces the "commands
        // must not use tag=0" rule separately.
        let mut wire = [0u8; MAX_WIRE_FRAME];
        let _ = encode_frame(0xC0, 0, &payload, &mut wire);
    }

    #[test]
    fn random_modulation_via_set_config_roundtrip(m in arb_modulation(), tag in arb_tag()) {
        let cmd = Command::SetConfig(m);
        let mut payload_buf = [0u8; 320];
        let payload_len = cmd.encode_payload(&mut payload_buf).unwrap();
        let mut wire = [0u8; MAX_WIRE_FRAME];
        let n = encode_frame(cmd.type_id(), tag, &payload_buf[..payload_len], &mut wire).unwrap();
        let mut decoder = FrameDecoder::new();
        let mut got: Option<(u8, u16, HVec<u8, 320>)> = None;
        decoder.feed(&wire[..n], |res| {
            if let FrameResult::Ok { type_id, tag, payload } = res {
                let mut p = HVec::new();
                p.extend_from_slice(payload).unwrap();
                got = Some((type_id, tag, p));
            }
        });
        let (type_id, decoded_tag, payload) = got.unwrap();
        prop_assert_eq!(type_id, commands::TYPE_SET_CONFIG);
        prop_assert_eq!(decoded_tag, tag);
        prop_assert_eq!(Command::parse(type_id, &payload).unwrap(), cmd);
    }

    #[test]
    fn radio_chip_id_from_u16_matches_as_u16(v in any::<u16>()) {
        if let Some(id) = RadioChipId::from_u16(v) {
            prop_assert_eq!(id.as_u16(), v);
        }
    }
}