Skip to main content

spodes_rs/classes/
ipv4_setup.rs

1use crate::interface::InterfaceClass;
2use crate::obis::ObisCode;
3use crate::types::attrs::IpOption;
4use crate::types::{BerError, CosemDataType};
5use serde::{Deserialize, Serialize};
6use std::any::Any;
7
8/// Configuration structure used to build an [`Ipv4Setup`] object.
9#[derive(Clone, Serialize, Deserialize, Debug)]
10pub struct Ipv4SetupConfig {
11    /// Attribute 1: the object's logical name (OBIS code).
12    pub logical_name: ObisCode,
13    /// Attribute 2: reference to the data link layer setup object.
14    pub dl_reference: Vec<u8>,
15    /// Attribute 3: the IPv4 address.
16    pub ip_address: u32,
17    /// Attribute 4: array of multicast IP addresses (double-long-unsigned).
18    pub multicast_ip_address: Vec<u32>,
19    /// Attribute 5: array of IP options.
20    pub ip_options: Vec<IpOption>,
21    /// Attribute 6: subnet mask.
22    pub subnet_mask: u32,
23    /// Attribute 7: gateway IP address.
24    pub gateway_ip_address: u32,
25    /// Attribute 8: whether DHCP is used to obtain the address.
26    pub use_dhcp_flag: bool,
27    /// Attribute 9: primary DNS address.
28    pub primary_dns_address: u32,
29    /// Attribute 10: secondary DNS address.
30    pub secondary_dns_address: u32,
31}
32
33/// `IPv4 setup` interface class (class_id = 42, version = 0) per IEC 62056-6-2
34/// ยง4.9.2. Configures the IPv4 network layer.
35#[derive(Clone, Serialize, Deserialize, Debug)]
36pub struct Ipv4Setup {
37    logical_name: ObisCode,
38    dl_reference: Vec<u8>,
39    ip_address: u32,
40    multicast_ip_address: Vec<u32>,
41    ip_options: Vec<IpOption>,
42    subnet_mask: u32,
43    gateway_ip_address: u32,
44    use_dhcp_flag: bool,
45    primary_dns_address: u32,
46    secondary_dns_address: u32,
47}
48
49impl Ipv4Setup {
50    /// Builds a new [`Ipv4Setup`] from its configuration.
51    pub fn new(config: Ipv4SetupConfig) -> Self {
52        Ipv4Setup {
53            logical_name: config.logical_name,
54            dl_reference: config.dl_reference,
55            ip_address: config.ip_address,
56            multicast_ip_address: config.multicast_ip_address,
57            ip_options: config.ip_options,
58            subnet_mask: config.subnet_mask,
59            gateway_ip_address: config.gateway_ip_address,
60            use_dhcp_flag: config.use_dhcp_flag,
61            primary_dns_address: config.primary_dns_address,
62            secondary_dns_address: config.secondary_dns_address,
63        }
64    }
65
66    /// Method 1: `add_mc_IP_address` โ€” adds a multicast IP address.
67    fn add_mc_ip_address(&mut self, data: &CosemDataType) -> Result<CosemDataType, String> {
68        let addr = match data {
69            CosemDataType::DoubleLongUnsigned(v) => *v,
70            _ => return Err("add_mc_IP_address expects a double-long-unsigned".to_string()),
71        };
72        if !self.multicast_ip_address.contains(&addr) {
73            self.multicast_ip_address.push(addr);
74        }
75        Ok(CosemDataType::Null)
76    }
77
78    /// Method 2: `delete_mc_IP_address` โ€” removes a multicast IP address.
79    fn delete_mc_ip_address(&mut self, data: &CosemDataType) -> Result<CosemDataType, String> {
80        let addr = match data {
81            CosemDataType::DoubleLongUnsigned(v) => *v,
82            _ => return Err("delete_mc_IP_address expects a double-long-unsigned".to_string()),
83        };
84        let before = self.multicast_ip_address.len();
85        self.multicast_ip_address.retain(|a| *a != addr);
86        if self.multicast_ip_address.len() == before {
87            return Err("Multicast IP address not found".to_string());
88        }
89        Ok(CosemDataType::Null)
90    }
91
92    /// Method 3: `get_nbof_mc_IP_addresses` โ€” returns the number of multicast IP
93    /// addresses currently configured.
94    fn get_nbof_mc_ip_addresses(&self) -> CosemDataType {
95        // A meter's multicast group membership count is always tiny.
96        #[allow(clippy::cast_possible_truncation)]
97        let count = self.multicast_ip_address.len() as u16;
98        CosemDataType::LongUnsigned(count)
99    }
100}
101
102impl InterfaceClass for Ipv4Setup {
103    fn class_id(&self) -> u16 {
104        42
105    }
106
107    fn version(&self) -> u8 {
108        0
109    }
110
111    fn logical_name(&self) -> &ObisCode {
112        &self.logical_name
113    }
114
115    fn attributes(&self) -> Vec<(u8, CosemDataType)> {
116        vec![
117            (1, CosemDataType::OctetString(self.logical_name.to_bytes())),
118            (2, CosemDataType::OctetString(self.dl_reference.clone())),
119            (3, CosemDataType::DoubleLongUnsigned(self.ip_address)),
120            (
121                4,
122                CosemDataType::Array(
123                    self.multicast_ip_address.iter().copied().map(CosemDataType::DoubleLongUnsigned).collect(),
124                ),
125            ),
126            (5, CosemDataType::Array(self.ip_options.iter().cloned().map(CosemDataType::from).collect())),
127            (6, CosemDataType::DoubleLongUnsigned(self.subnet_mask)),
128            (7, CosemDataType::DoubleLongUnsigned(self.gateway_ip_address)),
129            (8, CosemDataType::Boolean(self.use_dhcp_flag)),
130            (9, CosemDataType::DoubleLongUnsigned(self.primary_dns_address)),
131            (10, CosemDataType::DoubleLongUnsigned(self.secondary_dns_address)),
132        ]
133    }
134
135    fn methods(&self) -> Vec<(u8, String)> {
136        vec![
137            (1, "add_mc_IP_address".to_string()),
138            (2, "delete_mc_IP_address".to_string()),
139            (3, "get_nbof_mc_IP_addresses".to_string()),
140        ]
141    }
142
143    fn serialize_ber(&self, buf: &mut Vec<u8>) -> Result<(), BerError> {
144        let mut seq_buf = Vec::new();
145        CosemDataType::LongUnsigned(self.class_id()).serialize_ber(&mut seq_buf)?;
146        for (_, attr) in self.attributes() {
147            attr.serialize_ber(&mut seq_buf)?;
148        }
149        buf.push(0x02); // structure [2]
150        write_length(1 + self.attributes().len(), buf); // length = element count
151        buf.extend_from_slice(&seq_buf);
152        Ok(())
153    }
154
155    fn deserialize_ber(&mut self, data: &[u8]) -> Result<(), BerError> {
156        let (tlv, rest) = CosemDataType::deserialize_ber(data)?;
157        if !rest.is_empty() {
158            return Err(BerError::InvalidTag);
159        }
160        let CosemDataType::Structure(seq) = tlv else {
161            return Err(BerError::InvalidTag);
162        };
163        // class_id + 10 attributes.
164        if seq.len() != 11 {
165            return Err(BerError::InvalidLength);
166        }
167        if let CosemDataType::LongUnsigned(class_id) = seq[0] {
168            if class_id != self.class_id() {
169                return Err(BerError::InvalidValue);
170            }
171        } else {
172            return Err(BerError::InvalidTag);
173        }
174        if let CosemDataType::OctetString(obis) = &seq[1] {
175            if obis.len() == 6 {
176                self.logical_name = ObisCode::new(obis[0], obis[1], obis[2], obis[3], obis[4], obis[5]);
177            } else {
178                return Err(BerError::InvalidLength);
179            }
180        } else {
181            return Err(BerError::InvalidTag);
182        }
183        self.dl_reference = match &seq[2] {
184            CosemDataType::OctetString(v) => v.clone(),
185            _ => return Err(BerError::InvalidTag),
186        };
187        self.ip_address = take_dlu(&seq[3])?;
188        self.multicast_ip_address = take_dlu_array(&seq[4])?;
189        self.ip_options = take_ip_option_array(&seq[5])?;
190        self.subnet_mask = take_dlu(&seq[6])?;
191        self.gateway_ip_address = take_dlu(&seq[7])?;
192        self.use_dhcp_flag = match seq[8] {
193            CosemDataType::Boolean(v) => v,
194            _ => return Err(BerError::InvalidTag),
195        };
196        self.primary_dns_address = take_dlu(&seq[9])?;
197        self.secondary_dns_address = take_dlu(&seq[10])?;
198        Ok(())
199    }
200
201    fn invoke_method(&mut self, method_id: u8, params: Option<CosemDataType>) -> Result<CosemDataType, String> {
202        match method_id {
203            1 => self.add_mc_ip_address(&params.ok_or("Missing method parameter")?),
204            2 => self.delete_mc_ip_address(&params.ok_or("Missing method parameter")?),
205            3 => Ok(self.get_nbof_mc_ip_addresses()),
206            _ => Err(format!("Method {method_id} not supported for IPv4 setup")),
207        }
208    }
209
210    fn as_any(&self) -> &dyn Any {
211        self
212    }
213}
214
215fn take_dlu(value: &CosemDataType) -> Result<u32, BerError> {
216    match value {
217        CosemDataType::DoubleLongUnsigned(v) => Ok(*v),
218        _ => Err(BerError::InvalidTag),
219    }
220}
221
222fn take_dlu_array(value: &CosemDataType) -> Result<Vec<u32>, BerError> {
223    match value {
224        CosemDataType::Array(list) => list
225            .iter()
226            .map(|item| match item {
227                CosemDataType::DoubleLongUnsigned(v) => Ok(*v),
228                _ => Err(BerError::InvalidTag),
229            })
230            .collect(),
231        _ => Err(BerError::InvalidTag),
232    }
233}
234
235fn take_ip_option_array(value: &CosemDataType) -> Result<Vec<IpOption>, BerError> {
236    match value {
237        CosemDataType::Array(list) => {
238            list.iter().map(|item| IpOption::try_from(item).map_err(|_| BerError::InvalidValue)).collect()
239        }
240        _ => Err(BerError::InvalidTag),
241    }
242}
243
244/// Writes a BER length octet (short or long form).
245#[allow(clippy::cast_possible_truncation)] // length < 128 and num_octets in 1..=8 always fit u8
246fn write_length(length: usize, buf: &mut Vec<u8>) {
247    if length < 128 {
248        buf.push(length as u8);
249    } else {
250        let bytes = (length as u64).to_be_bytes();
251        let first_non_zero = bytes.iter().position(|&b| b != 0).unwrap_or(7);
252        let num_octets = 8 - first_non_zero;
253        buf.push(0x80 | num_octets as u8);
254        buf.extend_from_slice(&bytes[first_non_zero..]);
255    }
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261
262    fn sample() -> Ipv4Setup {
263        Ipv4Setup::new(Ipv4SetupConfig {
264            logical_name: ObisCode::new(0, 0, 25, 1, 0, 255),
265            dl_reference: vec![0, 0, 25, 2, 0, 255],
266            ip_address: 0xC0A80001,
267            multicast_ip_address: vec![],
268            ip_options: vec![],
269            subnet_mask: 0xFFFFFF00,
270            gateway_ip_address: 0xC0A800FE,
271            use_dhcp_flag: false,
272            primary_dns_address: 0x08080808,
273            secondary_dns_address: 0x08080404,
274        })
275    }
276
277    #[test]
278    fn class_id_and_attributes() {
279        let obj = sample();
280        assert_eq!(obj.class_id(), 42);
281        assert_eq!(obj.version(), 0);
282        assert_eq!(obj.attributes().len(), 10);
283        assert_eq!(obj.methods().len(), 3);
284    }
285
286    #[test]
287    fn round_trip() {
288        let mut obj = sample();
289        obj.multicast_ip_address = vec![0xE0000001];
290        let mut buf = Vec::new();
291        obj.serialize_ber(&mut buf).unwrap();
292        let mut decoded = sample();
293        decoded.deserialize_ber(&buf).unwrap();
294        assert_eq!(decoded.attributes(), obj.attributes());
295    }
296
297    #[test]
298    fn multicast_methods() {
299        let mut obj = sample();
300        obj.invoke_method(1, Some(CosemDataType::DoubleLongUnsigned(0xE0000001))).unwrap();
301        obj.invoke_method(1, Some(CosemDataType::DoubleLongUnsigned(0xE0000002))).unwrap();
302        assert_eq!(obj.invoke_method(3, None).unwrap(), CosemDataType::LongUnsigned(2));
303        obj.invoke_method(2, Some(CosemDataType::DoubleLongUnsigned(0xE0000001))).unwrap();
304        assert_eq!(obj.invoke_method(3, None).unwrap(), CosemDataType::LongUnsigned(1));
305        // Deleting a missing address fails.
306        assert!(obj.invoke_method(2, Some(CosemDataType::DoubleLongUnsigned(0x12345678))).is_err());
307    }
308}