industrial_protocols_modbus/
lib.rs1pub mod frame;
5
6use industrial_protocols_kernel::connection::Connection;
7use industrial_protocols_kernel::error::{ProtocolError, Result};
8use industrial_protocols_kernel::sdk::*;
9use std::sync::atomic::{AtomicU16, Ordering};
10
11pub struct ModbusProtocol {
12 variant: ModbusVariant,
13 unit_id: u8,
14 transaction_id: AtomicU16,
15}
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum ModbusVariant {
19 Tcp,
20 Rtu,
21 Ascii,
22}
23
24impl ModbusProtocol {
25 pub fn tcp() -> Self {
26 ModbusProtocol {
27 variant: ModbusVariant::Tcp,
28 unit_id: 1,
29 transaction_id: AtomicU16::new(1),
30 }
31 }
32
33 pub fn rtu(unit_id: u8) -> Self {
34 ModbusProtocol {
35 variant: ModbusVariant::Rtu,
36 unit_id,
37 transaction_id: AtomicU16::new(1),
38 }
39 }
40
41 pub fn ascii(unit_id: u8) -> Self {
42 ModbusProtocol {
43 variant: ModbusVariant::Ascii,
44 unit_id,
45 transaction_id: AtomicU16::new(1),
46 }
47 }
48
49 fn next_tid(&self) -> u16 {
50 self.transaction_id.fetch_add(1, Ordering::SeqCst)
51 }
52}
53
54impl Protocol for ModbusProtocol {
55 fn name(&self) -> &'static str {
56 "modbus"
57 }
58 fn version(&self) -> &'static str {
59 "1.0.0"
60 }
61 fn category(&self) -> ProtocolCategory {
62 ProtocolCategory::IndustrialEthernet
63 }
64 fn supported_variants(&self) -> &'static [&'static str] {
65 &["tcp", "rtu", "ascii"]
66 }
67}
68
69impl ProtocolRead for ModbusProtocol {
70 type Address = u16;
71 type Value = u16;
72
73 fn read(&self, conn: &mut dyn Connection, addr: &Self::Address) -> Result<Self::Value> {
74 let frame = match self.variant {
75 ModbusVariant::Tcp => {
76 frame::build_read_holding_registers_tcp(self.next_tid(), self.unit_id, *addr, 1)
77 }
78 ModbusVariant::Rtu => frame::build_read_holding_registers_rtu(self.unit_id, *addr, 1),
79 ModbusVariant::Ascii => {
80 frame::build_read_holding_registers_ascii(self.unit_id, *addr, 1)
81 }
82 };
83 let resp = conn.send(&frame).map_err(ProtocolError::from)?;
84 if let Some(exc) = frame::parse_exception(&resp) {
85 return Err(ProtocolError::DeviceError {
86 device: "modbus-device".into(),
87 code: exc as u16,
88 message: format!("Modbus exception {exc:#04X}"),
89 });
90 }
91 frame::parse_read_response(&resp)
92 .map_err(|e| ProtocolError::Parse {
93 protocol: "modbus".into(),
94 reason: e,
95 })?
96 .into_iter()
97 .next()
98 .ok_or_else(|| ProtocolError::Parse {
99 protocol: "modbus".into(),
100 reason: "empty response".into(),
101 })
102 }
103
104 fn read_batch(
105 &self,
106 conn: &mut dyn Connection,
107 addrs: &[Self::Address],
108 ) -> Result<Vec<Self::Value>> {
109 if addrs.is_empty() {
110 return Ok(vec![]);
111 }
112 let min = *addrs.iter().min().unwrap();
113 let max = *addrs.iter().max().unwrap();
114 let count = max
115 .checked_sub(min)
116 .and_then(|d| d.checked_add(1))
117 .ok_or_else(|| ProtocolError::Parse {
118 protocol: "modbus".into(),
119 reason: "address range too large".into(),
120 })?;
121 let frame = match self.variant {
122 ModbusVariant::Tcp => {
123 frame::build_read_holding_registers_tcp(self.next_tid(), self.unit_id, min, count)
124 }
125 ModbusVariant::Rtu => frame::build_read_holding_registers_rtu(self.unit_id, min, count),
126 ModbusVariant::Ascii => {
127 frame::build_read_holding_registers_ascii(self.unit_id, min, count)
128 }
129 };
130 let resp = conn.send(&frame).map_err(ProtocolError::from)?;
131 let all = frame::parse_read_response(&resp).map_err(|e| ProtocolError::Parse {
132 protocol: "modbus".into(),
133 reason: e,
134 })?;
135 addrs
136 .iter()
137 .map(|a| {
138 all.get((*a - min) as usize)
139 .copied()
140 .ok_or_else(|| ProtocolError::Parse {
141 protocol: "modbus".into(),
142 reason: format!("response missing register {a}"),
143 })
144 })
145 .collect()
146 }
147
148 fn read_range(
149 &self,
150 conn: &mut dyn Connection,
151 start: &Self::Address,
152 count: u16,
153 ) -> Result<Vec<Self::Value>> {
154 let frame = match self.variant {
155 ModbusVariant::Tcp => frame::build_read_holding_registers_tcp(
156 self.next_tid(),
157 self.unit_id,
158 *start,
159 count,
160 ),
161 ModbusVariant::Rtu => {
162 frame::build_read_holding_registers_rtu(self.unit_id, *start, count)
163 }
164 ModbusVariant::Ascii => {
165 frame::build_read_holding_registers_ascii(self.unit_id, *start, count)
166 }
167 };
168 let resp = conn.send(&frame).map_err(ProtocolError::from)?;
169 frame::parse_read_response(&resp).map_err(|e| ProtocolError::Parse {
170 protocol: "modbus".into(),
171 reason: e,
172 })
173 }
174}
175
176impl ProtocolWrite for ModbusProtocol {
177 type Address = u16;
178 type Value = u16;
179
180 fn write(
181 &self,
182 conn: &mut dyn Connection,
183 addr: &Self::Address,
184 value: &Self::Value,
185 ) -> Result<()> {
186 let frame = match self.variant {
187 ModbusVariant::Tcp => {
188 frame::build_write_single_register_tcp(self.next_tid(), self.unit_id, *addr, *value)
189 }
190 ModbusVariant::Rtu => {
191 frame::build_write_single_register_rtu(self.unit_id, *addr, *value)
192 }
193 ModbusVariant::Ascii => {
194 frame::build_write_single_register_ascii(self.unit_id, *addr, *value)
195 }
196 };
197 let resp = conn.send(&frame).map_err(ProtocolError::from)?;
198 if let Some(exc) = frame::parse_exception(&resp) {
199 return Err(ProtocolError::DeviceError {
200 device: "modbus-device".into(),
201 code: exc as u16,
202 message: format!("Modbus exception {exc:#04X}"),
203 });
204 }
205 Ok(())
206 }
207
208 fn write_batch(
209 &self,
210 conn: &mut dyn Connection,
211 items: &[(Self::Address, Self::Value)],
212 ) -> Result<()> {
213 if items.is_empty() {
214 return Ok(());
215 }
216 let start = items[0].0;
217 let values: Vec<u16> = items.iter().map(|(_, v)| *v).collect();
218 let frame = match self.variant {
219 ModbusVariant::Tcp => frame::build_write_multiple_registers_tcp(
220 self.next_tid(),
221 self.unit_id,
222 start,
223 &values,
224 ),
225 ModbusVariant::Rtu => {
226 frame::build_write_multiple_registers_rtu(self.unit_id, start, &values)
227 }
228 ModbusVariant::Ascii => {
229 for (addr, val) in items {
231 let f = frame::build_write_single_register_ascii(self.unit_id, *addr, *val);
232 conn.send(&f).map_err(ProtocolError::from)?;
233 }
234 return Ok(());
235 }
236 };
237 let resp = conn.send(&frame).map_err(ProtocolError::from)?;
238 if let Some(exc) = frame::parse_exception(&resp) {
239 return Err(ProtocolError::DeviceError {
240 device: "modbus-device".into(),
241 code: exc as u16,
242 message: format!("Modbus exception {exc:#04X}"),
243 });
244 }
245 Ok(())
246 }
247}
248
249impl ProtocolHealth for ModbusProtocol {
250 fn health(&self, conn: &mut dyn Connection) -> Result<HealthStatus> {
251 let start = std::time::Instant::now();
252 match self.read(conn, &0) {
253 Ok(_) => Ok(HealthStatus {
254 state: HealthState::Healthy,
255 latency_ms: start.elapsed().as_millis() as u64,
256 last_seen: std::time::Instant::now(),
257 details: format!("modbus/{:?}: read holding register 0 ok", self.variant),
258 }),
259 Err(e) => Ok(HealthStatus {
260 state: HealthState::Unhealthy,
261 latency_ms: start.elapsed().as_millis() as u64,
262 last_seen: std::time::Instant::now(),
263 details: format!("modbus health check failed: {e}"),
264 }),
265 }
266 }
267}
268
269impl ProtocolDiagnostics for ModbusProtocol {
270 fn diagnostics(&self, _conn: &mut dyn Connection) -> Result<DiagnosticsReport> {
271 Ok(DiagnosticsReport {
272 device_id: format!("modbus-{:?}-{}", self.variant, self.unit_id),
273 uptime_secs: None,
274 error_count: 0,
275 last_error: None,
276 custom_fields: std::collections::HashMap::from([
277 ("variant".into(), format!("{:?}", self.variant)),
278 ("unit_id".into(), self.unit_id.to_string()),
279 ]),
280 })
281 }
282}