Skip to main content

spodes_rs/classes/
mac_address_setup.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 a [`MacAddressSetup`] object.
8#[derive(Clone, Serialize, Deserialize, Debug)]
9pub struct MacAddressSetupConfig {
10    /// Attribute 1: the object's logical name (OBIS code).
11    pub logical_name: ObisCode,
12    /// Attribute 2: the Ethernet MAC address (octet-string, typically 6 octets).
13    pub mac_address: Vec<u8>,
14}
15
16/// `MAC address setup` interface class (class_id = 43, version = 0) per
17/// IEC 62056-6-2 §4.9.4. Holds the Ethernet MAC address of the device.
18///
19/// This class defines no specific methods.
20#[derive(Clone, Serialize, Deserialize, Debug)]
21pub struct MacAddressSetup {
22    logical_name: ObisCode,
23    mac_address: Vec<u8>,
24}
25
26impl MacAddressSetup {
27    /// Builds a new [`MacAddressSetup`] from its configuration.
28    pub fn new(config: MacAddressSetupConfig) -> Self {
29        MacAddressSetup { logical_name: config.logical_name, mac_address: config.mac_address }
30    }
31}
32
33impl InterfaceClass for MacAddressSetup {
34    fn class_id(&self) -> u16 {
35        43
36    }
37
38    fn version(&self) -> u8 {
39        0
40    }
41
42    fn logical_name(&self) -> &ObisCode {
43        &self.logical_name
44    }
45
46    fn attributes(&self) -> Vec<(u8, CosemDataType)> {
47        vec![
48            (1, CosemDataType::OctetString(self.logical_name.to_bytes())),
49            (2, CosemDataType::OctetString(self.mac_address.clone())),
50        ]
51    }
52
53    fn methods(&self) -> Vec<(u8, String)> {
54        // The MAC address setup class defines no specific methods.
55        vec![]
56    }
57
58    fn serialize_ber(&self, buf: &mut Vec<u8>) -> Result<(), BerError> {
59        let mut seq_buf = Vec::new();
60        CosemDataType::LongUnsigned(self.class_id()).serialize_ber(&mut seq_buf)?;
61        for (_, attr) in self.attributes() {
62            attr.serialize_ber(&mut seq_buf)?;
63        }
64        buf.push(0x02); // structure [2]
65        write_length(1 + self.attributes().len(), buf); // length = element count
66        buf.extend_from_slice(&seq_buf);
67        Ok(())
68    }
69
70    fn deserialize_ber(&mut self, data: &[u8]) -> Result<(), BerError> {
71        let (tlv, rest) = CosemDataType::deserialize_ber(data)?;
72        if !rest.is_empty() {
73            return Err(BerError::InvalidTag);
74        }
75        let CosemDataType::Structure(seq) = tlv else {
76            return Err(BerError::InvalidTag);
77        };
78        // class_id + 2 attributes.
79        if seq.len() != 3 {
80            return Err(BerError::InvalidLength);
81        }
82        if let CosemDataType::LongUnsigned(class_id) = seq[0] {
83            if class_id != self.class_id() {
84                return Err(BerError::InvalidValue);
85            }
86        } else {
87            return Err(BerError::InvalidTag);
88        }
89        if let CosemDataType::OctetString(obis) = &seq[1] {
90            if obis.len() == 6 {
91                self.logical_name = ObisCode::new(obis[0], obis[1], obis[2], obis[3], obis[4], obis[5]);
92            } else {
93                return Err(BerError::InvalidLength);
94            }
95        } else {
96            return Err(BerError::InvalidTag);
97        }
98        self.mac_address = match &seq[2] {
99            CosemDataType::OctetString(bytes) => bytes.clone(),
100            _ => return Err(BerError::InvalidTag),
101        };
102        Ok(())
103    }
104
105    fn invoke_method(&mut self, method_id: u8, _params: Option<CosemDataType>) -> Result<CosemDataType, String> {
106        Err(format!("Method {method_id} not supported for MAC address setup (no specific methods)"))
107    }
108
109    fn as_any(&self) -> &dyn Any {
110        self
111    }
112}
113
114/// Writes a BER length octet (short or long form).
115#[allow(clippy::cast_possible_truncation)] // length < 128 and num_octets in 1..=8 always fit u8
116fn write_length(length: usize, buf: &mut Vec<u8>) {
117    if length < 128 {
118        buf.push(length as u8);
119    } else {
120        let bytes = (length as u64).to_be_bytes();
121        let first_non_zero = bytes.iter().position(|&b| b != 0).unwrap_or(7);
122        let num_octets = 8 - first_non_zero;
123        buf.push(0x80 | num_octets as u8);
124        buf.extend_from_slice(&bytes[first_non_zero..]);
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    fn sample() -> MacAddressSetup {
133        MacAddressSetup::new(MacAddressSetupConfig {
134            logical_name: ObisCode::new(0, 0, 25, 2, 0, 255),
135            mac_address: vec![0x00, 0x11, 0x22, 0x33, 0x44, 0x55],
136        })
137    }
138
139    #[test]
140    fn class_id_and_attributes() {
141        let obj = sample();
142        assert_eq!(obj.class_id(), 43);
143        assert_eq!(obj.version(), 0);
144        assert_eq!(obj.attributes().len(), 2);
145        assert!(obj.methods().is_empty());
146    }
147
148    #[test]
149    fn round_trip() {
150        let obj = sample();
151        let mut buf = Vec::new();
152        obj.serialize_ber(&mut buf).unwrap();
153        let mut decoded = sample();
154        decoded.mac_address = vec![];
155        decoded.deserialize_ber(&buf).unwrap();
156        assert_eq!(decoded.attributes(), obj.attributes());
157    }
158}