Skip to main content

spodes_rs/classes/
disconnect_control.rs

1use crate::interface::InterfaceClass;
2use crate::obis::ObisCode;
3use crate::types::{BerError, CosemDataType};
4use serde::{Deserialize, Serialize};
5use std::any::Any;
6
7/// Values of the `control_state` attribute (IEC 62056-6-2 §4.5.8.2.3).
8pub mod control_state {
9    /// The output is open, the consumer is disconnected.
10    pub const DISCONNECTED: u8 = 0;
11    /// The output is closed, the consumer is connected.
12    pub const CONNECTED: u8 = 1;
13    /// The output is open but ready to be closed (manual reconnection pending).
14    pub const READY_FOR_RECONNECTION: u8 = 2;
15}
16
17/// Configuration structure used to build a [`DisconnectControl`] object.
18#[derive(Clone, Serialize, Deserialize, Debug)]
19pub struct DisconnectControlConfig {
20    /// Attribute 1: the object's logical name (OBIS code).
21    pub logical_name: ObisCode,
22    /// Attribute 2: physical output state (true = closed/connected).
23    pub output_state: bool,
24    /// Attribute 3: control state (see [`control_state`]).
25    pub control_state: u8,
26    /// Attribute 4: control mode (0..6, IEC 62056-6-2 §4.5.8.2.4).
27    pub control_mode: u8,
28}
29
30/// `Disconnect control` interface class (class_id = 70, version = 0) per
31/// IEC 62056-6-2 §4.5.8. Manages the internal or external disconnect relay
32/// (breaker) that connects or disconnects the consumer.
33#[derive(Clone, Serialize, Deserialize, Debug)]
34pub struct DisconnectControl {
35    logical_name: ObisCode,
36    output_state: bool,
37    control_state: u8,
38    control_mode: u8,
39}
40
41impl DisconnectControl {
42    /// Builds a new [`DisconnectControl`] from its configuration.
43    pub fn new(config: DisconnectControlConfig) -> Self {
44        DisconnectControl {
45            logical_name: config.logical_name,
46            output_state: config.output_state,
47            control_state: config.control_state,
48            control_mode: config.control_mode,
49        }
50    }
51
52    /// Method 1: `remote_disconnect` — forces the object into the `disconnected`
53    /// state if remote disconnection is enabled (control_mode > 0). When
54    /// control_mode is 0 the method has no effect (IEC 62056-6-2 §4.5.8.3.1).
55    fn remote_disconnect(&mut self) -> CosemDataType {
56        if self.control_mode > 0 {
57            self.control_state = control_state::DISCONNECTED;
58            self.output_state = false;
59        }
60        CosemDataType::Null
61    }
62
63    /// Method 2: `remote_reconnect` — forces the object into the
64    /// `ready_for_reconnection` state when direct remote reconnection is disabled
65    /// (control_mode 1, 3, 5, 6), or directly into the `connected` state when it
66    /// is enabled (control_mode 2, 4). When control_mode is 0 the method has no
67    /// effect (IEC 62056-6-2 §4.5.8.3.2).
68    fn remote_reconnect(&mut self) -> CosemDataType {
69        match self.control_mode {
70            2 | 4 => {
71                self.control_state = control_state::CONNECTED;
72                self.output_state = true;
73            }
74            1 | 3 | 5 | 6 => {
75                self.control_state = control_state::READY_FOR_RECONNECTION;
76                self.output_state = false;
77            }
78            _ => {}
79        }
80        CosemDataType::Null
81    }
82}
83
84impl InterfaceClass for DisconnectControl {
85    fn class_id(&self) -> u16 {
86        70
87    }
88
89    fn version(&self) -> u8 {
90        0
91    }
92
93    fn logical_name(&self) -> &ObisCode {
94        &self.logical_name
95    }
96
97    fn attributes(&self) -> Vec<(u8, CosemDataType)> {
98        vec![
99            (1, CosemDataType::OctetString(self.logical_name.to_bytes())),
100            (2, CosemDataType::Boolean(self.output_state)),
101            (3, CosemDataType::Enum(self.control_state)),
102            (4, CosemDataType::Enum(self.control_mode)),
103        ]
104    }
105
106    fn methods(&self) -> Vec<(u8, String)> {
107        vec![(1, "remote_disconnect".to_string()), (2, "remote_reconnect".to_string())]
108    }
109
110    fn serialize_ber(&self, buf: &mut Vec<u8>) -> Result<(), BerError> {
111        let mut seq_buf = Vec::new();
112        CosemDataType::LongUnsigned(self.class_id()).serialize_ber(&mut seq_buf)?;
113        for (_, attr) in self.attributes() {
114            attr.serialize_ber(&mut seq_buf)?;
115        }
116        buf.push(0x02); // structure [2]
117        write_length(1 + self.attributes().len(), buf); // length = element count
118        buf.extend_from_slice(&seq_buf);
119        Ok(())
120    }
121
122    fn deserialize_ber(&mut self, data: &[u8]) -> Result<(), BerError> {
123        let (tlv, rest) = CosemDataType::deserialize_ber(data)?;
124        if !rest.is_empty() {
125            return Err(BerError::InvalidTag);
126        }
127        let CosemDataType::Structure(seq) = tlv else {
128            return Err(BerError::InvalidTag);
129        };
130        // class_id + 4 attributes.
131        if seq.len() != 5 {
132            return Err(BerError::InvalidLength);
133        }
134        if let CosemDataType::LongUnsigned(class_id) = seq[0] {
135            if class_id != self.class_id() {
136                return Err(BerError::InvalidValue);
137            }
138        } else {
139            return Err(BerError::InvalidTag);
140        }
141        if let CosemDataType::OctetString(obis) = &seq[1] {
142            if obis.len() == 6 {
143                self.logical_name = ObisCode::new(obis[0], obis[1], obis[2], obis[3], obis[4], obis[5]);
144            } else {
145                return Err(BerError::InvalidLength);
146            }
147        } else {
148            return Err(BerError::InvalidTag);
149        }
150        self.output_state = match seq[2] {
151            CosemDataType::Boolean(v) => v,
152            _ => return Err(BerError::InvalidTag),
153        };
154        self.control_state = match seq[3] {
155            CosemDataType::Enum(v) => v,
156            _ => return Err(BerError::InvalidTag),
157        };
158        self.control_mode = match seq[4] {
159            CosemDataType::Enum(v) => v,
160            _ => return Err(BerError::InvalidTag),
161        };
162        Ok(())
163    }
164
165    fn set_attribute(&mut self, attribute_id: u8, value: CosemDataType) -> Result<(), String> {
166        match attribute_id {
167            4 => match value {
168                CosemDataType::Enum(v) => {
169                    self.control_mode = v;
170                    Ok(())
171                }
172                _ => Err("control_mode must be enum".into()),
173            },
174            _ => Err(format!("DisconnectControl attribute {attribute_id} is not writable")),
175        }
176    }
177
178    fn invoke_method(&mut self, method_id: u8, _params: Option<CosemDataType>) -> Result<CosemDataType, String> {
179        match method_id {
180            1 => Ok(self.remote_disconnect()),
181            2 => Ok(self.remote_reconnect()),
182            _ => Err(format!("Method {method_id} not supported for Disconnect control")),
183        }
184    }
185
186    fn as_any(&self) -> &dyn Any {
187        self
188    }
189}
190
191/// Writes a BER length octet (short or long form).
192#[allow(clippy::cast_possible_truncation)] // length < 128 and num_octets in 1..=8 always fit u8
193fn write_length(length: usize, buf: &mut Vec<u8>) {
194    if length < 128 {
195        buf.push(length as u8);
196    } else {
197        let bytes = (length as u64).to_be_bytes();
198        let first_non_zero = bytes.iter().position(|&b| b != 0).unwrap_or(7);
199        let num_octets = 8 - first_non_zero;
200        buf.push(0x80 | num_octets as u8);
201        buf.extend_from_slice(&bytes[first_non_zero..]);
202    }
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208
209    fn sample(control_mode: u8) -> DisconnectControl {
210        DisconnectControl::new(DisconnectControlConfig {
211            logical_name: ObisCode::new(0, 0, 96, 3, 10, 255),
212            output_state: true,
213            control_state: control_state::CONNECTED,
214            control_mode,
215        })
216    }
217
218    #[test]
219    fn class_id_and_attributes() {
220        let obj = sample(1);
221        assert_eq!(obj.class_id(), 70);
222        assert_eq!(obj.version(), 0);
223        assert_eq!(obj.attributes().len(), 4);
224        assert_eq!(obj.methods().len(), 2);
225    }
226
227    #[test]
228    fn round_trip() {
229        let obj = sample(2);
230        let mut buf = Vec::new();
231        obj.serialize_ber(&mut buf).unwrap();
232        let mut decoded = sample(0);
233        decoded.deserialize_ber(&buf).unwrap();
234        assert_eq!(decoded.attributes(), obj.attributes());
235    }
236
237    #[test]
238    fn disconnect_requires_enabled_mode() {
239        // control_mode 0 → method has no effect.
240        let mut obj = sample(0);
241        obj.invoke_method(1, None).unwrap();
242        assert_eq!(obj.attributes()[2].1, CosemDataType::Enum(control_state::CONNECTED));
243        // control_mode > 0 → disconnects.
244        let mut obj = sample(1);
245        obj.invoke_method(1, None).unwrap();
246        assert_eq!(obj.attributes()[2].1, CosemDataType::Enum(control_state::DISCONNECTED));
247        assert_eq!(obj.attributes()[1].1, CosemDataType::Boolean(false));
248    }
249
250    #[test]
251    fn reconnect_depends_on_control_mode() {
252        // Modes 2/4: direct reconnection → connected.
253        let mut obj = sample(2);
254        obj.control_state = control_state::DISCONNECTED;
255        obj.output_state = false;
256        obj.invoke_method(2, None).unwrap();
257        assert_eq!(obj.attributes()[2].1, CosemDataType::Enum(control_state::CONNECTED));
258        assert_eq!(obj.attributes()[1].1, CosemDataType::Boolean(true));
259        // Modes 1/3/5/6: manual reconnection → ready_for_reconnection.
260        let mut obj = sample(3);
261        obj.control_state = control_state::DISCONNECTED;
262        obj.invoke_method(2, None).unwrap();
263        assert_eq!(obj.attributes()[2].1, CosemDataType::Enum(control_state::READY_FOR_RECONNECTION));
264    }
265}