Skip to main content

industrial_protocols_most/
lib.rs

1// Copyright (c) 2026 erik <erik@erik.xyz> — https://erik.xyz
2//! # MOST — MOST 光纤多媒体协议。25/50/150 Mbps、控制消息+NetBlock 读取。
3
4//! MOST (Media Oriented Systems Transport) fiber optic protocol.
5//! 25/50/150 Mbps over POF. Requires MOST network interface controller.
6use industrial_protocols_kernel::connection::Connection;
7use industrial_protocols_kernel::error::{ProtocolError, Result};
8use industrial_protocols_kernel::sdk::*;
9
10pub struct MostProtocol {
11    pub node_addr: u16,
12}
13impl Default for MostProtocol {
14    fn default() -> Self {
15        Self::new()
16    }
17}
18
19impl MostProtocol {
20    pub fn new() -> Self {
21        MostProtocol { node_addr: 0x0100 }
22    }
23    pub fn addr(mut self, a: u16) -> Self {
24        self.node_addr = a;
25        self
26    }
27}
28
29// MOST25 frame: synchronous at 44.1 kHz, 64 bytes per frame
30// MOST150 frame: isochronous + packet data
31
32pub fn build_control_message(target: u16, fkt_id: u16, data: &[u8]) -> Vec<u8> {
33    let mut f = vec![0x01, 0x00]; // preamble
34    f.extend_from_slice(&target.to_be_bytes());
35    f.extend_from_slice(&fkt_id.to_be_bytes());
36    f.push(data.len() as u8);
37    f.extend_from_slice(data);
38    f
39}
40
41pub fn build_netblock_read(target: u16, offset: u32) -> Vec<u8> {
42    let mut f = vec![0x01, 0x02];
43    f.extend_from_slice(&target.to_be_bytes());
44    f.extend_from_slice(&offset.to_be_bytes());
45    f.extend_from_slice(&[0x00, 0x04]); // length
46    f
47}
48
49impl Protocol for MostProtocol {
50    fn name(&self) -> &'static str {
51        "most"
52    }
53    fn version(&self) -> &'static str {
54        "1.0.0"
55    }
56    fn category(&self) -> ProtocolCategory {
57        ProtocolCategory::AutomotiveBus
58    }
59    fn supported_variants(&self) -> &'static [&'static str] {
60        &["25", "50", "150"]
61    }
62}
63
64impl ProtocolRead for MostProtocol {
65    type Address = u32;
66    type Value = Vec<u8>;
67    fn read(&self, conn: &mut dyn Connection, addr: &Self::Address) -> Result<Self::Value> {
68        conn.send(&build_netblock_read(self.node_addr, *addr))
69            .map_err(ProtocolError::from)
70    }
71    fn read_batch(&self, c: &mut dyn Connection, a: &[Self::Address]) -> Result<Vec<Self::Value>> {
72        a.iter().map(|x| self.read(c, x)).collect()
73    }
74    fn read_range(
75        &self,
76        c: &mut dyn Connection,
77        s: &Self::Address,
78        n: u16,
79    ) -> Result<Vec<Self::Value>> {
80        (0..n).map(|_| self.read(c, s)).collect()
81    }
82}
83
84impl ProtocolHealth for MostProtocol {
85    fn health(&self, conn: &mut dyn Connection) -> Result<HealthStatus> {
86        let start = std::time::Instant::now();
87        match conn.send(&build_control_message(self.node_addr, 0x0101, &[])) {
88            Ok(_) => Ok(HealthStatus {
89                state: HealthState::Healthy,
90                latency_ms: start.elapsed().as_millis() as u64,
91                last_seen: std::time::Instant::now(),
92                details: "most control ok".into(),
93            }),
94            Err(e) => Ok(HealthStatus {
95                state: HealthState::Unhealthy,
96                latency_ms: 0,
97                last_seen: std::time::Instant::now(),
98                details: format!("{e}"),
99            }),
100        }
101    }
102}
103
104impl ProtocolDiagnostics for MostProtocol {
105    fn diagnostics(&self, _: &mut dyn Connection) -> Result<DiagnosticsReport> {
106        Ok(DiagnosticsReport {
107            device_id: format!("most:{}", self.node_addr),
108            uptime_secs: None,
109            error_count: 0,
110            last_error: None,
111            custom_fields: Default::default(),
112        })
113    }
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119    #[test]
120    fn test_ctrl() {
121        let f = build_control_message(0x100, 0x0101, &[]);
122        assert_eq!(f[0], 1);
123    }
124    #[test]
125    fn test_meta() {
126        assert_eq!(MostProtocol::new().name(), "most");
127    }
128}