Skip to main content

spodes_rs/classes/
arbitrator.rs

1use crate::interface::InterfaceClass;
2use crate::obis::ObisCode;
3use crate::types::attrs::ActionItem;
4use crate::types::{BerError, CosemDataType};
5use serde::{Deserialize, Serialize};
6use std::any::Any;
7
8/// Configuration structure used to build an [`Arbitrator`] object.
9#[derive(Clone, Serialize, Deserialize, Debug)]
10pub struct ArbitratorConfig {
11    /// Attribute 1: the object's logical name (OBIS code).
12    pub logical_name: ObisCode,
13    /// Attribute 2: array of `action` structures that can be requested.
14    pub actions: Vec<ActionItem>,
15    /// Attribute 3: permissions table (array of bit-strings, one per actor).
16    pub permissions_table: Vec<CosemDataType>,
17    /// Attribute 4: weightings table (array).
18    pub weightings_table: Vec<CosemDataType>,
19    /// Attribute 5: most recent requests table (array of bit-strings).
20    pub most_recent_requests_table: Vec<CosemDataType>,
21    /// Attribute 6: index of the action selected by the last arbitration.
22    pub last_outcome: u8,
23}
24
25/// `Arbitrator` interface class (class_id = 68, version = 0) per IEC 62056-6-2
26/// §4.5.12. Arbitrates action requests from several actors according to the
27/// permissions and weightings tables.
28///
29/// The full weighting/permission arbitration algorithm is out of scope for this
30/// data-model class: `request_action` records the request and `reset` clears the
31/// request table.
32#[derive(Clone, Serialize, Deserialize, Debug)]
33pub struct Arbitrator {
34    logical_name: ObisCode,
35    actions: Vec<ActionItem>,
36    permissions_table: Vec<CosemDataType>,
37    weightings_table: Vec<CosemDataType>,
38    most_recent_requests_table: Vec<CosemDataType>,
39    last_outcome: u8,
40}
41
42impl Arbitrator {
43    /// Builds a new [`Arbitrator`] from its configuration.
44    pub fn new(config: ArbitratorConfig) -> Self {
45        Arbitrator {
46            logical_name: config.logical_name,
47            actions: config.actions,
48            permissions_table: config.permissions_table,
49            weightings_table: config.weightings_table,
50            most_recent_requests_table: config.most_recent_requests_table,
51            last_outcome: config.last_outcome,
52        }
53    }
54
55    /// Method 1: `request_action` — records a request in the most-recent-requests
56    /// table (IEC 62056-6-2 §4.5.12.3).
57    fn request_action(&mut self, data: CosemDataType) -> CosemDataType {
58        self.most_recent_requests_table.push(data);
59        CosemDataType::Null
60    }
61
62    /// Method 2: `reset` — clears the most-recent-requests table and the last
63    /// outcome.
64    fn reset(&mut self) -> CosemDataType {
65        self.most_recent_requests_table.clear();
66        self.last_outcome = 0;
67        CosemDataType::Null
68    }
69}
70
71impl InterfaceClass for Arbitrator {
72    fn class_id(&self) -> u16 {
73        68
74    }
75
76    fn version(&self) -> u8 {
77        0
78    }
79
80    fn logical_name(&self) -> &ObisCode {
81        &self.logical_name
82    }
83
84    fn attributes(&self) -> Vec<(u8, CosemDataType)> {
85        vec![
86            (1, CosemDataType::OctetString(self.logical_name.to_bytes())),
87            (2, CosemDataType::Array(self.actions.iter().map(|a| CosemDataType::from(a.clone())).collect())),
88            (3, CosemDataType::Array(self.permissions_table.clone())),
89            (4, CosemDataType::Array(self.weightings_table.clone())),
90            (5, CosemDataType::Array(self.most_recent_requests_table.clone())),
91            (6, CosemDataType::Unsigned(self.last_outcome)),
92        ]
93    }
94
95    fn methods(&self) -> Vec<(u8, String)> {
96        vec![(1, "request_action".to_string()), (2, "reset".to_string())]
97    }
98
99    fn serialize_ber(&self, buf: &mut Vec<u8>) -> Result<(), BerError> {
100        let mut seq_buf = Vec::new();
101        CosemDataType::LongUnsigned(self.class_id()).serialize_ber(&mut seq_buf)?;
102        for (_, attr) in self.attributes() {
103            attr.serialize_ber(&mut seq_buf)?;
104        }
105        buf.push(0x02); // structure [2]
106        write_length(1 + self.attributes().len(), buf); // length = element count
107        buf.extend_from_slice(&seq_buf);
108        Ok(())
109    }
110
111    fn deserialize_ber(&mut self, data: &[u8]) -> Result<(), BerError> {
112        let (tlv, rest) = CosemDataType::deserialize_ber(data)?;
113        if !rest.is_empty() {
114            return Err(BerError::InvalidTag);
115        }
116        let CosemDataType::Structure(seq) = tlv else {
117            return Err(BerError::InvalidTag);
118        };
119        // class_id + 6 attributes.
120        if seq.len() != 7 {
121            return Err(BerError::InvalidLength);
122        }
123        if let CosemDataType::LongUnsigned(class_id) = seq[0] {
124            if class_id != self.class_id() {
125                return Err(BerError::InvalidValue);
126            }
127        } else {
128            return Err(BerError::InvalidTag);
129        }
130        if let CosemDataType::OctetString(obis) = &seq[1] {
131            if obis.len() == 6 {
132                self.logical_name = ObisCode::new(obis[0], obis[1], obis[2], obis[3], obis[4], obis[5]);
133            } else {
134                return Err(BerError::InvalidLength);
135            }
136        } else {
137            return Err(BerError::InvalidTag);
138        }
139        self.actions = take_array(&seq[2])?
140            .into_iter()
141            .map(|v| ActionItem::try_from(&v).map_err(|_| BerError::InvalidValue))
142            .collect::<Result<Vec<_>, _>>()?;
143        self.permissions_table = take_array(&seq[3])?;
144        self.weightings_table = take_array(&seq[4])?;
145        self.most_recent_requests_table = take_array(&seq[5])?;
146        self.last_outcome = match seq[6] {
147            CosemDataType::Unsigned(v) => v,
148            _ => return Err(BerError::InvalidTag),
149        };
150        Ok(())
151    }
152
153    fn invoke_method(&mut self, method_id: u8, params: Option<CosemDataType>) -> Result<CosemDataType, String> {
154        match method_id {
155            1 => Ok(self.request_action(params.ok_or("Missing method parameter")?)),
156            2 => Ok(self.reset()),
157            _ => Err(format!("Method {method_id} not supported for Arbitrator")),
158        }
159    }
160
161    fn as_any(&self) -> &dyn Any {
162        self
163    }
164}
165
166fn take_array(value: &CosemDataType) -> Result<Vec<CosemDataType>, BerError> {
167    match value {
168        CosemDataType::Array(list) => Ok(list.clone()),
169        _ => Err(BerError::InvalidTag),
170    }
171}
172
173/// Writes a BER length octet (short or long form).
174#[allow(clippy::cast_possible_truncation)] // length < 128 and num_octets in 1..=8 always fit u8
175fn write_length(length: usize, buf: &mut Vec<u8>) {
176    if length < 128 {
177        buf.push(length as u8);
178    } else {
179        let bytes = (length as u64).to_be_bytes();
180        let first_non_zero = bytes.iter().position(|&b| b != 0).unwrap_or(7);
181        let num_octets = 8 - first_non_zero;
182        buf.push(0x80 | num_octets as u8);
183        buf.extend_from_slice(&bytes[first_non_zero..]);
184    }
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190
191    fn sample() -> Arbitrator {
192        Arbitrator::new(ArbitratorConfig {
193            logical_name: ObisCode::new(0, 0, 96, 3, 20, 255),
194            actions: vec![ActionItem { script_logical_name: ObisCode::new(0, 0, 10, 0, 1, 255), script_selector: 1 }],
195            permissions_table: vec![CosemDataType::BitString(vec![0x80])],
196            weightings_table: vec![CosemDataType::Array(vec![CosemDataType::LongUnsigned(1)])],
197            most_recent_requests_table: vec![],
198            last_outcome: 0,
199        })
200    }
201
202    #[test]
203    fn class_id_and_attributes() {
204        let obj = sample();
205        assert_eq!(obj.class_id(), 68);
206        assert_eq!(obj.version(), 0);
207        assert_eq!(obj.attributes().len(), 6);
208        assert_eq!(obj.methods().len(), 2);
209    }
210
211    #[test]
212    fn round_trip() {
213        let obj = sample();
214        let mut buf = Vec::new();
215        obj.serialize_ber(&mut buf).unwrap();
216        let mut decoded = sample();
217        decoded.last_outcome = 9;
218        decoded.deserialize_ber(&buf).unwrap();
219        assert_eq!(decoded.attributes(), obj.attributes());
220    }
221
222    #[test]
223    fn request_then_reset() {
224        let mut obj = sample();
225        obj.invoke_method(1, Some(CosemDataType::BitString(vec![0x80]))).unwrap();
226        assert_eq!(obj.most_recent_requests_table.len(), 1);
227        obj.invoke_method(2, None).unwrap();
228        assert_eq!(obj.most_recent_requests_table.len(), 0);
229        assert_eq!(obj.attributes()[5].1, CosemDataType::Unsigned(0));
230    }
231}