Skip to main content

spodes_rs/classes/
status_mapping.rs

1use crate::interface::InterfaceClass;
2use crate::obis::ObisCode;
3use crate::types::{BerError, CosemDataType};
4use serde::{Deserialize, Serialize};
5use std::any::Any;
6
7/// One entry of the `status_mappings` attribute: a status flag mapped to the
8/// referenced status object.
9#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
10pub struct StatusMappingEntry {
11    /// The status flag identifier (bit number).
12    pub status_flag_id: u8,
13    /// Logical name of the referenced status-word object.
14    pub status_reference: ObisCode,
15}
16
17impl From<StatusMappingEntry> for CosemDataType {
18    fn from(e: StatusMappingEntry) -> Self {
19        CosemDataType::Structure(vec![
20            CosemDataType::Unsigned(e.status_flag_id),
21            CosemDataType::OctetString(e.status_reference.to_bytes()),
22        ])
23    }
24}
25
26impl TryFrom<&CosemDataType> for StatusMappingEntry {
27    type Error = String;
28
29    fn try_from(value: &CosemDataType) -> Result<Self, Self::Error> {
30        let fields = match value {
31            CosemDataType::Structure(fields) if fields.len() == 2 => fields,
32            _ => return Err("Expected structure { status_flag_id, status_reference }".to_string()),
33        };
34        let CosemDataType::Unsigned(status_flag_id) = fields[0] else {
35            return Err("status_flag_id must be unsigned".to_string());
36        };
37        let status_reference = match &fields[1] {
38            CosemDataType::OctetString(v) if v.len() == 6 => ObisCode::new(v[0], v[1], v[2], v[3], v[4], v[5]),
39            _ => return Err("status_reference must be a 6-octet logical name".to_string()),
40        };
41        Ok(StatusMappingEntry { status_flag_id, status_reference })
42    }
43}
44
45/// Configuration structure used to build a [`StatusMapping`] object.
46#[derive(Clone, Serialize, Deserialize, Debug)]
47pub struct StatusMappingConfig {
48    /// Attribute 1: the object's logical name (OBIS code).
49    pub logical_name: ObisCode,
50    /// Attribute 2: array of status mappings.
51    pub status_mappings: Vec<StatusMappingEntry>,
52}
53
54/// `Status mapping` interface class (class_id = 63, version = 0) per
55/// IEC 62056-6-2 §4.3.9. Maps the bits of a status word onto referenced status
56/// objects.
57///
58/// This class defines no specific methods.
59#[derive(Clone, Serialize, Deserialize, Debug)]
60pub struct StatusMapping {
61    logical_name: ObisCode,
62    status_mappings: Vec<StatusMappingEntry>,
63}
64
65impl StatusMapping {
66    /// Builds a new [`StatusMapping`] from its configuration.
67    pub fn new(config: StatusMappingConfig) -> Self {
68        StatusMapping { logical_name: config.logical_name, status_mappings: config.status_mappings }
69    }
70
71    /// Returns the status mappings (attribute 2).
72    pub fn status_mappings(&self) -> &[StatusMappingEntry] {
73        &self.status_mappings
74    }
75}
76
77impl InterfaceClass for StatusMapping {
78    fn class_id(&self) -> u16 {
79        63
80    }
81
82    fn version(&self) -> u8 {
83        0
84    }
85
86    fn logical_name(&self) -> &ObisCode {
87        &self.logical_name
88    }
89
90    fn attributes(&self) -> Vec<(u8, CosemDataType)> {
91        vec![
92            (1, CosemDataType::OctetString(self.logical_name.to_bytes())),
93            (2, CosemDataType::Array(self.status_mappings.iter().cloned().map(CosemDataType::from).collect())),
94        ]
95    }
96
97    fn methods(&self) -> Vec<(u8, String)> {
98        // The status mapping class defines no specific methods.
99        vec![]
100    }
101
102    fn serialize_ber(&self, buf: &mut Vec<u8>) -> Result<(), BerError> {
103        let mut seq_buf = Vec::new();
104        CosemDataType::LongUnsigned(self.class_id()).serialize_ber(&mut seq_buf)?;
105        for (_, attr) in self.attributes() {
106            attr.serialize_ber(&mut seq_buf)?;
107        }
108        buf.push(0x02); // structure [2]
109        write_length(1 + self.attributes().len(), buf);
110        buf.extend_from_slice(&seq_buf);
111        Ok(())
112    }
113
114    fn deserialize_ber(&mut self, data: &[u8]) -> Result<(), BerError> {
115        let (tlv, rest) = CosemDataType::deserialize_ber(data)?;
116        if !rest.is_empty() {
117            return Err(BerError::InvalidTag);
118        }
119        let CosemDataType::Structure(seq) = tlv else {
120            return Err(BerError::InvalidTag);
121        };
122        if seq.len() != 3 {
123            return Err(BerError::InvalidLength);
124        }
125        if let CosemDataType::LongUnsigned(class_id) = seq[0] {
126            if class_id != self.class_id() {
127                return Err(BerError::InvalidValue);
128            }
129        } else {
130            return Err(BerError::InvalidTag);
131        }
132        if let CosemDataType::OctetString(obis) = &seq[1] {
133            if obis.len() == 6 {
134                self.logical_name = ObisCode::new(obis[0], obis[1], obis[2], obis[3], obis[4], obis[5]);
135            } else {
136                return Err(BerError::InvalidLength);
137            }
138        } else {
139            return Err(BerError::InvalidTag);
140        }
141        self.status_mappings = match &seq[2] {
142            CosemDataType::Array(entries) => entries
143                .iter()
144                .map(StatusMappingEntry::try_from)
145                .collect::<Result<Vec<_>, _>>()
146                .map_err(|_| BerError::InvalidValue)?,
147            _ => return Err(BerError::InvalidTag),
148        };
149        Ok(())
150    }
151
152    fn invoke_method(&mut self, method_id: u8, _params: Option<CosemDataType>) -> Result<CosemDataType, String> {
153        Err(format!("Method {method_id} not supported for Status mapping (no specific methods)"))
154    }
155
156    fn as_any(&self) -> &dyn Any {
157        self
158    }
159}
160
161/// Writes a BER length octet (short or long form).
162#[allow(clippy::cast_possible_truncation)] // length < 128 and num_octets in 1..=8 always fit u8
163fn write_length(length: usize, buf: &mut Vec<u8>) {
164    if length < 128 {
165        buf.push(length as u8);
166    } else {
167        let bytes = (length as u64).to_be_bytes();
168        let first_non_zero = bytes.iter().position(|&b| b != 0).unwrap_or(7);
169        let num_octets = 8 - first_non_zero;
170        buf.push(0x80 | num_octets as u8);
171        buf.extend_from_slice(&bytes[first_non_zero..]);
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178
179    fn sample() -> StatusMapping {
180        StatusMapping::new(StatusMappingConfig {
181            logical_name: ObisCode::new(0, 0, 96, 10, 1, 255),
182            status_mappings: vec![
183                StatusMappingEntry { status_flag_id: 0, status_reference: ObisCode::new(0, 0, 97, 97, 0, 255) },
184                StatusMappingEntry { status_flag_id: 3, status_reference: ObisCode::new(0, 0, 97, 97, 1, 255) },
185            ],
186        })
187    }
188
189    #[test]
190    fn class_id_and_attributes() {
191        let obj = sample();
192        assert_eq!(obj.class_id(), 63);
193        assert_eq!(obj.attributes().len(), 2);
194        assert!(obj.methods().is_empty());
195    }
196
197    #[test]
198    fn round_trip() {
199        let obj = sample();
200        let mut buf = Vec::new();
201        obj.serialize_ber(&mut buf).unwrap();
202        let mut decoded = StatusMapping::new(StatusMappingConfig {
203            logical_name: ObisCode::new(0, 0, 0, 0, 0, 0),
204            status_mappings: vec![],
205        });
206        decoded.deserialize_ber(&buf).unwrap();
207        assert_eq!(decoded.attributes(), obj.attributes());
208        assert_eq!(decoded.status_mappings(), obj.status_mappings());
209    }
210}