industrial_protocols_lightbus/
lib.rs1use industrial_protocols_kernel::connection::Connection;
7use industrial_protocols_kernel::error::{ProtocolError, Result};
8use industrial_protocols_kernel::sdk::*;
9
10pub struct LightbusProtocol {
11 pub slave_id: u16,
12}
13impl Default for LightbusProtocol {
14 fn default() -> Self {
15 Self::new()
16 }
17}
18
19impl LightbusProtocol {
20 pub fn new() -> Self {
21 LightbusProtocol { slave_id: 1 }
22 }
23 pub fn slave(mut self, id: u16) -> Self {
24 self.slave_id = id;
25 self
26 }
27}
28
29pub fn build_read_register(slave: u16, reg: u16, len: u8) -> Vec<u8> {
32 let mut f = vec![0x02, (slave >> 8) as u8, slave as u8, 0x03, len];
33 f.extend_from_slice(®.to_le_bytes());
34 f.push(0x00);
35 f.push(0x00); f
37}
38
39pub fn build_write_register(slave: u16, reg: u16, data: &[u8]) -> Vec<u8> {
40 let mut f = vec![
41 0x02,
42 (slave >> 8) as u8,
43 slave as u8,
44 0x04,
45 data.len() as u8,
46 ];
47 f.extend_from_slice(®.to_le_bytes());
48 f.extend_from_slice(data);
49 f.push(0x00);
50 f.push(0x00);
51 f
52}
53
54impl Protocol for LightbusProtocol {
55 fn name(&self) -> &'static str {
56 "lightbus"
57 }
58 fn version(&self) -> &'static str {
59 "1.0.0"
60 }
61 fn category(&self) -> ProtocolCategory {
62 ProtocolCategory::HardwareBridge
63 }
64 fn supported_variants(&self) -> &'static [&'static str] {
65 &["ring"]
66 }
67}
68
69impl ProtocolRead for LightbusProtocol {
70 type Address = u16;
71 type Value = u16;
72 fn read(&self, conn: &mut dyn Connection, addr: &Self::Address) -> Result<Self::Value> {
73 let f = build_read_register(self.slave_id, *addr, 2);
74 let resp = conn.send(&f).map_err(ProtocolError::from)?;
75 Ok(if resp.len() >= 9 {
76 u16::from_le_bytes([resp[6], resp[7]])
77 } else {
78 0
79 })
80 }
81 fn read_batch(&self, c: &mut dyn Connection, a: &[Self::Address]) -> Result<Vec<Self::Value>> {
82 a.iter().map(|x| self.read(c, x)).collect()
83 }
84 fn read_range(
85 &self,
86 c: &mut dyn Connection,
87 s: &Self::Address,
88 n: u16,
89 ) -> Result<Vec<Self::Value>> {
90 (0..n).map(|_| self.read(c, s)).collect()
91 }
92}
93
94impl ProtocolWrite for LightbusProtocol {
95 type Address = u16;
96 type Value = u16;
97 fn write(
98 &self,
99 conn: &mut dyn Connection,
100 addr: &Self::Address,
101 value: &Self::Value,
102 ) -> Result<()> {
103 conn.send(&build_write_register(
104 self.slave_id,
105 *addr,
106 &value.to_le_bytes(),
107 ))
108 .map_err(ProtocolError::from)?;
109 Ok(())
110 }
111 fn write_batch(
112 &self,
113 c: &mut dyn Connection,
114 i: &[(Self::Address, Self::Value)],
115 ) -> Result<()> {
116 for (a, v) in i {
117 self.write(c, a, v)?;
118 }
119 Ok(())
120 }
121}
122
123impl ProtocolHealth for LightbusProtocol {
124 fn health(&self, conn: &mut dyn Connection) -> Result<HealthStatus> {
125 let start = std::time::Instant::now();
126 match self.read(conn, &0) {
127 Ok(_) => Ok(HealthStatus {
128 state: HealthState::Healthy,
129 latency_ms: start.elapsed().as_millis() as u64,
130 last_seen: std::time::Instant::now(),
131 details: "lightbus ok".into(),
132 }),
133 Err(e) => Ok(HealthStatus {
134 state: HealthState::Unhealthy,
135 latency_ms: 0,
136 last_seen: std::time::Instant::now(),
137 details: format!("{e}"),
138 }),
139 }
140 }
141}
142
143impl ProtocolDiagnostics for LightbusProtocol {
144 fn diagnostics(&self, _: &mut dyn Connection) -> Result<DiagnosticsReport> {
145 Ok(DiagnosticsReport {
146 device_id: format!("lb:{}", self.slave_id),
147 uptime_secs: None,
148 error_count: 0,
149 last_error: None,
150 custom_fields: Default::default(),
151 })
152 }
153}
154
155#[cfg(test)]
156mod tests {
157 use super::*;
158 #[test]
159 fn test_read() {
160 let f = build_read_register(1, 0x100, 2);
161 assert_eq!(f[0], 0x02);
162 }
163 #[test]
164 fn test_meta() {
165 assert_eq!(LightbusProtocol::new().name(), "lightbus");
166 }
167}