mote-api 0.2.0

Message and API definitions for communicating with Mote
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
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
#![no_std]
#![deny(missing_docs)]
#![doc = include_str!("../README.md")]

// I'd prefer to move away from alloc, but it's here for now.
extern crate alloc;
use core::marker::PhantomData;

use alloc::{collections::vec_deque::VecDeque, vec::Vec};

use serde::{Deserialize, Serialize, de::DeserializeOwned};
use thiserror::Error;

/// Message type definitions sent over the mote/host link.
pub mod messages;

use crate::messages::{host_to_mote, mote_to_host};

/// Which side of the mote/host link a piece of code represents.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Role {
    /// The embedded firmware side.
    Mote,
    /// The host driver side.
    Host,
}

impl Role {
    const fn other(self) -> Role {
        match self {
            Role::Mote => Role::Host,
            Role::Host => Role::Mote,
        }
    }

    /// Returns `"mote"` or `"host"`.
    pub const fn as_str(self) -> &'static str {
        match self {
            Role::Mote => "mote",
            Role::Host => "host",
        }
    }
}

impl core::fmt::Display for Role {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

mod sealed {
    pub trait Sealed {}
    impl Sealed for crate::messages::mote_to_host::Message {}
    impl Sealed for crate::messages::host_to_mote::Message {}
}

/// Identifies which side of the mote/host link decodes a given message type.
///
/// Sealed: only mote-api's own message types implement this.
pub trait MessageRole: sealed::Sealed {
    /// Which side receives (decodes) this message type.
    const RECEIVER: Role;
}

impl MessageRole for mote_to_host::Message {
    const RECEIVER: Role = Role::Host;
}

impl MessageRole for host_to_mote::Message {
    const RECEIVER: Role = Role::Mote;
}

/// The number of raw (non-postcard, non-serde) bytes reserved at the start of every
/// message frame for the version header.
const VERSION_HEADER_LEN: usize = 6;

/// The mote-api crate version embedded in every message header.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Version {
    /// Semver major component.
    pub major: u16,
    /// Semver minor component.
    pub minor: u16,
    /// Semver patch component.
    pub patch: u16,
}

impl Version {
    /// The version of the mote-api crate this binary was compiled against.
    pub const LOCAL: Version = Version {
        major: parse_u16(env!("CARGO_PKG_VERSION_MAJOR")),
        minor: parse_u16(env!("CARGO_PKG_VERSION_MINOR")),
        patch: parse_u16(env!("CARGO_PKG_VERSION_PATCH")),
    };

    const fn to_wire_bytes(self) -> [u8; VERSION_HEADER_LEN] {
        let [a0, a1] = self.major.to_le_bytes();
        let [b0, b1] = self.minor.to_le_bytes();
        let [c0, c1] = self.patch.to_le_bytes();
        [a0, a1, b0, b1, c0, c1]
    }

    fn from_wire_bytes(bytes: [u8; VERSION_HEADER_LEN]) -> Self {
        Self {
            major: u16::from_le_bytes([bytes[0], bytes[1]]),
            minor: u16::from_le_bytes([bytes[2], bytes[3]]),
            patch: u16::from_le_bytes([bytes[4], bytes[5]]),
        }
    }

    /// The (major, minor, patch) key that must match exactly for two versions to be
    /// considered wire-compatible, per semver's caret-compatibility rules.
    const fn breaking_key(self) -> (u16, u16, u16) {
        if self.major != 0 {
            (self.major, 0, 0)
        } else if self.minor != 0 {
            (0, self.minor, 0)
        } else {
            (0, 0, self.patch)
        }
    }

    fn is_compatible_with(self, other: Version) -> bool {
        self.breaking_key() == other.breaking_key()
    }
}

impl core::fmt::Display for Version {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
    }
}

/// Parses a decimal digit string (as produced by Cargo's `CARGO_PKG_VERSION_*` env
/// vars) into a `u16`, at compile time.
const fn parse_u16(s: &str) -> u16 {
    let bytes = s.as_bytes();
    let mut value: u16 = 0;
    let mut i = 0;
    while i < bytes.len() {
        assert!(
            bytes[i].is_ascii_digit(),
            "CARGO_PKG_VERSION component must be decimal digits"
        );
        value = value * 10 + (bytes[i] - b'0') as u16;
        i += 1;
    }
    value
}

/// Error type
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
    /// The message body failed to encode or decode.
    #[error("message decode failed: {0}")]
    DecodeError(alloc::string::String),
    /// COBS framing failed to encode or decode.
    #[error("Cobs pack/unpack failed")]
    CobsError(corncobs::CobsError),
    /// The frame was too short to contain a version header.
    #[error("Message frame too short to contain a version header")]
    MalformedHeader,
    /// The sender and receiver are running incompatible mote-api versions;
    /// the frame was rejected without attempting to decode it.
    #[error(
        "mote-api version mismatch: {local_role} is v{local}, {remote_role} is v{remote} — update {behind} to a compatible version"
    )]
    VersionMismatch {
        /// This side's mote-api version.
        local: Version,
        /// The other side's mote-api version, read from the frame header.
        remote: Version,
        /// Which side `local` is.
        local_role: Role,
        /// Which side `remote` is.
        remote_role: Role,
        /// Which side is on the older version and needs updating.
        behind: Role,
    },
}

impl From<corncobs::CobsError> for Error {
    fn from(value: corncobs::CobsError) -> Self {
        Self::CobsError(value)
    }
}

impl From<postcard::Error> for Error {
    fn from(value: postcard::Error) -> Self {
        use alloc::string::ToString;
        Self::DecodeError(value.to_string())
    }
}

/// Implements encoding of message types.
fn to_slice<M>(message: &M) -> Result<Vec<u8>, Error>
where
    M: Serialize + ?Sized,
{
    let body = postcard::to_allocvec(message)?;
    let mut plain_buf: Vec<u8> = Vec::with_capacity(VERSION_HEADER_LEN + body.len());
    plain_buf.extend_from_slice(&Version::LOCAL.to_wire_bytes());
    plain_buf.extend_from_slice(&body);

    let encoded_size = corncobs::max_encoded_len(plain_buf.len());
    let mut cobs_buff: Vec<u8> = Vec::with_capacity(encoded_size);
    cobs_buff.resize(encoded_size, 10);
    let encoded_size = corncobs::encode_buf(&plain_buf, &mut cobs_buff);
    cobs_buff.truncate(encoded_size);

    Ok(cobs_buff)
}

/// Implements decoding of message types.
fn from_bytes<M>(bytes: &[u8]) -> Result<M, Error>
where
    M: DeserializeOwned + MessageRole,
{
    let mut cobs_buff: Vec<u8> = Vec::with_capacity(bytes.len());
    cobs_buff.resize(bytes.len(), 10);
    let decoded_size = corncobs::decode_buf(bytes, &mut cobs_buff)?;
    cobs_buff.truncate(decoded_size);

    if cobs_buff.len() < VERSION_HEADER_LEN {
        return Err(Error::MalformedHeader);
    }
    let (header, body) = cobs_buff.split_at(VERSION_HEADER_LEN);
    let remote = Version::from_wire_bytes(
        header
            .try_into()
            .expect("split_at guarantees len == VERSION_HEADER_LEN"),
    );

    if !Version::LOCAL.is_compatible_with(remote) {
        let local_role = M::RECEIVER;
        let remote_role = local_role.other();
        let behind = if Version::LOCAL.breaking_key() < remote.breaking_key() {
            local_role
        } else {
            remote_role
        };
        return Err(Error::VersionMismatch {
            local: Version::LOCAL,
            remote,
            local_role,
            remote_role,
            behind,
        });
    }

    Ok(postcard::from_bytes::<M>(body)?)
}

// Sets the capacity for the deserialization ringbuffer
const MAX_MESSAGE_LENGTH: usize = 5000;

/// Bidirectional SansIO communication link betweek mote and the host.
///
/// You probably do not want to directly construct this. Instead, use the type aliases:
/// MoteLink (use on host)
/// HostLink (use on mote)
/// MoteConfigLink
/// HostConfigLink
pub struct MoteComms<const MTU: usize, I, O>
where
    I: DeserializeOwned, // Input type
    O: Serialize,        // Output type
{
    buffered_transmits: VecDeque<Vec<u8>>,
    deserialization_buffer: VecDeque<u8>,

    in_type: PhantomData<I>,
    out_type: PhantomData<O>,
}

impl<const MTU: usize, I, O> core::fmt::Debug for MoteComms<MTU, I, O>
where
    I: DeserializeOwned,
    O: Serialize,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("MoteComms")
            .field("mtu", &MTU)
            .field("buffered_transmits", &self.buffered_transmits.len())
            .field("deserialization_buffer", &self.deserialization_buffer.len())
            .finish()
    }
}

impl<const MTU: usize, I, O> Default for MoteComms<MTU, I, O>
where
    I: for<'de> Deserialize<'de>, // Input type
    O: Serialize,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<const MTU: usize, I, O> MoteComms<MTU, I, O>
where
    I: for<'de> Deserialize<'de>, // Input type
    O: Serialize,                 // Output type
{
    /// Generate a new link
    pub fn new() -> Self {
        Self {
            buffered_transmits: VecDeque::new(),
            deserialization_buffer: VecDeque::new(),
            in_type: PhantomData,
            out_type: PhantomData,
        }
    }

    /// Queue a message to be sent
    pub fn send(&mut self, message: O) -> Result<(), Error> {
        let encoded_bytes: Vec<u8> = to_slice(&message)?;

        // Break message into packets given the MTU
        for chunk in encoded_bytes.chunks(MTU) {
            self.buffered_transmits.push_back(Vec::from(chunk));
        }

        Ok(())
    }

    /// Get the next packet to be sent
    pub fn poll_transmit(&mut self) -> Option<Vec<u8>> {
        self.buffered_transmits.pop_front()
    }

    /// Receive a message from raw bytes
    pub fn handle_receive(&mut self, packet: &[u8]) {
        // Push the received bytes into the serialization buffer, potentially dropping the first
        // value if the buffer is full
        packet.iter().for_each(|byte| {
            self.deserialization_buffer.push_back(*byte);
            if self.deserialization_buffer.len() > MAX_MESSAGE_LENGTH {
                self.deserialization_buffer.pop_front();
            }
        });
    }

    /// Poll for new messages in the recv buffer
    pub fn poll_receive(&mut self) -> Result<Option<I>, Error>
    where
        I: MessageRole,
    {
        if let Some(end) = self.deserialization_buffer.iter().position(|&x| x == 0) {
            let linear_buf: Vec<u8> = self.deserialization_buffer.drain(0..=end).collect();
            match from_bytes::<I>(&linear_buf) {
                Ok(msg) => Ok(Some(msg)),
                Err(Error::CobsError(corncobs::CobsError::Truncated)) => {
                    // We checked for this in the if above, so it shouldn't happen.
                    // But it isn't an error.
                    Ok(None)
                }
                Err(other) => Err(other),
            }
        } else {
            // No end byte = no message
            Ok(None)
        }
    }
}

/// Used by the host to send commands to and receive data from Mote
pub type MoteLink = MoteComms<
    1400, // UDP MTU(ish)
    mote_to_host::Message,
    host_to_mote::Message,
>;

/// Used by Mote to send data to and receive commands from the host
pub type HostLink = MoteComms<
    1400, // UDP MTU(ish)
    host_to_mote::Message,
    mote_to_host::Message,
>;

/// Used by the host to send commands to and receive data from Mote
pub type MoteConfigLink = MoteComms<
    64, // Serial MTU
    mote_to_host::Message,
    host_to_mote::Message,
>;

/// Used by Mote to send data to and receive commands from the host
pub type HostConfigLink = MoteComms<
    64, // Serial MTU
    host_to_mote::Message,
    mote_to_host::Message,
>;

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::{boxed::Box, string::String, vec};

    // Returns all mote_to_host message variants
    fn all_mote_messages() -> Vec<mote_to_host::Message> {
        vec![
            mote_to_host::Message::Ping,
            mote_to_host::Message::Pong,
            mote_to_host::Message::Scan(vec![
                mote_to_host::Point {
                    quality: 255,
                    angle_rad: 1.5707,
                    distance_mm: 500.0,
                },
                mote_to_host::Point {
                    quality: 0,
                    angle_rad: 0.0,
                    distance_mm: 0.0,
                },
            ]),
            mote_to_host::Message::State(Box::new(mote_to_host::State {
                uid: String::from("mote-test"),
                ip: Some(String::from("192.168.1.100")),
                mac: Some(String::from("aa:bb:cc:dd:ee:ff")),
                current_network_connection: Some(Ok(String::from("MyWifi"))),
                available_network_connections: vec![mote_to_host::NetworkConnection {
                    ssid: String::from("MyWifi"),
                    strength: 80,
                }],
                built_in_test: mote_to_host::BitCollection {
                    power: vec![mote_to_host::Bit {
                        name: String::from("battery"),
                        result: mote_to_host::BitResult::Pass,
                    }],
                    wifi: vec![],
                    lidar: vec![mote_to_host::Bit {
                        name: String::from("lidar_init"),
                        result: mote_to_host::BitResult::Waiting,
                    }],
                    imu: vec![],
                    encoders: vec![mote_to_host::Bit {
                        name: String::from("left_enc"),
                        result: mote_to_host::BitResult::Fail,
                    }],
                },
            })),
        ]
    }

    // Returns all host_to_mote message variants.
    fn all_host_messages() -> Vec<host_to_mote::Message> {
        vec![
            host_to_mote::Message::Ping,
            host_to_mote::Message::Pong,
            host_to_mote::Message::RequestNetworkScan,
            host_to_mote::Message::SetNetworkConnectionConfig(
                host_to_mote::SetNetworkConnectionConfig {
                    ssid: String::from("MyWifi"),
                    password: String::from("hunter2"),
                },
            ),
            host_to_mote::Message::SetUid(host_to_mote::SetUid {
                uid: String::from("mote-abc"),
            }),
            host_to_mote::Message::SetDriveBaseVelocity(host_to_mote::SetDriveBaseVelocity {
                left_velocity_rad_per_s: 1.5,
                right_velocity_rad_per_s: -1.5,
            }),
        ]
    }

    // --- encode / decode ---

    #[test]
    fn test_encode_decode_failed_connection() -> Result<(), Error> {
        let reasons = [
            mote_to_host::ConnectionError::Timeout,
            mote_to_host::ConnectionError::AuthOrRefused,
            mote_to_host::ConnectionError::Other(String::from("radio hardware fault")),
        ];
        for reason in reasons {
            let mut state = mote_to_host::State::default();
            state.current_network_connection = Some(Err(reason));
            let msg = mote_to_host::Message::State(alloc::boxed::Box::new(state));

            // Direct codec round-trip.
            let recv: mote_to_host::Message = from_bytes(&to_slice(&msg)?)?;
            assert_eq!(msg, recv);

            // Full serial-link round-trip (mote -> host) with MTU-64 fragmentation.
            let mut host_l = HostConfigLink::new();
            host_l.send(msg.clone())?;
            let mut mote_l = MoteConfigLink::new();
            while let Some(payload) = host_l.poll_transmit() {
                mote_l.handle_receive(&payload);
            }
            assert_eq!(mote_l.poll_receive()?.unwrap(), msg);
        }
        Ok(())
    }

    #[test]
    fn test_encode_decode_all_variants() -> Result<(), Error> {
        for msg in all_mote_messages() {
            let bytes = to_slice(&msg)?;
            let recv: mote_to_host::Message = from_bytes(&bytes)?;
            assert_eq!(msg, recv);
        }
        for msg in all_host_messages() {
            let bytes = to_slice(&msg)?;
            let recv: host_to_mote::Message = from_bytes(&bytes)?;
            assert_eq!(msg, recv);
        }
        Ok(())
    }

    // --- poll_transmit / poll_receive on empty state ---

    #[test]
    fn test_poll_transmit_empty() {
        let mut link = MoteLink::new();
        assert!(link.poll_transmit().is_none());
    }

    #[test]
    fn test_poll_receive_empty() -> Result<(), Error> {
        let mut link = MoteLink::new();
        assert!(link.poll_receive()?.is_none());
        Ok(())
    }

    // --- Default::default() ---

    #[test]
    fn test_default() -> Result<(), Error> {
        let mut link: MoteLink = Default::default();
        link.send(host_to_mote::Message::Ping)?;
        assert!(link.poll_transmit().is_some());
        Ok(())
    }

    // --- config link round-trips (all variants) ---

    #[test]
    fn test_config_links() -> Result<(), Error> {
        for msg in all_mote_messages() {
            let mut host_l = HostConfigLink::new();
            host_l.send(msg.clone())?;
            let mut mote_l = MoteConfigLink::new();
            while let Some(payload) = host_l.poll_transmit() {
                mote_l.handle_receive(&payload);
            }
            assert_eq!(mote_l.poll_receive()?.unwrap(), msg);
        }

        for msg in all_host_messages() {
            let mut mote_l = MoteConfigLink::new();
            mote_l.send(msg.clone())?;
            let mut host_l = HostConfigLink::new();
            while let Some(payload) = mote_l.poll_transmit() {
                host_l.handle_receive(&payload);
            }
            assert_eq!(host_l.poll_receive()?.unwrap(), msg);
        }
        Ok(())
    }

    // --- UDP link round-trips (all variants) ---

    #[test]
    fn test_udp_links() -> Result<(), Error> {
        for msg in all_mote_messages() {
            let mut host_l = HostLink::new();
            host_l.send(msg.clone())?;
            let mut mote_l = MoteLink::new();
            while let Some(payload) = host_l.poll_transmit() {
                mote_l.handle_receive(&payload);
            }
            assert_eq!(mote_l.poll_receive()?.unwrap(), msg);
        }

        for msg in all_host_messages() {
            let mut mote_l = MoteLink::new();
            mote_l.send(msg.clone())?;
            let mut host_l = HostLink::new();
            while let Some(payload) = mote_l.poll_transmit() {
                host_l.handle_receive(&payload);
            }
            assert_eq!(host_l.poll_receive()?.unwrap(), msg);
        }
        Ok(())
    }

    // --- Fragmentation: large message split across MTU=64 packets ---

    #[test]
    fn test_fragmentation() -> Result<(), Error> {
        let scan = mote_to_host::Message::Scan(
            (0..100u8)
                .map(|i| mote_to_host::Point {
                    quality: i,
                    angle_rad: i as f32 * 0.01,
                    distance_mm: i as f32 * 10.0,
                })
                .collect(),
        );

        let mut host_l = HostConfigLink::new(); // MTU = 64
        host_l.send(scan.clone())?;

        let mut packet_count = 0usize;
        let mut mote_l = MoteConfigLink::new();
        while let Some(payload) = host_l.poll_transmit() {
            assert!(payload.len() <= 64, "packet exceeded MTU");
            mote_l.handle_receive(&payload);
            packet_count += 1;
        }
        assert!(
            packet_count > 1,
            "expected fragmentation into multiple packets"
        );

        assert_eq!(mote_l.poll_receive()?.unwrap(), scan);
        Ok(())
    }

    // --- Multiple messages received in order ---

    #[test]
    fn test_multiple_messages_in_order() -> Result<(), Error> {
        let messages = [
            host_to_mote::Message::Ping,
            host_to_mote::Message::RequestNetworkScan,
            host_to_mote::Message::Pong,
        ];
        let mut mote_l = MoteConfigLink::new();
        let mut host_l = HostConfigLink::new();

        for msg in &messages {
            mote_l.send(msg.clone())?;
        }
        while let Some(payload) = mote_l.poll_transmit() {
            host_l.handle_receive(&payload);
        }
        for expected in &messages {
            assert_eq!(&host_l.poll_receive()?.unwrap(), expected);
        }
        assert!(host_l.poll_receive()?.is_none());
        Ok(())
    }

    // --- Bad data in the receive buffer ---

    #[test]
    fn test_truncated_cobs_produces_no_message() -> Result<(), Error> {
        let mut link = MoteLink::new();
        // First byte 0xFF tells COBS to skip 254 more bytes, but the packet ends
        // after three bytes — corncobs returns Truncated, which maps to Ok(None).
        link.handle_receive(&[0xFF, 0xFE, 0xFD, 0x00]);
        assert!(link.poll_receive()?.is_none());
        Ok(())
    }

    #[test]
    fn test_empty_cobs_payload_returns_error() {
        let mut link = MoteLink::new();
        // [0x01, 0x00] is a valid COBS frame (overhead byte 0x01 = no data, then
        // terminator), but the empty decoded payload is too short to even contain a
        // version header — this returns MalformedHeader before bitcode ever runs.
        link.handle_receive(&[0x01, 0x00]);
        assert!(matches!(link.poll_receive(), Err(Error::MalformedHeader)));
    }

    // --- Version header ---

    #[test]
    fn test_version_wire_roundtrip() {
        for v in [
            Version {
                major: 0,
                minor: 0,
                patch: 0,
            },
            Version {
                major: 1,
                minor: 2,
                patch: 3,
            },
            Version {
                major: 65535,
                minor: 65535,
                patch: 65535,
            },
        ] {
            assert_eq!(Version::from_wire_bytes(v.to_wire_bytes()), v);
        }
    }

    #[test]
    fn test_version_is_compatible_with() {
        let v = |major, minor, patch| Version {
            major,
            minor,
            patch,
        };
        let cases = [
            (v(1, 2, 3), v(1, 9, 9), true),
            (v(1, 2, 3), v(2, 0, 0), false),
            (v(0, 3, 1), v(0, 3, 9), true),
            (v(0, 3, 1), v(0, 4, 0), false),
            (v(0, 0, 1), v(0, 0, 2), false),
            (v(0, 0, 1), v(0, 0, 1), true),
        ];
        for (a, b, expected) in cases {
            assert_eq!(
                a.is_compatible_with(b),
                expected,
                "{a} vs {b} expected compatible={expected}"
            );
        }
    }

    /// Hand-encodes a frame with an arbitrary (possibly non-LOCAL) version header,
    /// bypassing `to_slice`'s use of `Version::LOCAL`, so mismatch behavior can be
    /// tested directly.
    fn encode_with_version(version: Version, message: &host_to_mote::Message) -> Vec<u8> {
        let body = postcard::to_allocvec(message).unwrap();
        let mut plain = Vec::with_capacity(VERSION_HEADER_LEN + body.len());
        plain.extend_from_slice(&version.to_wire_bytes());
        plain.extend_from_slice(&body);
        let encoded_size = corncobs::max_encoded_len(plain.len());
        let mut cobs_buf = vec![0u8; encoded_size];
        let n = corncobs::encode_buf(&plain, &mut cobs_buf);
        cobs_buf.truncate(n);
        cobs_buf
    }

    #[test]
    fn test_version_mismatch_detected() {
        let mismatched = Version {
            major: Version::LOCAL.major,
            minor: Version::LOCAL.minor.wrapping_add(1),
            patch: Version::LOCAL.patch,
        };
        let mut link = HostConfigLink::new();
        link.handle_receive(&encode_with_version(
            mismatched,
            &host_to_mote::Message::Ping,
        ));

        match link.poll_receive() {
            Err(Error::VersionMismatch {
                local,
                remote,
                local_role,
                remote_role,
                ..
            }) => {
                assert_eq!(local, Version::LOCAL);
                assert_eq!(remote, mismatched);
                assert_eq!(local_role, Role::Mote);
                assert_eq!(remote_role, Role::Host);
            }
            other => panic!("expected VersionMismatch, got {other:?}"),
        }
    }

    #[test]
    fn test_version_mismatch_does_not_strand_a_good_frame_behind_it() -> Result<(), Error> {
        let mismatched = Version {
            major: Version::LOCAL.major,
            minor: Version::LOCAL.minor.wrapping_add(1),
            patch: Version::LOCAL.patch,
        };
        let mut link = HostConfigLink::new();
        link.handle_receive(&encode_with_version(
            mismatched,
            &host_to_mote::Message::Ping,
        ));

        // A normally-encoded (LOCAL-versioned) good frame appended right behind it.
        let mut good = MoteConfigLink::new();
        good.send(host_to_mote::Message::Pong)?;
        while let Some(payload) = good.poll_transmit() {
            link.handle_receive(&payload);
        }

        assert!(matches!(
            link.poll_receive(),
            Err(Error::VersionMismatch { .. })
        ));
        assert_eq!(link.poll_receive()?, Some(host_to_mote::Message::Pong));
        Ok(())
    }

    #[test]
    fn test_message_role_matches_link_direction() {
        assert_eq!(<mote_to_host::Message as MessageRole>::RECEIVER, Role::Host);
        assert_eq!(<host_to_mote::Message as MessageRole>::RECEIVER, Role::Mote);
    }

    // --- Receive buffer is capped at MAX_MESSAGE_LENGTH ---

    #[test]
    fn test_receive_buffer_overflow() -> Result<(), Error> {
        let mut link = MoteLink::new();
        // Feed more bytes than MAX_MESSAGE_LENGTH with no terminator.
        let data = vec![0xABu8; MAX_MESSAGE_LENGTH + 500];
        link.handle_receive(&data);
        // No zero byte in the buffer so poll_receive returns None, not an error.
        assert!(link.poll_receive()?.is_none());
        Ok(())
    }
}