Skip to main content

industrial_protocols_iolink/
lib.rs

1// Copyright (c) 2026 erik <erik@erik.xyz> — https://erik.xyz
2//! # IOLINK — IO-Link 协议。点对点串行通信、PDin/PDout 过程数据、ISDU 参数读写。
3
4//! IO-Link protocol via ifm/Balluff IO-Link Master gateway.
5//! Point-to-point serial communication at 4.8/38.4/230.4 kbps.
6use industrial_protocols_kernel::connection::Connection;
7use industrial_protocols_kernel::error::{ProtocolError, Result};
8use industrial_protocols_kernel::sdk::*;
9
10pub struct IolinkProtocol {
11    pub port: u8,
12    pub master_host: String,
13}
14impl Default for IolinkProtocol {
15    fn default() -> Self {
16        Self::new()
17    }
18}
19
20impl IolinkProtocol {
21    pub fn new() -> Self {
22        IolinkProtocol {
23            port: 1,
24            master_host: "192.168.1.1".into(),
25        }
26    }
27    pub fn port(mut self, p: u8) -> Self {
28        self.port = p;
29        self
30    }
31}
32
33// IO-Link frame via master TCP gateway:
34// [Channel 1B] [Service 1B] [Index 2B] [Subindex 1B] [Data nB]
35
36pub fn build_read_pdin(port: u8) -> Vec<u8> {
37    vec![port, 0x48, 0x00, 0x00, 0x00]
38}
39
40pub fn build_read_param(port: u8, index: u16, subindex: u8) -> Vec<u8> {
41    vec![port, 0x43, (index >> 8) as u8, index as u8, subindex]
42}
43
44pub fn build_write_param(port: u8, index: u16, subindex: u8, data: &[u8]) -> Vec<u8> {
45    let mut f = vec![port, 0x43, (index >> 8) as u8, index as u8, subindex];
46    f.extend_from_slice(data);
47    f
48}
49
50impl Protocol for IolinkProtocol {
51    fn name(&self) -> &'static str {
52        "iolink"
53    }
54    fn version(&self) -> &'static str {
55        "1.0.0"
56    }
57    fn category(&self) -> ProtocolCategory {
58        ProtocolCategory::Fieldbus
59    }
60    fn supported_variants(&self) -> &'static [&'static str] {
61        &["com1", "com2", "com3"]
62    }
63}
64
65impl ProtocolRead for IolinkProtocol {
66    type Address = u16;
67    type Value = Vec<u8>;
68    fn read(&self, conn: &mut dyn Connection, addr: &Self::Address) -> Result<Self::Value> {
69        let index = *addr;
70        let subidx = 0u8;
71        let f = build_read_param(self.port, index, subidx);
72        conn.send(&f).map_err(ProtocolError::from)
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 ProtocolWrite for IolinkProtocol {
88    type Address = u16;
89    type Value = Vec<u8>;
90    fn write(
91        &self,
92        conn: &mut dyn Connection,
93        addr: &Self::Address,
94        value: &Self::Value,
95    ) -> Result<()> {
96        let f = build_write_param(self.port, *addr, 0, value);
97        conn.send(&f).map_err(ProtocolError::from)?;
98        Ok(())
99    }
100    fn write_batch(
101        &self,
102        c: &mut dyn Connection,
103        i: &[(Self::Address, Self::Value)],
104    ) -> Result<()> {
105        for (a, v) in i {
106            self.write(c, a, v)?;
107        }
108        Ok(())
109    }
110}
111
112impl ProtocolHealth for IolinkProtocol {
113    fn health(&self, conn: &mut dyn Connection) -> Result<HealthStatus> {
114        let start = std::time::Instant::now();
115        match conn.send(&build_read_pdin(self.port)) {
116            Ok(_) => Ok(HealthStatus {
117                state: HealthState::Healthy,
118                latency_ms: start.elapsed().as_millis() as u64,
119                last_seen: std::time::Instant::now(),
120                details: "iolink PDin ok".into(),
121            }),
122            Err(e) => Ok(HealthStatus {
123                state: HealthState::Unhealthy,
124                latency_ms: 0,
125                last_seen: std::time::Instant::now(),
126                details: format!("{e}"),
127            }),
128        }
129    }
130}
131
132impl ProtocolDiagnostics for IolinkProtocol {
133    fn diagnostics(&self, _: &mut dyn Connection) -> Result<DiagnosticsReport> {
134        Ok(DiagnosticsReport {
135            device_id: format!("iolink:port{}", self.port),
136            uptime_secs: None,
137            error_count: 0,
138            last_error: None,
139            custom_fields: Default::default(),
140        })
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147    #[test]
148    fn test_pdin() {
149        let f = build_read_pdin(1);
150        assert_eq!(f[0], 1);
151        assert_eq!(f[1], 0x48);
152    }
153    #[test]
154    fn test_meta() {
155        assert_eq!(IolinkProtocol::new().name(), "iolink");
156    }
157}