Skip to main content

industrial_protocols_vme/
lib.rs

1// Copyright (c) 2026 erik <erik@erik.xyz> — https://erik.xyz
2//! # VME — VME/VPX 工控背板协议。A16/A24/A32 地址空间、AM 地址修饰码。
3
4//! VME/VPX industrial backplane bus protocol.
5//! VME64 32/64-bit, 3U/6U form factor. Requires VME bridge module.
6use industrial_protocols_kernel::connection::Connection;
7use industrial_protocols_kernel::error::{ProtocolError, Result};
8use industrial_protocols_kernel::sdk::*;
9
10pub struct VmeProtocol {
11    pub slot: u8,
12    pub address_space: VmeSpace,
13}
14#[derive(Debug, Clone, Copy)]
15pub enum VmeSpace {
16    A16,
17    A24,
18    A32,
19}
20impl Default for VmeProtocol {
21    fn default() -> Self {
22        Self::new()
23    }
24}
25
26impl VmeProtocol {
27    pub fn new() -> Self {
28        VmeProtocol {
29            slot: 1,
30            address_space: VmeSpace::A16,
31        }
32    }
33    pub fn slot(mut self, s: u8) -> Self {
34        self.slot = s;
35        self
36    }
37}
38
39// VME bus cycle: [AM 6b] [Address 16/24/32b] [Data 8/16/32/64b]
40// Accessed via VME bridge (e.g., Tundra Universe II, PCI-VME adapter)
41
42pub fn build_read_cycle(space: VmeSpace, addr: u32, width: u8) -> Vec<u8> {
43    let am = match space {
44        VmeSpace::A16 => 0x29,
45        VmeSpace::A24 => 0x39,
46        VmeSpace::A32 => 0x09,
47    };
48    let mut f = vec![am, width];
49    f.extend_from_slice(&addr.to_be_bytes());
50    f
51}
52
53pub fn build_write_cycle(space: VmeSpace, addr: u32, data: &[u8]) -> Vec<u8> {
54    let am = match space {
55        VmeSpace::A16 => 0x2A,
56        VmeSpace::A24 => 0x3A,
57        VmeSpace::A32 => 0x0A,
58    };
59    let mut f = vec![am, data.len() as u8];
60    f.extend_from_slice(&addr.to_be_bytes());
61    f.extend_from_slice(data);
62    f
63}
64
65impl Protocol for VmeProtocol {
66    fn name(&self) -> &'static str {
67        "vme"
68    }
69    fn version(&self) -> &'static str {
70        "1.0.0"
71    }
72    fn category(&self) -> ProtocolCategory {
73        ProtocolCategory::SystemBus
74    }
75    fn supported_variants(&self) -> &'static [&'static str] {
76        &["vme64", "vpx"]
77    }
78}
79
80impl ProtocolRead for VmeProtocol {
81    type Address = u32;
82    type Value = u32;
83    fn read(&self, conn: &mut dyn Connection, addr: &Self::Address) -> Result<Self::Value> {
84        let f = build_read_cycle(self.address_space, *addr, 4);
85        let resp = conn.send(&f).map_err(ProtocolError::from)?;
86        Ok(if resp.len() >= 6 {
87            u32::from_be_bytes([resp[2], resp[3], resp[4], resp[5]])
88        } else {
89            0
90        })
91    }
92    fn read_batch(&self, c: &mut dyn Connection, a: &[Self::Address]) -> Result<Vec<Self::Value>> {
93        a.iter().map(|x| self.read(c, x)).collect()
94    }
95    fn read_range(
96        &self,
97        c: &mut dyn Connection,
98        s: &Self::Address,
99        n: u16,
100    ) -> Result<Vec<Self::Value>> {
101        (0..n).map(|_| self.read(c, s)).collect()
102    }
103}
104
105impl ProtocolWrite for VmeProtocol {
106    type Address = u32;
107    type Value = u32;
108    fn write(
109        &self,
110        conn: &mut dyn Connection,
111        addr: &Self::Address,
112        value: &Self::Value,
113    ) -> Result<()> {
114        conn.send(&build_write_cycle(
115            self.address_space,
116            *addr,
117            &value.to_be_bytes(),
118        ))
119        .map_err(ProtocolError::from)?;
120        Ok(())
121    }
122    fn write_batch(
123        &self,
124        c: &mut dyn Connection,
125        i: &[(Self::Address, Self::Value)],
126    ) -> Result<()> {
127        for (a, v) in i {
128            self.write(c, a, v)?;
129        }
130        Ok(())
131    }
132}
133
134impl ProtocolHealth for VmeProtocol {
135    fn health(&self, conn: &mut dyn Connection) -> Result<HealthStatus> {
136        let start = std::time::Instant::now();
137        match self.read(conn, &0) {
138            Ok(v) => Ok(HealthStatus {
139                state: HealthState::Healthy,
140                latency_ms: start.elapsed().as_millis() as u64,
141                last_seen: std::time::Instant::now(),
142                details: format!("vme addr0=0x{v:08x}"),
143            }),
144            Err(e) => Ok(HealthStatus {
145                state: HealthState::Unhealthy,
146                latency_ms: 0,
147                last_seen: std::time::Instant::now(),
148                details: format!("{e}"),
149            }),
150        }
151    }
152}
153
154impl ProtocolDiagnostics for VmeProtocol {
155    fn diagnostics(&self, _: &mut dyn Connection) -> Result<DiagnosticsReport> {
156        Ok(DiagnosticsReport {
157            device_id: format!("vme:slot{}", self.slot),
158            uptime_secs: None,
159            error_count: 0,
160            last_error: None,
161            custom_fields: Default::default(),
162        })
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169    #[test]
170    fn test_read() {
171        let f = build_read_cycle(VmeSpace::A16, 0x100, 2);
172        assert_eq!(f[0], 0x29);
173    }
174    #[test]
175    fn test_meta() {
176        assert_eq!(VmeProtocol::new().name(), "vme");
177    }
178}