Skip to main content

industrial_protocols_controlnet/
lib.rs

1// Copyright (c) 2026 erik <erik@erik.xyz> — https://erik.xyz
2//! # CONTROLNET — ControlNet 协议。5 Mbps 令牌传递、UCMM 非连接消息、需 1784-PCIC/S。
3
4//! ControlNet protocol via Allen-Bradley 1784-PCIC/S card.
5//! 5 Mbps, scheduled token-passing for real-time I/O.
6use industrial_protocols_kernel::connection::Connection;
7use industrial_protocols_kernel::error::{ProtocolError, Result};
8use industrial_protocols_kernel::sdk::*;
9
10pub struct ControlnetProtocol {
11    pub node: u8,
12}
13impl Default for ControlnetProtocol {
14    fn default() -> Self {
15        Self::new()
16    }
17}
18
19impl ControlnetProtocol {
20    pub fn new() -> Self {
21        ControlnetProtocol { node: 1 }
22    }
23    pub fn node(mut self, n: u8) -> Self {
24        self.node = n;
25        self
26    }
27}
28
29// ControlNet MAC frame: [Preamble 16B] [StartDelim 1B] [Source 1B] [Lpackets...] [CRC 2B] [EndDelim 1B]
30
31pub fn build_ucmm_read(node: u8, class: u16, instance: u16, attr: u16) -> Vec<u8> {
32    let mut f = vec![0xAA; 16];
33    f.push(0xAB); // preamble + start
34    f.push(node);
35    f.push(0x52); // UCMM Unconnected Send
36    f.extend_from_slice(&class.to_le_bytes());
37    f.extend_from_slice(&instance.to_le_bytes());
38    f.extend_from_slice(&attr.to_le_bytes());
39    f.push(0x00);
40    f.push(0x00); // CRC placeholder
41    f
42}
43
44impl Protocol for ControlnetProtocol {
45    fn name(&self) -> &'static str {
46        "controlnet"
47    }
48    fn version(&self) -> &'static str {
49        "1.0.0"
50    }
51    fn category(&self) -> ProtocolCategory {
52        ProtocolCategory::Fieldbus
53    }
54    fn supported_variants(&self) -> &'static [&'static str] {
55        &["1784-pcics"]
56    }
57}
58
59impl ProtocolRead for ControlnetProtocol {
60    type Address = u16;
61    type Value = u16;
62    fn read(&self, conn: &mut dyn Connection, addr: &Self::Address) -> Result<Self::Value> {
63        let class = *addr;
64        let instance = 1u16;
65        let attr = 1u16;
66        let f = build_ucmm_read(self.node, class, instance, attr);
67        let resp = conn.send(&f).map_err(ProtocolError::from)?;
68        Ok(if resp.len() >= 24 {
69            u16::from_le_bytes([resp[22], resp[23]])
70        } else {
71            0
72        })
73    }
74    fn read_batch(&self, c: &mut dyn Connection, a: &[Self::Address]) -> Result<Vec<Self::Value>> {
75        a.iter().map(|x| self.read(c, x)).collect()
76    }
77    fn read_range(
78        &self,
79        c: &mut dyn Connection,
80        s: &Self::Address,
81        n: u16,
82    ) -> Result<Vec<Self::Value>> {
83        (0..n).map(|_| self.read(c, s)).collect()
84    }
85}
86
87impl ProtocolHealth for ControlnetProtocol {
88    fn health(&self, conn: &mut dyn Connection) -> Result<HealthStatus> {
89        let start = std::time::Instant::now();
90        match conn.send(&build_ucmm_read(self.node, 0x01, 1, 1)) {
91            Ok(_) => Ok(HealthStatus {
92                state: HealthState::Healthy,
93                latency_ms: start.elapsed().as_millis() as u64,
94                last_seen: std::time::Instant::now(),
95                details: "controlnet ucmm ok".into(),
96            }),
97            Err(e) => Ok(HealthStatus {
98                state: HealthState::Unhealthy,
99                latency_ms: 0,
100                last_seen: std::time::Instant::now(),
101                details: format!("{e}"),
102            }),
103        }
104    }
105}
106
107impl ProtocolDiagnostics for ControlnetProtocol {
108    fn diagnostics(&self, _: &mut dyn Connection) -> Result<DiagnosticsReport> {
109        Ok(DiagnosticsReport {
110            device_id: format!("cn:node{}", self.node),
111            uptime_secs: None,
112            error_count: 0,
113            last_error: None,
114            custom_fields: Default::default(),
115        })
116    }
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122    #[test]
123    fn test_ucmm() {
124        let f = build_ucmm_read(1, 0x01, 1, 1);
125        assert_eq!(f[0], 0xAA);
126        assert_eq!(f[16], 0xAB);
127    }
128    #[test]
129    fn test_meta() {
130        assert_eq!(ControlnetProtocol::new().name(), "controlnet");
131    }
132}