Skip to main content

spodes_rs/service/
set.rs

1//! The xDLMS SET service (IEC 62056-5-3, 6.10): write one or more COSEM object
2//! attributes.
3//!
4//! Request bytes for SET-REQUEST-NORMAL, from IEC 62056-5-3 Annex F.1:
5//!
6//! ```text
7//! C1 01 C1 0001 0000800000FF 02 00 0932 <50 octets>
8//! ^tag                            ^^ access-selection   ^^ value (A-XDR)
9//!    ^^ normal   ^^ iid  ^^^^^^^^ attribute descriptor
10//! ```
11//!
12//! Block transfer (SET-REQUEST-WITH-FIRST-DATABLOCK and friends) is not modelled
13//! yet.
14
15use crate::types::CosemDataType;
16
17use super::get::AccessSelection;
18use super::{push_length, read_length, tag, AttributeDescriptor, DataBlockSa, ServiceError};
19
20mod request_type {
21    pub const NORMAL: u8 = 1;
22    pub const WITH_FIRST_DATABLOCK: u8 = 2;
23    pub const WITH_DATABLOCK: u8 = 3;
24    pub const WITH_LIST: u8 = 4;
25}
26
27mod response_type {
28    pub const NORMAL: u8 = 1;
29    pub const DATABLOCK: u8 = 2;
30    pub const LAST_DATABLOCK: u8 = 3;
31    pub const WITH_LIST: u8 = 5;
32}
33
34/// A SET-Request APDU.
35#[derive(Debug, Clone, PartialEq)]
36pub enum SetRequest {
37    /// SET-REQUEST-NORMAL: write a single attribute.
38    Normal {
39        /// The invoke-id and priority byte.
40        invoke_id_and_priority: u8,
41        /// The attribute to write.
42        attribute: AttributeDescriptor,
43        /// Optional selective access applied to the attribute.
44        access_selection: Option<AccessSelection>,
45        /// The value to write.
46        value: CosemDataType,
47    },
48    /// SET-REQUEST-WITH-FIRST-DATABLOCK: the attribute reference and the first
49    /// block of the value.
50    WithFirstDatablock {
51        /// The invoke-id and priority byte.
52        invoke_id_and_priority: u8,
53        /// The attribute to write.
54        attribute: AttributeDescriptor,
55        /// Optional selective access applied to the attribute.
56        access_selection: Option<AccessSelection>,
57        /// The first block of the value being written.
58        datablock: DataBlockSa,
59    },
60    /// SET-REQUEST-WITH-DATABLOCK: a subsequent block of the value.
61    WithDatablock {
62        /// The invoke-id and priority byte.
63        invoke_id_and_priority: u8,
64        /// The next block of the value being written.
65        datablock: DataBlockSa,
66    },
67    /// SET-REQUEST-WITH-LIST: write several attributes in one request.
68    WithList {
69        /// The invoke-id and priority byte.
70        invoke_id_and_priority: u8,
71        /// The attributes to write, each with optional selective access.
72        attributes: Vec<(AttributeDescriptor, Option<AccessSelection>)>,
73        /// The values to write, one per attribute in order.
74        values: Vec<CosemDataType>,
75    },
76}
77
78impl SetRequest {
79    /// Encodes the request APDU.
80    pub fn encode(&self) -> Result<Vec<u8>, ServiceError> {
81        let mut buf = vec![tag::SET_REQUEST];
82        match self {
83            SetRequest::Normal { invoke_id_and_priority, attribute, access_selection, value } => {
84                buf.push(request_type::NORMAL);
85                buf.push(*invoke_id_and_priority);
86                attribute.encode(&mut buf);
87                AccessSelection::encode_into(access_selection, &mut buf)?;
88                value.serialize_ber(&mut buf)?;
89            }
90            SetRequest::WithFirstDatablock { invoke_id_and_priority, attribute, access_selection, datablock } => {
91                buf.push(request_type::WITH_FIRST_DATABLOCK);
92                buf.push(*invoke_id_and_priority);
93                attribute.encode(&mut buf);
94                AccessSelection::encode_into(access_selection, &mut buf)?;
95                datablock.encode(&mut buf);
96            }
97            SetRequest::WithDatablock { invoke_id_and_priority, datablock } => {
98                buf.push(request_type::WITH_DATABLOCK);
99                buf.push(*invoke_id_and_priority);
100                datablock.encode(&mut buf);
101            }
102            SetRequest::WithList { invoke_id_and_priority, attributes, values } => {
103                buf.push(request_type::WITH_LIST);
104                buf.push(*invoke_id_and_priority);
105                push_length(attributes.len(), &mut buf);
106                for (attribute, access_selection) in attributes {
107                    attribute.encode(&mut buf);
108                    AccessSelection::encode_into(access_selection, &mut buf)?;
109                }
110                push_length(values.len(), &mut buf);
111                for value in values {
112                    value.serialize_ber(&mut buf)?;
113                }
114            }
115        }
116        Ok(buf)
117    }
118
119    /// Decodes a request APDU.
120    pub fn decode(bytes: &[u8]) -> Result<SetRequest, ServiceError> {
121        if bytes.len() < 3 {
122            return Err(ServiceError::Truncated);
123        }
124        if bytes[0] != tag::SET_REQUEST {
125            return Err(ServiceError::UnexpectedTag(bytes[0]));
126        }
127        let invoke_id_and_priority = bytes[2];
128        match bytes[1] {
129            request_type::NORMAL => {
130                let (attribute, n) = AttributeDescriptor::decode(&bytes[3..])?;
131                let (access_selection, m) = AccessSelection::decode_from(&bytes[3 + n..])?;
132                let (value, _) = CosemDataType::deserialize_ber(&bytes[3 + n + m..])?;
133                Ok(SetRequest::Normal { invoke_id_and_priority, attribute, access_selection, value })
134            }
135            request_type::WITH_FIRST_DATABLOCK => {
136                let (attribute, n) = AttributeDescriptor::decode(&bytes[3..])?;
137                let (access_selection, m) = AccessSelection::decode_from(&bytes[3 + n..])?;
138                let (datablock, _) = DataBlockSa::decode(&bytes[3 + n + m..])?;
139                Ok(SetRequest::WithFirstDatablock { invoke_id_and_priority, attribute, access_selection, datablock })
140            }
141            request_type::WITH_DATABLOCK => {
142                let (datablock, _) = DataBlockSa::decode(&bytes[3..])?;
143                Ok(SetRequest::WithDatablock { invoke_id_and_priority, datablock })
144            }
145            request_type::WITH_LIST => {
146                let (count, header) = read_length(&bytes[3..])?;
147                let mut pos = 3 + header;
148                let mut attributes = Vec::with_capacity(count);
149                for _ in 0..count {
150                    let (attribute, n) = AttributeDescriptor::decode(&bytes[pos..])?;
151                    pos += n;
152                    let (access_selection, m) = AccessSelection::decode_from(&bytes[pos..])?;
153                    pos += m;
154                    attributes.push((attribute, access_selection));
155                }
156                let (vcount, vheader) = read_length(&bytes[pos..])?;
157                pos += vheader;
158                let mut values = Vec::with_capacity(vcount);
159                for _ in 0..vcount {
160                    let (value, rest) = CosemDataType::deserialize_ber(&bytes[pos..])?;
161                    pos = bytes.len() - rest.len();
162                    values.push(value);
163                }
164                Ok(SetRequest::WithList { invoke_id_and_priority, attributes, values })
165            }
166            other => Err(ServiceError::UnexpectedType(other)),
167        }
168    }
169}
170
171/// A SET-Response APDU.
172#[derive(Debug, Clone, PartialEq)]
173pub enum SetResponse {
174    /// SET-RESPONSE-NORMAL: carries a single data-access-result code.
175    Normal {
176        /// The invoke-id and priority byte.
177        invoke_id_and_priority: u8,
178        /// The data-access-result code.
179        result: u8,
180    },
181    /// SET-RESPONSE-DATABLOCK: acknowledges reception of an intermediate block.
182    Datablock {
183        /// The invoke-id and priority byte.
184        invoke_id_and_priority: u8,
185        /// The number of the block being acknowledged.
186        block_number: u32,
187    },
188    /// SET-RESPONSE-LAST-DATABLOCK: acknowledges the last block and delivers the
189    /// result.
190    LastDatablock {
191        /// The invoke-id and priority byte.
192        invoke_id_and_priority: u8,
193        /// The data-access-result code.
194        result: u8,
195        /// The number of the last block.
196        block_number: u32,
197    },
198    /// SET-RESPONSE-WITH-LIST: one data-access-result code per written attribute.
199    WithList {
200        /// The invoke-id and priority byte.
201        invoke_id_and_priority: u8,
202        /// One data-access-result code per attribute, in order.
203        results: Vec<u8>,
204    },
205}
206
207impl SetResponse {
208    /// Encodes the response APDU.
209    pub fn encode(&self) -> Vec<u8> {
210        match self {
211            SetResponse::Normal { invoke_id_and_priority, result } => {
212                vec![tag::SET_RESPONSE, response_type::NORMAL, *invoke_id_and_priority, *result]
213            }
214            SetResponse::Datablock { invoke_id_and_priority, block_number } => {
215                let mut buf = vec![tag::SET_RESPONSE, response_type::DATABLOCK, *invoke_id_and_priority];
216                buf.extend_from_slice(&block_number.to_be_bytes());
217                buf
218            }
219            SetResponse::LastDatablock { invoke_id_and_priority, result, block_number } => {
220                let mut buf = vec![tag::SET_RESPONSE, response_type::LAST_DATABLOCK, *invoke_id_and_priority, *result];
221                buf.extend_from_slice(&block_number.to_be_bytes());
222                buf
223            }
224            SetResponse::WithList { invoke_id_and_priority, results } => {
225                let mut buf = vec![tag::SET_RESPONSE, response_type::WITH_LIST, *invoke_id_and_priority];
226                push_length(results.len(), &mut buf);
227                buf.extend_from_slice(results);
228                buf
229            }
230        }
231    }
232
233    /// Decodes a response APDU.
234    pub fn decode(bytes: &[u8]) -> Result<SetResponse, ServiceError> {
235        if bytes.len() < 4 {
236            return Err(ServiceError::Truncated);
237        }
238        if bytes[0] != tag::SET_RESPONSE {
239            return Err(ServiceError::UnexpectedTag(bytes[0]));
240        }
241        let invoke_id_and_priority = bytes[2];
242        match bytes[1] {
243            response_type::NORMAL => Ok(SetResponse::Normal { invoke_id_and_priority, result: bytes[3] }),
244            response_type::DATABLOCK => {
245                let b = bytes.get(3..7).ok_or(ServiceError::Truncated)?;
246                Ok(SetResponse::Datablock {
247                    invoke_id_and_priority,
248                    block_number: u32::from_be_bytes([b[0], b[1], b[2], b[3]]),
249                })
250            }
251            response_type::LAST_DATABLOCK => {
252                let result = bytes[3];
253                let b = bytes.get(4..8).ok_or(ServiceError::Truncated)?;
254                Ok(SetResponse::LastDatablock {
255                    invoke_id_and_priority,
256                    result,
257                    block_number: u32::from_be_bytes([b[0], b[1], b[2], b[3]]),
258                })
259            }
260            response_type::WITH_LIST => {
261                let (count, header) = read_length(&bytes[3..])?;
262                let start = 3 + header;
263                let results = bytes.get(start..start + count).ok_or(ServiceError::Truncated)?.to_vec();
264                Ok(SetResponse::WithList { invoke_id_and_priority, results })
265            }
266            other => Err(ServiceError::UnexpectedType(other)),
267        }
268    }
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274    use crate::obis::ObisCode;
275    use crate::service::data_access_result;
276
277    #[test]
278    fn set_request_normal_matches_reference_bytes() {
279        // IEC 62056-5-3 Annex F.1 prefix: C1 01 C1 0001 0000800000FF 02 00 09 02 AABB.
280        let req = SetRequest::Normal {
281            invoke_id_and_priority: 0xC1,
282            attribute: AttributeDescriptor::new(1, ObisCode::new(0, 0, 0x80, 0, 0, 0xFF), 2),
283            access_selection: None,
284            value: CosemDataType::OctetString(vec![0xAA, 0xBB]),
285        };
286        assert_eq!(
287            req.encode().unwrap(),
288            vec![0xC1, 0x01, 0xC1, 0x00, 0x01, 0x00, 0x00, 0x80, 0x00, 0x00, 0xFF, 0x02, 0x00, 0x09, 0x02, 0xAA, 0xBB]
289        );
290        assert_eq!(SetRequest::decode(&req.encode().unwrap()).unwrap(), req);
291    }
292
293    #[test]
294    fn set_response_normal_matches_reference_bytes() {
295        // IEC 62056-5-3 Annex F: C5 01 C1 00 (Success).
296        let resp = SetResponse::Normal { invoke_id_and_priority: 0xC1, result: data_access_result::SUCCESS };
297        assert_eq!(resp.encode(), vec![0xC5, 0x01, 0xC1, 0x00]);
298        assert_eq!(SetResponse::decode(&resp.encode()).unwrap(), resp);
299    }
300
301    #[test]
302    fn set_request_with_datablock_matches_reference_bytes() {
303        // IEC 62056-5-3 Annex F.8: C1 03 C1 01 00000003 11 <17 octets>.
304        let raw =
305            vec![0x39, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x50, 0x0A, 0x03, 0x30, 0x30, 0x30];
306        let req = SetRequest::WithDatablock {
307            invoke_id_and_priority: 0xC1,
308            datablock: DataBlockSa { last_block: true, block_number: 3, raw_data: raw },
309        };
310        let bytes = req.encode().unwrap();
311        assert_eq!(&bytes[..6], &[0xC1, 0x03, 0xC1, 0x01, 0x00, 0x00]);
312        assert_eq!(SetRequest::decode(&bytes).unwrap(), req);
313    }
314
315    #[test]
316    fn set_request_with_list_round_trips() {
317        let req = SetRequest::WithList {
318            invoke_id_and_priority: 0xC1,
319            attributes: vec![
320                (AttributeDescriptor::new(1, ObisCode::new(0, 0, 0x80, 0, 0, 0xFF), 2), None),
321                (AttributeDescriptor::new(3, ObisCode::new(1, 0, 1, 8, 0, 0xFF), 2), None),
322            ],
323            values: vec![CosemDataType::Unsigned(1), CosemDataType::LongUnsigned(0x1234)],
324        };
325        let bytes = req.encode().unwrap();
326        // C1 04 C1 02 <attr1> 00 <attr2> 00 02 <11 01> <12 1234>.
327        assert_eq!(bytes[..4], [0xC1, 0x04, 0xC1, 0x02]);
328        assert_eq!(SetRequest::decode(&bytes).unwrap(), req);
329    }
330
331    #[test]
332    fn set_response_with_list_round_trips() {
333        let resp = SetResponse::WithList {
334            invoke_id_and_priority: 0xC1,
335            results: vec![data_access_result::SUCCESS, data_access_result::READ_WRITE_DENIED],
336        };
337        let bytes = resp.encode();
338        // C5 05 C1 02 00 03.
339        assert_eq!(bytes, vec![0xC5, 0x05, 0xC1, 0x02, 0x00, 0x03]);
340        assert_eq!(SetResponse::decode(&bytes).unwrap(), resp);
341    }
342
343    #[test]
344    fn set_response_datablock_variants_round_trip() {
345        let ack = SetResponse::Datablock { invoke_id_and_priority: 0xC1, block_number: 1 };
346        assert_eq!(ack.encode(), vec![0xC5, 0x02, 0xC1, 0x00, 0x00, 0x00, 0x01]);
347        assert_eq!(SetResponse::decode(&ack.encode()).unwrap(), ack);
348
349        let last = SetResponse::LastDatablock { invoke_id_and_priority: 0xC1, result: 0, block_number: 3 };
350        assert_eq!(last.encode(), vec![0xC5, 0x03, 0xC1, 0x00, 0x00, 0x00, 0x00, 0x03]);
351        assert_eq!(SetResponse::decode(&last.encode()).unwrap(), last);
352    }
353}