Skip to main content

industrial_protocols_modbusplus/
lib.rs

1// Copyright (c) 2026 erik <erik@erik.xyz> — https://erik.xyz
2//! # MODBUSPLUS — Modbus Plus 协议。1 Mbps 令牌对等通信、需 SA85/BM85 适配器。
3
4//! Modbus Plus (MB+) via Schneider SA85/BM85 adapter.
5//! Token-passing peer-to-peer at 1 Mbps over RS-485.
6use industrial_protocols_kernel::connection::Connection;
7use industrial_protocols_kernel::error::{ProtocolError, Result};
8use industrial_protocols_kernel::sdk::*;
9
10pub struct ModbusplusProtocol {
11    pub station: u8,
12}
13impl Default for ModbusplusProtocol {
14    fn default() -> Self {
15        Self::new()
16    }
17}
18
19impl ModbusplusProtocol {
20    pub fn new() -> Self {
21        ModbusplusProtocol { station: 1 }
22    }
23    pub fn station(mut self, s: u8) -> Self {
24        self.station = s;
25        self
26    }
27}
28
29// MB+ frame: [Preamble 1B] [SD 1B] [Dest 1B] [Src 1B] [LLC 1B] [Data...] [CRC 2B]
30
31pub fn build_read_request(station: u8, dest: u8, ref_addr: u16, count: u16) -> Vec<u8> {
32    let mut f = vec![0xFF, 0x68, dest, station, 0x03];
33    f.extend_from_slice(&ref_addr.to_be_bytes());
34    f.extend_from_slice(&count.to_be_bytes());
35    f.push(0x00);
36    f.push(0x00);
37    f
38}
39
40pub fn build_global_data_read(station: u8) -> Vec<u8> {
41    vec![0xFF, 0x68, 0xFF, station, 0x80, 0x00, 0x00, 0x00]
42}
43
44impl Protocol for ModbusplusProtocol {
45    fn name(&self) -> &'static str {
46        "modbusplus"
47    }
48    fn version(&self) -> &'static str {
49        "1.0.0"
50    }
51    fn category(&self) -> ProtocolCategory {
52        ProtocolCategory::HardwareBridge
53    }
54    fn supported_variants(&self) -> &'static [&'static str] {
55        &["sa85", "bm85"]
56    }
57}
58
59impl ProtocolRead for ModbusplusProtocol {
60    type Address = u16;
61    type Value = u16;
62    fn read(&self, conn: &mut dyn Connection, addr: &Self::Address) -> Result<Self::Value> {
63        let f = build_read_request(self.station, self.station + 1, *addr, 1);
64        let resp = conn.send(&f).map_err(ProtocolError::from)?;
65        Ok(if resp.len() >= 10 {
66            u16::from_be_bytes([resp[6], resp[7]])
67        } else {
68            0
69        })
70    }
71    fn read_batch(&self, c: &mut dyn Connection, a: &[Self::Address]) -> Result<Vec<Self::Value>> {
72        a.iter().map(|x| self.read(c, x)).collect()
73    }
74    fn read_range(
75        &self,
76        c: &mut dyn Connection,
77        s: &Self::Address,
78        n: u16,
79    ) -> Result<Vec<Self::Value>> {
80        (0..n).map(|_| self.read(c, s)).collect()
81    }
82}
83
84impl ProtocolHealth for ModbusplusProtocol {
85    fn health(&self, conn: &mut dyn Connection) -> Result<HealthStatus> {
86        let start = std::time::Instant::now();
87        match conn.send(&build_global_data_read(self.station)) {
88            Ok(_) => Ok(HealthStatus {
89                state: HealthState::Healthy,
90                latency_ms: start.elapsed().as_millis() as u64,
91                last_seen: std::time::Instant::now(),
92                details: "modbus+ ok".into(),
93            }),
94            Err(e) => Ok(HealthStatus {
95                state: HealthState::Unhealthy,
96                latency_ms: 0,
97                last_seen: std::time::Instant::now(),
98                details: format!("{e}"),
99            }),
100        }
101    }
102}
103
104impl ProtocolDiagnostics for ModbusplusProtocol {
105    fn diagnostics(&self, _: &mut dyn Connection) -> Result<DiagnosticsReport> {
106        Ok(DiagnosticsReport {
107            device_id: format!("mb+:{}", self.station),
108            uptime_secs: None,
109            error_count: 0,
110            last_error: None,
111            custom_fields: Default::default(),
112        })
113    }
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119    #[test]
120    fn test_read() {
121        let f = build_read_request(1, 2, 0x100, 1);
122        assert_eq!(f[0], 0xFF);
123    }
124    #[test]
125    fn test_meta() {
126        assert_eq!(ModbusplusProtocol::new().name(), "modbusplus");
127    }
128}