Skip to main content

spodes_rs/spodus/
tasks.rs

1//! Meter data-exchange tasks (СТО 34.01-5.1-013-2023, §10.7, `0.0.94.7.133.255`).
2//!
3//! Read/write/action jobs the ИВКЭ runs against meters, held as a `Data` (IC 1)
4//! object whose value is an `array exchange` (§10.7):
5//!
6//! ```text
7//! exchange ::= structure {
8//!     task_id: long-unsigned,
9//!     meter-id: array octet-string,
10//!     array script {
11//!         service_id, class_id, obis, index,
12//!         range_descriptor: structure || null-data,
13//!         entry_descriptor: structure || null-data,
14//!         value: attribute-specific || null-data
15//!     },
16//!     execution_type: enum,
17//!     execution_time: array { time: octet-string, date: octet-string },
18//!     priority: long-unsigned
19//! }
20//! ```
21
22use crate::classes::data::Data;
23use crate::types::CosemDataType;
24
25use super::obis;
26
27/// `service_id` values of a task script (§10.7).
28pub mod service_id {
29    /// GET service.
30    pub const GET: u8 = 1;
31    /// SET service.
32    pub const SET: u8 = 2;
33    /// ACTION service.
34    pub const ACTION: u8 = 3;
35}
36
37/// One meter object access within a task (§10.7, `script`).
38#[derive(Clone, Debug, Default)]
39pub struct Script {
40    /// Service to invoke (see [`service_id`]).
41    pub service_id: u8,
42    /// Class id of the target object.
43    pub class_id: u8,
44    /// OBIS of the target object.
45    pub obis: Vec<u8>,
46    /// Attribute or method index.
47    pub index: u8,
48    /// Selective-access range descriptor, or `None`.
49    pub range_descriptor: Option<CosemDataType>,
50    /// Selective-access entry descriptor, or `None`.
51    pub entry_descriptor: Option<CosemDataType>,
52    /// Value for SET/ACTION, or `None`.
53    pub value: Option<CosemDataType>,
54}
55
56impl Script {
57    fn to_structure(&self) -> CosemDataType {
58        let opt = |v: &Option<CosemDataType>| v.clone().unwrap_or(CosemDataType::Null);
59        CosemDataType::Structure(vec![
60            CosemDataType::Unsigned(self.service_id),
61            CosemDataType::Unsigned(self.class_id),
62            CosemDataType::OctetString(self.obis.clone()),
63            CosemDataType::Unsigned(self.index),
64            opt(&self.range_descriptor),
65            opt(&self.entry_descriptor),
66            opt(&self.value),
67        ])
68    }
69}
70
71/// One scheduled execution time (§10.7, `execution_time_date`).
72#[derive(Clone, Debug, Default)]
73pub struct ExecutionTime {
74    /// Time octets.
75    pub time: Vec<u8>,
76    /// Date octets.
77    pub date: Vec<u8>,
78}
79
80/// One data-exchange task (§10.7, `exchange`).
81#[derive(Clone, Debug, Default)]
82pub struct ExchangeTask {
83    /// Task identifier.
84    pub task_id: u32,
85    /// Meters the task applies to (empty = the task is disabled).
86    pub meter_ids: Vec<Vec<u8>>,
87    /// The object accesses to run.
88    pub scripts: Vec<Script>,
89    /// Execution type (as `single action schedule` type, IC 22).
90    pub execution_type: u8,
91    /// Scheduled execution times.
92    pub execution_times: Vec<ExecutionTime>,
93    /// Execution priority (ascending order).
94    pub priority: u16,
95}
96
97impl ExchangeTask {
98    fn to_structure(&self) -> CosemDataType {
99        let meter_ids = self.meter_ids.iter().map(|m| CosemDataType::OctetString(m.clone())).collect();
100        let scripts = self.scripts.iter().map(Script::to_structure).collect();
101        let times = self
102            .execution_times
103            .iter()
104            .map(|t| {
105                CosemDataType::Structure(vec![
106                    CosemDataType::OctetString(t.time.clone()),
107                    CosemDataType::OctetString(t.date.clone()),
108                ])
109            })
110            .collect();
111        // task_id is practically always <=u16::MAX (a concentrator won't
112        // schedule 65536+ tasks); the wire field is long-unsigned regardless
113        // of the wider in-memory type.
114        #[allow(clippy::cast_possible_truncation)]
115        let task_id = self.task_id as u16;
116        CosemDataType::Structure(vec![
117            CosemDataType::LongUnsigned(task_id),
118            CosemDataType::Array(meter_ids),
119            CosemDataType::Array(scripts),
120            CosemDataType::Enum(self.execution_type),
121            CosemDataType::Array(times),
122            CosemDataType::LongUnsigned(self.priority),
123        ])
124    }
125}
126
127/// The data-exchange task list (§10.7, `0.0.94.7.133.255`).
128#[derive(Clone, Debug, Default)]
129pub struct ExchangeTasks {
130    tasks: Vec<ExchangeTask>,
131}
132
133impl ExchangeTasks {
134    /// Creates an empty task list.
135    pub fn new() -> Self {
136        Self::default()
137    }
138
139    /// Adds a task.
140    pub fn add(&mut self, task: ExchangeTask) {
141        self.tasks.push(task);
142    }
143
144    /// Finds a task by id.
145    pub fn find(&self, task_id: u32) -> Option<&ExchangeTask> {
146        self.tasks.iter().find(|t| t.task_id == task_id)
147    }
148
149    /// Builds the COSEM `Data` (IC 1) object holding the task array (§10.7).
150    pub fn build(&self) -> Data {
151        let array = self.tasks.iter().map(ExchangeTask::to_structure).collect();
152        Data::new(obis::data_exchange_tasks(), CosemDataType::Array(array))
153    }
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159    use crate::interface::InterfaceClass;
160
161    #[test]
162    fn exchange_tasks_build_data_object() {
163        let mut tasks = ExchangeTasks::new();
164        tasks.add(ExchangeTask {
165            task_id: 7,
166            meter_ids: vec![b"SIT12260004".to_vec()],
167            scripts: vec![Script {
168                service_id: service_id::GET,
169                class_id: 1,
170                obis: vec![1, 0, 1, 8, 0, 255],
171                index: 2,
172                ..Default::default()
173            }],
174            execution_type: 0,
175            execution_times: vec![ExecutionTime { time: vec![0, 0, 0, 0], date: vec![0xFF; 5] }],
176            priority: 1,
177        });
178
179        assert_eq!(tasks.find(7).unwrap().priority, 1);
180        assert!(tasks.find(9).is_none());
181
182        let object = tasks.build();
183        assert_eq!(object.class_id(), 1);
184        assert_eq!(object.logical_name(), &obis::data_exchange_tasks());
185        let CosemDataType::Array(rows) = &object.attributes()[1].1 else { panic!("array") };
186        assert_eq!(rows.len(), 1);
187        let CosemDataType::Structure(fields) = &rows[0] else { panic!("exchange structure") };
188        assert_eq!(fields.len(), 6);
189        assert_eq!(fields[0], CosemDataType::LongUnsigned(7));
190        // scripts array with one script of seven fields.
191        let CosemDataType::Array(scripts) = &fields[2] else { panic!("scripts array") };
192        let CosemDataType::Structure(script) = &scripts[0] else { panic!("script structure") };
193        assert_eq!(script.len(), 7);
194        assert_eq!(script[0], CosemDataType::Unsigned(service_id::GET));
195        // absent optional fields are null-data.
196        assert_eq!(script[4], CosemDataType::Null);
197    }
198}