cat_dev/mion/proto/control/
mod.rs

1//! Protocols specifically for talking with the "control" port of the MION
2//! board.
3//!
4//! The main use case for talking to the control port is identifying which
5//! MIONs actually exist on your network, and getting basic information about
6//! them to then connect to them.
7
8mod announcement;
9mod errors;
10
11pub use announcement::*;
12pub use errors::*;
13
14use std::fmt::{Display, Formatter, Result as FmtResult};
15
16/// Used as a "Request" & "Response" code for a packet when talking with
17/// the MION Bridge.
18#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
19pub enum MionCommandByte {
20	Search,
21	Broadcast,
22	AnnounceYourselves,
23	AcknowledgeAnnouncement,
24}
25impl Display for MionCommandByte {
26	fn fmt(&self, fmt: &mut Formatter<'_>) -> FmtResult {
27		match *self {
28			Self::Search => write!(fmt, "Search(0x3f)"),
29			Self::Broadcast => write!(fmt, "Broadcast(0x21)"),
30			Self::AnnounceYourselves => write!(fmt, "AnnounceYourselves(0x2A)"),
31			Self::AcknowledgeAnnouncement => write!(fmt, "AcknowledgeAnnouncement(0x20)"),
32		}
33	}
34}
35impl TryFrom<u8> for MionCommandByte {
36	type Error = MionControlProtocolError;
37
38	fn try_from(value: u8) -> Result<Self, Self::Error> {
39		match value {
40			0x3F => Ok(Self::Search),
41			0x21 => Ok(Self::Broadcast),
42			0x2A => Ok(Self::AnnounceYourselves),
43			0x20 => Ok(Self::AcknowledgeAnnouncement),
44			_ => Err(MionControlProtocolError::UnknownCommand(value)),
45		}
46	}
47}
48impl From<MionCommandByte> for u8 {
49	fn from(value: MionCommandByte) -> Self {
50		match value {
51			MionCommandByte::Search => 0x3F,
52			MionCommandByte::Broadcast => 0x21,
53			MionCommandByte::AnnounceYourselves => 0x2A,
54			MionCommandByte::AcknowledgeAnnouncement => 0x20,
55		}
56	}
57}
58
59#[cfg(test)]
60mod unit_tests {
61	use super::*;
62
63	#[test]
64	pub fn ser_and_deser() {
65		for command_byte in vec![
66			MionCommandByte::Search,
67			MionCommandByte::Broadcast,
68			MionCommandByte::AnnounceYourselves,
69			MionCommandByte::AcknowledgeAnnouncement,
70		] {
71			assert_eq!(
72				command_byte,
73				MionCommandByte::try_from(u8::from(command_byte))
74					.expect("Failed to serialize/deserialize command byte: {command_byte}"),
75				"MionCommandByte was not the same after serializing, and deserializing."
76			);
77		}
78	}
79}