Skip to main content

spodes_rs/classes/
mbus_slave.rs

1use crate::interface::InterfaceClass;
2use crate::obis::ObisCode;
3use crate::types::{BerError, CosemDataType};
4use serde::{Deserialize, Serialize};
5use std::any::Any;
6
7/// Configuration structure used to build an [`MbusSlave`] object.
8#[derive(Clone, Serialize, Deserialize, Debug)]
9pub struct MbusSlaveConfig {
10    /// Attribute 1: the object's logical name (OBIS code).
11    pub logical_name: ObisCode,
12    /// Attribute 2: primary (physical) address on the M-Bus.
13    pub physical_address: u16,
14    /// Attribute 3: logical (secondary) address.
15    pub logical_address: u16,
16    /// Attribute 4: device identification number (octet-string, BCD).
17    pub id_number: Vec<u8>,
18    /// Attribute 5: manufacturer identification (octet-string).
19    pub manufacturer: Vec<u8>,
20    /// Attribute 6: device version / generation.
21    pub version: u8,
22    /// Attribute 7: medium (per EN 13757-3, Table 3).
23    pub medium: u8,
24}
25
26/// `M-Bus slave` device descriptor interface class (class_id = 76, version = 0),
27/// describing an M-Bus device attached behind the port (addresses,
28/// identification, manufacturer, medium).
29///
30/// This class defines no specific methods.
31#[derive(Clone, Serialize, Deserialize, Debug)]
32pub struct MbusSlave {
33    logical_name: ObisCode,
34    physical_address: u16,
35    logical_address: u16,
36    id_number: Vec<u8>,
37    manufacturer: Vec<u8>,
38    version: u8,
39    medium: u8,
40}
41
42impl MbusSlave {
43    /// Builds a new [`MbusSlave`] from its configuration.
44    pub fn new(config: MbusSlaveConfig) -> Self {
45        MbusSlave {
46            logical_name: config.logical_name,
47            physical_address: config.physical_address,
48            logical_address: config.logical_address,
49            id_number: config.id_number,
50            manufacturer: config.manufacturer,
51            version: config.version,
52            medium: config.medium,
53        }
54    }
55}
56
57impl InterfaceClass for MbusSlave {
58    fn class_id(&self) -> u16 {
59        76
60    }
61
62    fn version(&self) -> u8 {
63        0
64    }
65
66    fn logical_name(&self) -> &ObisCode {
67        &self.logical_name
68    }
69
70    fn attributes(&self) -> Vec<(u8, CosemDataType)> {
71        vec![
72            (1, CosemDataType::OctetString(self.logical_name.to_bytes())),
73            (2, CosemDataType::LongUnsigned(self.physical_address)),
74            (3, CosemDataType::LongUnsigned(self.logical_address)),
75            (4, CosemDataType::OctetString(self.id_number.clone())),
76            (5, CosemDataType::OctetString(self.manufacturer.clone())),
77            (6, CosemDataType::Unsigned(self.version)),
78            (7, CosemDataType::Unsigned(self.medium)),
79        ]
80    }
81
82    fn methods(&self) -> Vec<(u8, String)> {
83        // The M-Bus slave class defines no specific methods.
84        vec![]
85    }
86
87    fn serialize_ber(&self, buf: &mut Vec<u8>) -> Result<(), BerError> {
88        let mut seq_buf = Vec::new();
89        CosemDataType::LongUnsigned(self.class_id()).serialize_ber(&mut seq_buf)?;
90        for (_, attr) in self.attributes() {
91            attr.serialize_ber(&mut seq_buf)?;
92        }
93        buf.push(0x02); // structure [2]
94        write_length(1 + self.attributes().len(), buf);
95        buf.extend_from_slice(&seq_buf);
96        Ok(())
97    }
98
99    fn deserialize_ber(&mut self, data: &[u8]) -> Result<(), BerError> {
100        let (tlv, rest) = CosemDataType::deserialize_ber(data)?;
101        if !rest.is_empty() {
102            return Err(BerError::InvalidTag);
103        }
104        let CosemDataType::Structure(seq) = tlv else {
105            return Err(BerError::InvalidTag);
106        };
107        if seq.len() != 8 {
108            return Err(BerError::InvalidLength);
109        }
110        if let CosemDataType::LongUnsigned(class_id) = seq[0] {
111            if class_id != self.class_id() {
112                return Err(BerError::InvalidValue);
113            }
114        } else {
115            return Err(BerError::InvalidTag);
116        }
117        if let CosemDataType::OctetString(obis) = &seq[1] {
118            if obis.len() == 6 {
119                self.logical_name = ObisCode::new(obis[0], obis[1], obis[2], obis[3], obis[4], obis[5]);
120            } else {
121                return Err(BerError::InvalidLength);
122            }
123        } else {
124            return Err(BerError::InvalidTag);
125        }
126        self.physical_address = take_long_unsigned(&seq[2])?;
127        self.logical_address = take_long_unsigned(&seq[3])?;
128        self.id_number = take_octets(&seq[4])?;
129        self.manufacturer = take_octets(&seq[5])?;
130        self.version = take_unsigned(&seq[6])?;
131        self.medium = take_unsigned(&seq[7])?;
132        Ok(())
133    }
134
135    fn invoke_method(&mut self, method_id: u8, _params: Option<CosemDataType>) -> Result<CosemDataType, String> {
136        Err(format!("Method {method_id} not supported for M-Bus slave (no specific methods)"))
137    }
138
139    fn as_any(&self) -> &dyn Any {
140        self
141    }
142}
143
144fn take_long_unsigned(value: &CosemDataType) -> Result<u16, BerError> {
145    match value {
146        CosemDataType::LongUnsigned(v) => Ok(*v),
147        _ => Err(BerError::InvalidTag),
148    }
149}
150
151fn take_unsigned(value: &CosemDataType) -> Result<u8, BerError> {
152    match value {
153        CosemDataType::Unsigned(v) => Ok(*v),
154        _ => Err(BerError::InvalidTag),
155    }
156}
157
158fn take_octets(value: &CosemDataType) -> Result<Vec<u8>, BerError> {
159    match value {
160        CosemDataType::OctetString(v) => Ok(v.clone()),
161        _ => Err(BerError::InvalidTag),
162    }
163}
164
165/// Writes a BER length octet (short or long form).
166#[allow(clippy::cast_possible_truncation)] // length < 128 and num_octets in 1..=8 always fit u8
167fn write_length(length: usize, buf: &mut Vec<u8>) {
168    if length < 128 {
169        buf.push(length as u8);
170    } else {
171        let bytes = (length as u64).to_be_bytes();
172        let first_non_zero = bytes.iter().position(|&b| b != 0).unwrap_or(7);
173        let num_octets = 8 - first_non_zero;
174        buf.push(0x80 | num_octets as u8);
175        buf.extend_from_slice(&bytes[first_non_zero..]);
176    }
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182
183    fn sample() -> MbusSlave {
184        MbusSlave::new(MbusSlaveConfig {
185            logical_name: ObisCode::new(0, 1, 24, 1, 0, 255),
186            physical_address: 5,
187            logical_address: 0,
188            id_number: vec![0x12, 0x34, 0x56, 0x78],
189            manufacturer: vec![b'A', b'B', b'C'],
190            version: 1,
191            medium: 7, // water
192        })
193    }
194
195    #[test]
196    fn class_id_and_attributes() {
197        let obj = sample();
198        assert_eq!(obj.class_id(), 76);
199        assert_eq!(obj.attributes().len(), 7);
200        assert!(obj.methods().is_empty());
201    }
202
203    #[test]
204    fn round_trip() {
205        let obj = sample();
206        let mut buf = Vec::new();
207        obj.serialize_ber(&mut buf).unwrap();
208        let mut decoded = MbusSlave::new(MbusSlaveConfig {
209            logical_name: ObisCode::new(0, 0, 0, 0, 0, 0),
210            physical_address: 0,
211            logical_address: 0,
212            id_number: vec![],
213            manufacturer: vec![],
214            version: 0,
215            medium: 0,
216        });
217        decoded.deserialize_ber(&buf).unwrap();
218        assert_eq!(decoded.attributes(), obj.attributes());
219    }
220}