Skip to main content

spodes_rs/classes/
iec_hdlc_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 an [`IecHdlcSetup`] object.
8#[derive(Clone, Serialize, Deserialize, Debug)]
9pub struct IecHdlcSetupConfig {
10    /// Attribute 1: the object's logical name (OBIS code).
11    pub logical_name: ObisCode,
12    /// Class version: 0 or 1. In version 0 attributes 5 and 6 are `unsigned`;
13    /// in version 1 they are `long-unsigned` (wider maximum info field length).
14    pub version: u8,
15    /// Attribute 2: communication speed (enum).
16    pub comm_speed: u8,
17    /// Attribute 3: transmit window size.
18    pub window_size_transmit: u8,
19    /// Attribute 4: receive window size.
20    pub window_size_receive: u8,
21    /// Attribute 5: maximum transmit info field length.
22    pub max_info_field_length_transmit: u16,
23    /// Attribute 6: maximum receive info field length.
24    pub max_info_field_length_receive: u16,
25    /// Attribute 7: inter-octet time-out, in milliseconds.
26    pub inter_octet_time_out: u16,
27    /// Attribute 8: inactivity time-out, in seconds.
28    pub inactivity_time_out: u16,
29    /// Attribute 9: HDLC device (physical) address.
30    pub device_address: u16,
31}
32
33/// `IEC HDLC setup` interface class (class_id = 23) per IEC 62056-6-2 §4.7.2.
34/// Configures the HDLC data link layer.
35///
36/// Both versions are supported: they share the same nine attributes, differing
37/// only in the type of the two maximum-info-field-length attributes
38/// (`unsigned` in version 0, `long-unsigned` in version 1). This class defines
39/// no specific methods.
40#[derive(Clone, Serialize, Deserialize, Debug)]
41pub struct IecHdlcSetup {
42    version: u8,
43    logical_name: ObisCode,
44    comm_speed: u8,
45    window_size_transmit: u8,
46    window_size_receive: u8,
47    max_info_field_length_transmit: u16,
48    max_info_field_length_receive: u16,
49    inter_octet_time_out: u16,
50    inactivity_time_out: u16,
51    device_address: u16,
52}
53
54impl IecHdlcSetup {
55    /// Builds a new [`IecHdlcSetup`] from its configuration.
56    pub fn new(config: IecHdlcSetupConfig) -> Self {
57        IecHdlcSetup {
58            version: config.version,
59            logical_name: config.logical_name,
60            comm_speed: config.comm_speed,
61            window_size_transmit: config.window_size_transmit,
62            window_size_receive: config.window_size_receive,
63            max_info_field_length_transmit: config.max_info_field_length_transmit,
64            max_info_field_length_receive: config.max_info_field_length_receive,
65            inter_octet_time_out: config.inter_octet_time_out,
66            inactivity_time_out: config.inactivity_time_out,
67            device_address: config.device_address,
68        }
69    }
70
71    /// Encodes a maximum-info-field-length attribute with the version-dependent
72    /// type: `unsigned` in version 0, `long-unsigned` in version 1.
73    fn max_info(&self, value: u16) -> CosemDataType {
74        if self.version >= 1 {
75            CosemDataType::LongUnsigned(value)
76        } else {
77            // Version 0 represents this attribute as `unsigned`; a value above
78            // 255 there is a misconfiguration (should have been version >= 1).
79            debug_assert!(value <= u16::from(u8::MAX), "max_info_field_length exceeds version 0's unsigned range");
80            #[allow(clippy::cast_possible_truncation)]
81            let v = value as u8;
82            CosemDataType::Unsigned(v)
83        }
84    }
85}
86
87impl InterfaceClass for IecHdlcSetup {
88    fn class_id(&self) -> u16 {
89        23
90    }
91
92    fn version(&self) -> u8 {
93        self.version
94    }
95
96    fn logical_name(&self) -> &ObisCode {
97        &self.logical_name
98    }
99
100    fn attributes(&self) -> Vec<(u8, CosemDataType)> {
101        vec![
102            (1, CosemDataType::OctetString(self.logical_name.to_bytes())),
103            (2, CosemDataType::Enum(self.comm_speed)),
104            (3, CosemDataType::Unsigned(self.window_size_transmit)),
105            (4, CosemDataType::Unsigned(self.window_size_receive)),
106            (5, self.max_info(self.max_info_field_length_transmit)),
107            (6, self.max_info(self.max_info_field_length_receive)),
108            (7, CosemDataType::LongUnsigned(self.inter_octet_time_out)),
109            (8, CosemDataType::LongUnsigned(self.inactivity_time_out)),
110            (9, CosemDataType::LongUnsigned(self.device_address)),
111        ]
112    }
113
114    fn methods(&self) -> Vec<(u8, String)> {
115        // The IEC HDLC setup class defines no specific methods.
116        vec![]
117    }
118
119    fn serialize_ber(&self, buf: &mut Vec<u8>) -> Result<(), BerError> {
120        let mut seq_buf = Vec::new();
121        CosemDataType::LongUnsigned(self.class_id()).serialize_ber(&mut seq_buf)?;
122        for (_, attr) in self.attributes() {
123            attr.serialize_ber(&mut seq_buf)?;
124        }
125        buf.push(0x02); // structure [2]
126        write_length(1 + self.attributes().len(), buf); // length = element count
127        buf.extend_from_slice(&seq_buf);
128        Ok(())
129    }
130
131    fn deserialize_ber(&mut self, data: &[u8]) -> Result<(), BerError> {
132        let (tlv, rest) = CosemDataType::deserialize_ber(data)?;
133        if !rest.is_empty() {
134            return Err(BerError::InvalidTag);
135        }
136        let CosemDataType::Structure(seq) = tlv else {
137            return Err(BerError::InvalidTag);
138        };
139        // class_id + 9 attributes.
140        if seq.len() != 10 {
141            return Err(BerError::InvalidLength);
142        }
143        if let CosemDataType::LongUnsigned(class_id) = seq[0] {
144            if class_id != self.class_id() {
145                return Err(BerError::InvalidValue);
146            }
147        } else {
148            return Err(BerError::InvalidTag);
149        }
150        if let CosemDataType::OctetString(obis) = &seq[1] {
151            if obis.len() == 6 {
152                self.logical_name = ObisCode::new(obis[0], obis[1], obis[2], obis[3], obis[4], obis[5]);
153            } else {
154                return Err(BerError::InvalidLength);
155            }
156        } else {
157            return Err(BerError::InvalidTag);
158        }
159        self.comm_speed = match seq[2] {
160            CosemDataType::Enum(v) => v,
161            _ => return Err(BerError::InvalidTag),
162        };
163        self.window_size_transmit = take_unsigned(&seq[3])?;
164        self.window_size_receive = take_unsigned(&seq[4])?;
165        // The type of attribute 5/6 identifies the version.
166        self.version = match &seq[5] {
167            CosemDataType::LongUnsigned(_) => 1,
168            _ => 0,
169        };
170        self.max_info_field_length_transmit = take_u16(&seq[5])?;
171        self.max_info_field_length_receive = take_u16(&seq[6])?;
172        self.inter_octet_time_out = take_long_unsigned(&seq[7])?;
173        self.inactivity_time_out = take_long_unsigned(&seq[8])?;
174        self.device_address = take_long_unsigned(&seq[9])?;
175        Ok(())
176    }
177
178    fn set_attribute(&mut self, attribute_id: u8, value: CosemDataType) -> Result<(), String> {
179        match attribute_id {
180            2 => match value {
181                CosemDataType::Enum(v) => {
182                    self.comm_speed = v;
183                    Ok(())
184                }
185                _ => Err("comm_speed must be enum".into()),
186            },
187            3 => {
188                self.window_size_transmit =
189                    take_unsigned(&value).map_err(|_| "window_size_transmit must be unsigned".to_string())?;
190                Ok(())
191            }
192            4 => {
193                self.window_size_receive =
194                    take_unsigned(&value).map_err(|_| "window_size_receive must be unsigned".to_string())?;
195                Ok(())
196            }
197            5 => {
198                self.max_info_field_length_transmit =
199                    take_u16(&value).map_err(|_| "max_info_field_length_transmit must be unsigned".to_string())?;
200                Ok(())
201            }
202            6 => {
203                self.max_info_field_length_receive =
204                    take_u16(&value).map_err(|_| "max_info_field_length_receive must be unsigned".to_string())?;
205                Ok(())
206            }
207            7 => {
208                self.inter_octet_time_out =
209                    take_long_unsigned(&value).map_err(|_| "inter_octet_time_out must be long-unsigned".to_string())?;
210                Ok(())
211            }
212            8 => {
213                self.inactivity_time_out =
214                    take_long_unsigned(&value).map_err(|_| "inactivity_time_out must be long-unsigned".to_string())?;
215                Ok(())
216            }
217            9 => {
218                self.device_address =
219                    take_long_unsigned(&value).map_err(|_| "device_address must be long-unsigned".to_string())?;
220                Ok(())
221            }
222            _ => Err(format!("IecHdlcSetup attribute {attribute_id} is not writable")),
223        }
224    }
225
226    fn invoke_method(&mut self, method_id: u8, _params: Option<CosemDataType>) -> Result<CosemDataType, String> {
227        Err(format!("Method {method_id} not supported for IEC HDLC setup (no specific methods)"))
228    }
229
230    fn as_any(&self) -> &dyn Any {
231        self
232    }
233}
234
235fn take_unsigned(value: &CosemDataType) -> Result<u8, BerError> {
236    match value {
237        CosemDataType::Unsigned(v) => Ok(*v),
238        _ => Err(BerError::InvalidTag),
239    }
240}
241
242fn take_long_unsigned(value: &CosemDataType) -> Result<u16, BerError> {
243    match value {
244        CosemDataType::LongUnsigned(v) => Ok(*v),
245        _ => Err(BerError::InvalidTag),
246    }
247}
248
249/// Reads either an `unsigned` (v0) or a `long-unsigned` (v1) as `u16`.
250fn take_u16(value: &CosemDataType) -> Result<u16, BerError> {
251    match value {
252        CosemDataType::LongUnsigned(v) => Ok(*v),
253        CosemDataType::Unsigned(v) => Ok(u16::from(*v)),
254        _ => Err(BerError::InvalidTag),
255    }
256}
257
258/// Writes a BER length octet (short or long form).
259#[allow(clippy::cast_possible_truncation)] // length < 128 and num_octets in 1..=8 always fit u8
260fn write_length(length: usize, buf: &mut Vec<u8>) {
261    if length < 128 {
262        buf.push(length as u8);
263    } else {
264        let bytes = (length as u64).to_be_bytes();
265        let first_non_zero = bytes.iter().position(|&b| b != 0).unwrap_or(7);
266        let num_octets = 8 - first_non_zero;
267        buf.push(0x80 | num_octets as u8);
268        buf.extend_from_slice(&bytes[first_non_zero..]);
269    }
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275
276    fn sample_versioned(version: u8) -> IecHdlcSetup {
277        IecHdlcSetup::new(IecHdlcSetupConfig {
278            logical_name: ObisCode::new(0, 0, 22, 0, 0, 255),
279            version,
280            comm_speed: 5,
281            window_size_transmit: 1,
282            window_size_receive: 1,
283            max_info_field_length_transmit: 128,
284            max_info_field_length_receive: 128,
285            inter_octet_time_out: 25,
286            inactivity_time_out: 120,
287            device_address: 0x0010,
288        })
289    }
290
291    #[test]
292    fn attribute_type_depends_on_version() {
293        let v0 = sample_versioned(0);
294        assert_eq!(v0.attributes().len(), 9);
295        assert!(v0.methods().is_empty());
296        assert_eq!(v0.attributes()[4].1, CosemDataType::Unsigned(128));
297        let v1 = sample_versioned(1);
298        assert_eq!(v1.attributes()[4].1, CosemDataType::LongUnsigned(128));
299    }
300
301    #[test]
302    fn round_trip_all_versions() {
303        for version in 0..=1u8 {
304            let obj = sample_versioned(version);
305            let mut buf = Vec::new();
306            obj.serialize_ber(&mut buf).unwrap();
307            let mut decoded = sample_versioned(1 - version);
308            decoded.deserialize_ber(&buf).unwrap();
309            assert_eq!(decoded.version(), version);
310            assert_eq!(decoded.attributes(), obj.attributes());
311        }
312    }
313}