1#![no_std]
2#![deny(missing_docs)]
3#![doc = include_str!("../README.md")]
4
5extern crate alloc;
7use core::marker::PhantomData;
8
9use alloc::{collections::vec_deque::VecDeque, vec::Vec};
10
11use serde::{Deserialize, Serialize, de::DeserializeOwned};
12use thiserror::Error;
13
14pub mod messages;
16
17use crate::messages::{host_to_mote, mote_to_host};
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum Role {
22 Mote,
24 Host,
26}
27
28impl Role {
29 const fn other(self) -> Role {
30 match self {
31 Role::Mote => Role::Host,
32 Role::Host => Role::Mote,
33 }
34 }
35
36 pub const fn as_str(self) -> &'static str {
38 match self {
39 Role::Mote => "mote",
40 Role::Host => "host",
41 }
42 }
43}
44
45impl core::fmt::Display for Role {
46 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
47 write!(f, "{}", self.as_str())
48 }
49}
50
51mod sealed {
52 pub trait Sealed {}
53 impl Sealed for crate::messages::mote_to_host::Message {}
54 impl Sealed for crate::messages::host_to_mote::Message {}
55}
56
57pub trait MessageRole: sealed::Sealed {
61 const RECEIVER: Role;
63}
64
65impl MessageRole for mote_to_host::Message {
66 const RECEIVER: Role = Role::Host;
67}
68
69impl MessageRole for host_to_mote::Message {
70 const RECEIVER: Role = Role::Mote;
71}
72
73const VERSION_HEADER_LEN: usize = 6;
76
77#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
79pub struct Version {
80 pub major: u16,
82 pub minor: u16,
84 pub patch: u16,
86}
87
88impl Version {
89 pub const LOCAL: Version = Version {
91 major: parse_u16(env!("CARGO_PKG_VERSION_MAJOR")),
92 minor: parse_u16(env!("CARGO_PKG_VERSION_MINOR")),
93 patch: parse_u16(env!("CARGO_PKG_VERSION_PATCH")),
94 };
95
96 const fn to_wire_bytes(self) -> [u8; VERSION_HEADER_LEN] {
97 let [a0, a1] = self.major.to_le_bytes();
98 let [b0, b1] = self.minor.to_le_bytes();
99 let [c0, c1] = self.patch.to_le_bytes();
100 [a0, a1, b0, b1, c0, c1]
101 }
102
103 fn from_wire_bytes(bytes: [u8; VERSION_HEADER_LEN]) -> Self {
104 Self {
105 major: u16::from_le_bytes([bytes[0], bytes[1]]),
106 minor: u16::from_le_bytes([bytes[2], bytes[3]]),
107 patch: u16::from_le_bytes([bytes[4], bytes[5]]),
108 }
109 }
110
111 const fn breaking_key(self) -> (u16, u16, u16) {
114 if self.major != 0 {
115 (self.major, 0, 0)
116 } else if self.minor != 0 {
117 (0, self.minor, 0)
118 } else {
119 (0, 0, self.patch)
120 }
121 }
122
123 fn is_compatible_with(self, other: Version) -> bool {
124 self.breaking_key() == other.breaking_key()
125 }
126}
127
128impl core::fmt::Display for Version {
129 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
130 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
131 }
132}
133
134const fn parse_u16(s: &str) -> u16 {
137 let bytes = s.as_bytes();
138 let mut value: u16 = 0;
139 let mut i = 0;
140 while i < bytes.len() {
141 assert!(
142 bytes[i].is_ascii_digit(),
143 "CARGO_PKG_VERSION component must be decimal digits"
144 );
145 value = value * 10 + (bytes[i] - b'0') as u16;
146 i += 1;
147 }
148 value
149}
150
151#[derive(Error, Debug)]
153#[non_exhaustive]
154pub enum Error {
155 #[error("message decode failed: {0}")]
157 DecodeError(alloc::string::String),
158 #[error("Cobs pack/unpack failed")]
160 CobsError(corncobs::CobsError),
161 #[error("Message frame too short to contain a version header")]
163 MalformedHeader,
164 #[error(
167 "mote-api version mismatch: {local_role} is v{local}, {remote_role} is v{remote} — update {behind} to a compatible version"
168 )]
169 VersionMismatch {
170 local: Version,
172 remote: Version,
174 local_role: Role,
176 remote_role: Role,
178 behind: Role,
180 },
181}
182
183impl From<corncobs::CobsError> for Error {
184 fn from(value: corncobs::CobsError) -> Self {
185 Self::CobsError(value)
186 }
187}
188
189impl From<postcard::Error> for Error {
190 fn from(value: postcard::Error) -> Self {
191 use alloc::string::ToString;
192 Self::DecodeError(value.to_string())
193 }
194}
195
196fn to_slice<M>(message: &M) -> Result<Vec<u8>, Error>
198where
199 M: Serialize + ?Sized,
200{
201 let body = postcard::to_allocvec(message)?;
202 let mut plain_buf: Vec<u8> = Vec::with_capacity(VERSION_HEADER_LEN + body.len());
203 plain_buf.extend_from_slice(&Version::LOCAL.to_wire_bytes());
204 plain_buf.extend_from_slice(&body);
205
206 let encoded_size = corncobs::max_encoded_len(plain_buf.len());
207 let mut cobs_buff: Vec<u8> = Vec::with_capacity(encoded_size);
208 cobs_buff.resize(encoded_size, 10);
209 let encoded_size = corncobs::encode_buf(&plain_buf, &mut cobs_buff);
210 cobs_buff.truncate(encoded_size);
211
212 Ok(cobs_buff)
213}
214
215fn from_bytes<M>(bytes: &[u8]) -> Result<M, Error>
217where
218 M: DeserializeOwned + MessageRole,
219{
220 let mut cobs_buff: Vec<u8> = Vec::with_capacity(bytes.len());
221 cobs_buff.resize(bytes.len(), 10);
222 let decoded_size = corncobs::decode_buf(bytes, &mut cobs_buff)?;
223 cobs_buff.truncate(decoded_size);
224
225 if cobs_buff.len() < VERSION_HEADER_LEN {
226 return Err(Error::MalformedHeader);
227 }
228 let (header, body) = cobs_buff.split_at(VERSION_HEADER_LEN);
229 let remote = Version::from_wire_bytes(
230 header
231 .try_into()
232 .expect("split_at guarantees len == VERSION_HEADER_LEN"),
233 );
234
235 if !Version::LOCAL.is_compatible_with(remote) {
236 let local_role = M::RECEIVER;
237 let remote_role = local_role.other();
238 let behind = if Version::LOCAL.breaking_key() < remote.breaking_key() {
239 local_role
240 } else {
241 remote_role
242 };
243 return Err(Error::VersionMismatch {
244 local: Version::LOCAL,
245 remote,
246 local_role,
247 remote_role,
248 behind,
249 });
250 }
251
252 Ok(postcard::from_bytes::<M>(body)?)
253}
254
255const MAX_MESSAGE_LENGTH: usize = 5000;
257
258pub struct MoteComms<const MTU: usize, I, O>
266where
267 I: DeserializeOwned, O: Serialize, {
270 buffered_transmits: VecDeque<Vec<u8>>,
271 deserialization_buffer: VecDeque<u8>,
272
273 in_type: PhantomData<I>,
274 out_type: PhantomData<O>,
275}
276
277impl<const MTU: usize, I, O> core::fmt::Debug for MoteComms<MTU, I, O>
278where
279 I: DeserializeOwned,
280 O: Serialize,
281{
282 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
283 f.debug_struct("MoteComms")
284 .field("mtu", &MTU)
285 .field("buffered_transmits", &self.buffered_transmits.len())
286 .field("deserialization_buffer", &self.deserialization_buffer.len())
287 .finish()
288 }
289}
290
291impl<const MTU: usize, I, O> Default for MoteComms<MTU, I, O>
292where
293 I: for<'de> Deserialize<'de>, O: Serialize,
295{
296 fn default() -> Self {
297 Self::new()
298 }
299}
300
301impl<const MTU: usize, I, O> MoteComms<MTU, I, O>
302where
303 I: for<'de> Deserialize<'de>, O: Serialize, {
306 pub fn new() -> Self {
308 Self {
309 buffered_transmits: VecDeque::new(),
310 deserialization_buffer: VecDeque::new(),
311 in_type: PhantomData,
312 out_type: PhantomData,
313 }
314 }
315
316 pub fn send(&mut self, message: O) -> Result<(), Error> {
318 let encoded_bytes: Vec<u8> = to_slice(&message)?;
319
320 for chunk in encoded_bytes.chunks(MTU) {
322 self.buffered_transmits.push_back(Vec::from(chunk));
323 }
324
325 Ok(())
326 }
327
328 pub fn poll_transmit(&mut self) -> Option<Vec<u8>> {
330 self.buffered_transmits.pop_front()
331 }
332
333 pub fn handle_receive(&mut self, packet: &[u8]) {
335 packet.iter().for_each(|byte| {
338 self.deserialization_buffer.push_back(*byte);
339 if self.deserialization_buffer.len() > MAX_MESSAGE_LENGTH {
340 self.deserialization_buffer.pop_front();
341 }
342 });
343 }
344
345 pub fn poll_receive(&mut self) -> Result<Option<I>, Error>
347 where
348 I: MessageRole,
349 {
350 if let Some(end) = self.deserialization_buffer.iter().position(|&x| x == 0) {
351 let linear_buf: Vec<u8> = self.deserialization_buffer.drain(0..=end).collect();
352 match from_bytes::<I>(&linear_buf) {
353 Ok(msg) => Ok(Some(msg)),
354 Err(Error::CobsError(corncobs::CobsError::Truncated)) => {
355 Ok(None)
358 }
359 Err(other) => Err(other),
360 }
361 } else {
362 Ok(None)
364 }
365 }
366}
367
368pub type MoteLink = MoteComms<
370 1400, mote_to_host::Message,
372 host_to_mote::Message,
373>;
374
375pub type HostLink = MoteComms<
377 1400, host_to_mote::Message,
379 mote_to_host::Message,
380>;
381
382pub type MoteConfigLink = MoteComms<
384 64, mote_to_host::Message,
386 host_to_mote::Message,
387>;
388
389pub type HostConfigLink = MoteComms<
391 64, host_to_mote::Message,
393 mote_to_host::Message,
394>;
395
396#[cfg(test)]
397mod tests {
398 use super::*;
399 use alloc::{boxed::Box, string::String, vec};
400
401 fn all_mote_messages() -> Vec<mote_to_host::Message> {
403 vec![
404 mote_to_host::Message::Ping,
405 mote_to_host::Message::Pong,
406 mote_to_host::Message::Scan(vec![
407 mote_to_host::Point {
408 quality: 255,
409 angle_rad: 1.5707,
410 distance_mm: 500.0,
411 },
412 mote_to_host::Point {
413 quality: 0,
414 angle_rad: 0.0,
415 distance_mm: 0.0,
416 },
417 ]),
418 mote_to_host::Message::State(Box::new(mote_to_host::State {
419 uid: String::from("mote-test"),
420 ip: Some(String::from("192.168.1.100")),
421 mac: Some(String::from("aa:bb:cc:dd:ee:ff")),
422 current_network_connection: Some(Ok(String::from("MyWifi"))),
423 available_network_connections: vec![mote_to_host::NetworkConnection {
424 ssid: String::from("MyWifi"),
425 strength: 80,
426 }],
427 built_in_test: mote_to_host::BitCollection {
428 power: vec![mote_to_host::Bit {
429 name: String::from("battery"),
430 result: mote_to_host::BitResult::Pass,
431 }],
432 wifi: vec![],
433 lidar: vec![mote_to_host::Bit {
434 name: String::from("lidar_init"),
435 result: mote_to_host::BitResult::Waiting,
436 }],
437 imu: vec![],
438 encoders: vec![mote_to_host::Bit {
439 name: String::from("left_enc"),
440 result: mote_to_host::BitResult::Fail,
441 }],
442 },
443 })),
444 ]
445 }
446
447 fn all_host_messages() -> Vec<host_to_mote::Message> {
449 vec![
450 host_to_mote::Message::Ping,
451 host_to_mote::Message::Pong,
452 host_to_mote::Message::RequestNetworkScan,
453 host_to_mote::Message::SetNetworkConnectionConfig(
454 host_to_mote::SetNetworkConnectionConfig {
455 ssid: String::from("MyWifi"),
456 password: String::from("hunter2"),
457 },
458 ),
459 host_to_mote::Message::SetUid(host_to_mote::SetUid {
460 uid: String::from("mote-abc"),
461 }),
462 host_to_mote::Message::SetDriveBaseVelocity(host_to_mote::SetDriveBaseVelocity {
463 left_velocity_rad_per_s: 1.5,
464 right_velocity_rad_per_s: -1.5,
465 }),
466 ]
467 }
468
469 #[test]
472 fn test_encode_decode_failed_connection() -> Result<(), Error> {
473 let reasons = [
474 mote_to_host::ConnectionError::Timeout,
475 mote_to_host::ConnectionError::AuthOrRefused,
476 mote_to_host::ConnectionError::Other(String::from("radio hardware fault")),
477 ];
478 for reason in reasons {
479 let mut state = mote_to_host::State::default();
480 state.current_network_connection = Some(Err(reason));
481 let msg = mote_to_host::Message::State(alloc::boxed::Box::new(state));
482
483 let recv: mote_to_host::Message = from_bytes(&to_slice(&msg)?)?;
485 assert_eq!(msg, recv);
486
487 let mut host_l = HostConfigLink::new();
489 host_l.send(msg.clone())?;
490 let mut mote_l = MoteConfigLink::new();
491 while let Some(payload) = host_l.poll_transmit() {
492 mote_l.handle_receive(&payload);
493 }
494 assert_eq!(mote_l.poll_receive()?.unwrap(), msg);
495 }
496 Ok(())
497 }
498
499 #[test]
500 fn test_encode_decode_all_variants() -> Result<(), Error> {
501 for msg in all_mote_messages() {
502 let bytes = to_slice(&msg)?;
503 let recv: mote_to_host::Message = from_bytes(&bytes)?;
504 assert_eq!(msg, recv);
505 }
506 for msg in all_host_messages() {
507 let bytes = to_slice(&msg)?;
508 let recv: host_to_mote::Message = from_bytes(&bytes)?;
509 assert_eq!(msg, recv);
510 }
511 Ok(())
512 }
513
514 #[test]
517 fn test_poll_transmit_empty() {
518 let mut link = MoteLink::new();
519 assert!(link.poll_transmit().is_none());
520 }
521
522 #[test]
523 fn test_poll_receive_empty() -> Result<(), Error> {
524 let mut link = MoteLink::new();
525 assert!(link.poll_receive()?.is_none());
526 Ok(())
527 }
528
529 #[test]
532 fn test_default() -> Result<(), Error> {
533 let mut link: MoteLink = Default::default();
534 link.send(host_to_mote::Message::Ping)?;
535 assert!(link.poll_transmit().is_some());
536 Ok(())
537 }
538
539 #[test]
542 fn test_config_links() -> Result<(), Error> {
543 for msg in all_mote_messages() {
544 let mut host_l = HostConfigLink::new();
545 host_l.send(msg.clone())?;
546 let mut mote_l = MoteConfigLink::new();
547 while let Some(payload) = host_l.poll_transmit() {
548 mote_l.handle_receive(&payload);
549 }
550 assert_eq!(mote_l.poll_receive()?.unwrap(), msg);
551 }
552
553 for msg in all_host_messages() {
554 let mut mote_l = MoteConfigLink::new();
555 mote_l.send(msg.clone())?;
556 let mut host_l = HostConfigLink::new();
557 while let Some(payload) = mote_l.poll_transmit() {
558 host_l.handle_receive(&payload);
559 }
560 assert_eq!(host_l.poll_receive()?.unwrap(), msg);
561 }
562 Ok(())
563 }
564
565 #[test]
568 fn test_udp_links() -> Result<(), Error> {
569 for msg in all_mote_messages() {
570 let mut host_l = HostLink::new();
571 host_l.send(msg.clone())?;
572 let mut mote_l = MoteLink::new();
573 while let Some(payload) = host_l.poll_transmit() {
574 mote_l.handle_receive(&payload);
575 }
576 assert_eq!(mote_l.poll_receive()?.unwrap(), msg);
577 }
578
579 for msg in all_host_messages() {
580 let mut mote_l = MoteLink::new();
581 mote_l.send(msg.clone())?;
582 let mut host_l = HostLink::new();
583 while let Some(payload) = mote_l.poll_transmit() {
584 host_l.handle_receive(&payload);
585 }
586 assert_eq!(host_l.poll_receive()?.unwrap(), msg);
587 }
588 Ok(())
589 }
590
591 #[test]
594 fn test_fragmentation() -> Result<(), Error> {
595 let scan = mote_to_host::Message::Scan(
596 (0..100u8)
597 .map(|i| mote_to_host::Point {
598 quality: i,
599 angle_rad: i as f32 * 0.01,
600 distance_mm: i as f32 * 10.0,
601 })
602 .collect(),
603 );
604
605 let mut host_l = HostConfigLink::new(); host_l.send(scan.clone())?;
607
608 let mut packet_count = 0usize;
609 let mut mote_l = MoteConfigLink::new();
610 while let Some(payload) = host_l.poll_transmit() {
611 assert!(payload.len() <= 64, "packet exceeded MTU");
612 mote_l.handle_receive(&payload);
613 packet_count += 1;
614 }
615 assert!(
616 packet_count > 1,
617 "expected fragmentation into multiple packets"
618 );
619
620 assert_eq!(mote_l.poll_receive()?.unwrap(), scan);
621 Ok(())
622 }
623
624 #[test]
627 fn test_multiple_messages_in_order() -> Result<(), Error> {
628 let messages = [
629 host_to_mote::Message::Ping,
630 host_to_mote::Message::RequestNetworkScan,
631 host_to_mote::Message::Pong,
632 ];
633 let mut mote_l = MoteConfigLink::new();
634 let mut host_l = HostConfigLink::new();
635
636 for msg in &messages {
637 mote_l.send(msg.clone())?;
638 }
639 while let Some(payload) = mote_l.poll_transmit() {
640 host_l.handle_receive(&payload);
641 }
642 for expected in &messages {
643 assert_eq!(&host_l.poll_receive()?.unwrap(), expected);
644 }
645 assert!(host_l.poll_receive()?.is_none());
646 Ok(())
647 }
648
649 #[test]
652 fn test_truncated_cobs_produces_no_message() -> Result<(), Error> {
653 let mut link = MoteLink::new();
654 link.handle_receive(&[0xFF, 0xFE, 0xFD, 0x00]);
657 assert!(link.poll_receive()?.is_none());
658 Ok(())
659 }
660
661 #[test]
662 fn test_empty_cobs_payload_returns_error() {
663 let mut link = MoteLink::new();
664 link.handle_receive(&[0x01, 0x00]);
668 assert!(matches!(link.poll_receive(), Err(Error::MalformedHeader)));
669 }
670
671 #[test]
674 fn test_version_wire_roundtrip() {
675 for v in [
676 Version {
677 major: 0,
678 minor: 0,
679 patch: 0,
680 },
681 Version {
682 major: 1,
683 minor: 2,
684 patch: 3,
685 },
686 Version {
687 major: 65535,
688 minor: 65535,
689 patch: 65535,
690 },
691 ] {
692 assert_eq!(Version::from_wire_bytes(v.to_wire_bytes()), v);
693 }
694 }
695
696 #[test]
697 fn test_version_is_compatible_with() {
698 let v = |major, minor, patch| Version {
699 major,
700 minor,
701 patch,
702 };
703 let cases = [
704 (v(1, 2, 3), v(1, 9, 9), true),
705 (v(1, 2, 3), v(2, 0, 0), false),
706 (v(0, 3, 1), v(0, 3, 9), true),
707 (v(0, 3, 1), v(0, 4, 0), false),
708 (v(0, 0, 1), v(0, 0, 2), false),
709 (v(0, 0, 1), v(0, 0, 1), true),
710 ];
711 for (a, b, expected) in cases {
712 assert_eq!(
713 a.is_compatible_with(b),
714 expected,
715 "{a} vs {b} expected compatible={expected}"
716 );
717 }
718 }
719
720 fn encode_with_version(version: Version, message: &host_to_mote::Message) -> Vec<u8> {
724 let body = postcard::to_allocvec(message).unwrap();
725 let mut plain = Vec::with_capacity(VERSION_HEADER_LEN + body.len());
726 plain.extend_from_slice(&version.to_wire_bytes());
727 plain.extend_from_slice(&body);
728 let encoded_size = corncobs::max_encoded_len(plain.len());
729 let mut cobs_buf = vec![0u8; encoded_size];
730 let n = corncobs::encode_buf(&plain, &mut cobs_buf);
731 cobs_buf.truncate(n);
732 cobs_buf
733 }
734
735 #[test]
736 fn test_version_mismatch_detected() {
737 let mismatched = Version {
738 major: Version::LOCAL.major,
739 minor: Version::LOCAL.minor.wrapping_add(1),
740 patch: Version::LOCAL.patch,
741 };
742 let mut link = HostConfigLink::new();
743 link.handle_receive(&encode_with_version(
744 mismatched,
745 &host_to_mote::Message::Ping,
746 ));
747
748 match link.poll_receive() {
749 Err(Error::VersionMismatch {
750 local,
751 remote,
752 local_role,
753 remote_role,
754 ..
755 }) => {
756 assert_eq!(local, Version::LOCAL);
757 assert_eq!(remote, mismatched);
758 assert_eq!(local_role, Role::Mote);
759 assert_eq!(remote_role, Role::Host);
760 }
761 other => panic!("expected VersionMismatch, got {other:?}"),
762 }
763 }
764
765 #[test]
766 fn test_version_mismatch_does_not_strand_a_good_frame_behind_it() -> Result<(), Error> {
767 let mismatched = Version {
768 major: Version::LOCAL.major,
769 minor: Version::LOCAL.minor.wrapping_add(1),
770 patch: Version::LOCAL.patch,
771 };
772 let mut link = HostConfigLink::new();
773 link.handle_receive(&encode_with_version(
774 mismatched,
775 &host_to_mote::Message::Ping,
776 ));
777
778 let mut good = MoteConfigLink::new();
780 good.send(host_to_mote::Message::Pong)?;
781 while let Some(payload) = good.poll_transmit() {
782 link.handle_receive(&payload);
783 }
784
785 assert!(matches!(
786 link.poll_receive(),
787 Err(Error::VersionMismatch { .. })
788 ));
789 assert_eq!(link.poll_receive()?, Some(host_to_mote::Message::Pong));
790 Ok(())
791 }
792
793 #[test]
794 fn test_message_role_matches_link_direction() {
795 assert_eq!(<mote_to_host::Message as MessageRole>::RECEIVER, Role::Host);
796 assert_eq!(<host_to_mote::Message as MessageRole>::RECEIVER, Role::Mote);
797 }
798
799 #[test]
802 fn test_receive_buffer_overflow() -> Result<(), Error> {
803 let mut link = MoteLink::new();
804 let data = vec![0xABu8; MAX_MESSAGE_LENGTH + 500];
806 link.handle_receive(&data);
807 assert!(link.poll_receive()?.is_none());
809 Ok(())
810 }
811}