industrial_protocols_interbus/
lib.rs1use industrial_protocols_kernel::connection::Connection;
7use industrial_protocols_kernel::error::{ProtocolError, Result};
8use industrial_protocols_kernel::sdk::*;
9
10pub struct InterbusProtocol {
11 pub slave_id: u8,
12}
13impl Default for InterbusProtocol {
14 fn default() -> Self {
15 Self::new()
16 }
17}
18
19impl InterbusProtocol {
20 pub fn new() -> Self {
21 InterbusProtocol { slave_id: 1 }
22 }
23 pub fn slave(mut self, id: u8) -> Self {
24 self.slave_id = id;
25 self
26 }
27}
28
29pub fn build_read_request(slave: u8, reg: u16) -> Vec<u8> {
33 vec![0x00, 0x01, slave, (reg >> 8) as u8, reg as u8, 0x00, 0x00]
34}
35
36pub fn build_write_request(slave: u8, reg: u16, data: &[u8]) -> Vec<u8> {
37 let mut f = vec![0x00, 0x02, slave, (reg >> 8) as u8, reg as u8];
38 f.push(data.len() as u8);
39 f.extend_from_slice(data);
40 f
41}
42
43impl Protocol for InterbusProtocol {
44 fn name(&self) -> &'static str {
45 "interbus"
46 }
47 fn version(&self) -> &'static str {
48 "1.0.0"
49 }
50 fn category(&self) -> ProtocolCategory {
51 ProtocolCategory::Fieldbus
52 }
53 fn supported_variants(&self) -> &'static [&'static str] {
54 &["ibs"]
55 }
56}
57
58impl ProtocolRead for InterbusProtocol {
59 type Address = u16;
60 type Value = Vec<u8>;
61 fn read(&self, conn: &mut dyn Connection, addr: &Self::Address) -> Result<Self::Value> {
62 conn.send(&build_read_request(self.slave_id, *addr))
63 .map_err(ProtocolError::from)
64 }
65 fn read_batch(&self, c: &mut dyn Connection, a: &[Self::Address]) -> Result<Vec<Self::Value>> {
66 a.iter().map(|x| self.read(c, x)).collect()
67 }
68 fn read_range(
69 &self,
70 c: &mut dyn Connection,
71 s: &Self::Address,
72 n: u16,
73 ) -> Result<Vec<Self::Value>> {
74 (0..n).map(|_| self.read(c, s)).collect()
75 }
76}
77
78impl ProtocolHealth for InterbusProtocol {
79 fn health(&self, conn: &mut dyn Connection) -> Result<HealthStatus> {
80 let start = std::time::Instant::now();
81 match self.read(conn, &0) {
82 Ok(_) => Ok(HealthStatus {
83 state: HealthState::Healthy,
84 latency_ms: start.elapsed().as_millis() as u64,
85 last_seen: std::time::Instant::now(),
86 details: "interbus read ok".into(),
87 }),
88 Err(e) => Ok(HealthStatus {
89 state: HealthState::Unhealthy,
90 latency_ms: 0,
91 last_seen: std::time::Instant::now(),
92 details: format!("{e}"),
93 }),
94 }
95 }
96}
97
98impl ProtocolDiagnostics for InterbusProtocol {
99 fn diagnostics(&self, _: &mut dyn Connection) -> Result<DiagnosticsReport> {
100 Ok(DiagnosticsReport {
101 device_id: format!("ibs:slave{}", self.slave_id),
102 uptime_secs: None,
103 error_count: 0,
104 last_error: None,
105 custom_fields: Default::default(),
106 })
107 }
108}
109
110#[cfg(test)]
111mod tests {
112 use super::*;
113 #[test]
114 fn test_read() {
115 let f = build_read_request(1, 0x100);
116 assert_eq!(f.len(), 7);
117 }
118 #[test]
119 fn test_meta() {
120 assert_eq!(InterbusProtocol::new().name(), "interbus");
121 }
122}