Skip to main content

spodes_rs/service/
get.rs

1//! The xDLMS GET service (IEC 62056-5-3, 6.9): read one or more COSEM object
2//! attributes.
3//!
4//! Request bytes for GET-REQUEST-NORMAL, from IEC 62056-5-3 Annex F.1:
5//!
6//! ```text
7//! C0 01 C1 0001 0000800000FF 02 00
8//! ^tag                            ^^ access-selection (0 = none)
9//!    ^^ normal   ^^ invoke-id-and-priority
10//!         ^^^^^^^^^^^^^^^^^^^^^^^ attribute descriptor (class-id, obis, attr-id)
11//! ```
12
13use crate::types::CosemDataType;
14
15use super::{tag, AttributeDescriptor, ServiceError};
16
17/// Request-type octets of the GET service.
18mod request_type {
19    pub const NORMAL: u8 = 1;
20    pub const NEXT: u8 = 2;
21    pub const WITH_LIST: u8 = 3;
22}
23
24/// Response-type octets of the GET service.
25mod response_type {
26    pub const NORMAL: u8 = 1;
27    pub const WITH_DATABLOCK: u8 = 2;
28    pub const WITH_LIST: u8 = 3;
29}
30
31/// Optional selective-access parameters attached to an attribute descriptor.
32#[derive(Debug, Clone, PartialEq)]
33pub struct AccessSelection {
34    /// The access selector (which selective-access method to apply).
35    pub selector: u8,
36    /// The selective-access parameters for the chosen selector.
37    pub parameters: CosemDataType,
38}
39
40impl AccessSelection {
41    /// Encodes an optional selective-access descriptor (0x00 = absent).
42    pub fn encode_into(this: &Option<AccessSelection>, buf: &mut Vec<u8>) -> Result<(), ServiceError> {
43        match this {
44            None => buf.push(0x00),
45            Some(sel) => {
46                buf.push(0x01);
47                buf.push(sel.selector);
48                sel.parameters.serialize_ber(buf)?;
49            }
50        }
51        Ok(())
52    }
53
54    /// Decodes an optional selective-access descriptor, returning it and the
55    /// number of octets consumed.
56    pub fn decode_from(bytes: &[u8]) -> Result<(Option<AccessSelection>, usize), ServiceError> {
57        match bytes.first() {
58            Some(0x00) => Ok((None, 1)),
59            Some(0x01) => {
60                let selector = *bytes.get(1).ok_or(ServiceError::Truncated)?;
61                let (parameters, rest) = CosemDataType::deserialize_ber(&bytes[2..])?;
62                let consumed = 2 + (bytes.len() - 2 - rest.len());
63                Ok((Some(AccessSelection { selector, parameters }), consumed))
64            }
65            Some(&other) => Err(ServiceError::UnexpectedType(other)),
66            None => Err(ServiceError::Truncated),
67        }
68    }
69}
70
71/// A GET-Request APDU.
72#[derive(Debug, Clone, PartialEq)]
73pub enum GetRequest {
74    /// GET-REQUEST-NORMAL: read a single attribute.
75    Normal {
76        /// The invoke-id and priority byte.
77        invoke_id_and_priority: u8,
78        /// The attribute to read.
79        attribute: AttributeDescriptor,
80        /// Optional selective access applied to the attribute.
81        access_selection: Option<AccessSelection>,
82    },
83    /// GET-REQUEST-NEXT: request the next data block during block transfer.
84    Next {
85        /// The invoke-id and priority byte.
86        invoke_id_and_priority: u8,
87        /// The number of the block being acknowledged/requested.
88        block_number: u32,
89    },
90    /// GET-REQUEST-WITH-LIST: read several attributes in one request.
91    WithList {
92        /// The invoke-id and priority byte.
93        invoke_id_and_priority: u8,
94        /// Each entry is an attribute descriptor with optional selective access.
95        attributes: Vec<(AttributeDescriptor, Option<AccessSelection>)>,
96    },
97}
98
99impl GetRequest {
100    /// Encodes the request APDU.
101    pub fn encode(&self) -> Result<Vec<u8>, ServiceError> {
102        let mut buf = vec![tag::GET_REQUEST];
103        match self {
104            GetRequest::Normal { invoke_id_and_priority, attribute, access_selection } => {
105                buf.push(request_type::NORMAL);
106                buf.push(*invoke_id_and_priority);
107                attribute.encode(&mut buf);
108                AccessSelection::encode_into(access_selection, &mut buf)?;
109            }
110            GetRequest::Next { invoke_id_and_priority, block_number } => {
111                buf.push(request_type::NEXT);
112                buf.push(*invoke_id_and_priority);
113                buf.extend_from_slice(&block_number.to_be_bytes());
114            }
115            GetRequest::WithList { invoke_id_and_priority, attributes } => {
116                buf.push(request_type::WITH_LIST);
117                buf.push(*invoke_id_and_priority);
118                push_length(attributes.len(), &mut buf);
119                for (attribute, access_selection) in attributes {
120                    attribute.encode(&mut buf);
121                    AccessSelection::encode_into(access_selection, &mut buf)?;
122                }
123            }
124        }
125        Ok(buf)
126    }
127
128    /// Decodes a request APDU.
129    pub fn decode(bytes: &[u8]) -> Result<GetRequest, ServiceError> {
130        if bytes.len() < 3 {
131            return Err(ServiceError::Truncated);
132        }
133        if bytes[0] != tag::GET_REQUEST {
134            return Err(ServiceError::UnexpectedTag(bytes[0]));
135        }
136        let invoke_id_and_priority = bytes[2];
137        match bytes[1] {
138            request_type::NORMAL => {
139                let (attribute, n) = AttributeDescriptor::decode(&bytes[3..])?;
140                let (access_selection, _) = AccessSelection::decode_from(&bytes[3 + n..])?;
141                Ok(GetRequest::Normal { invoke_id_and_priority, attribute, access_selection })
142            }
143            request_type::NEXT => {
144                let b = bytes.get(3..7).ok_or(ServiceError::Truncated)?;
145                let block_number = u32::from_be_bytes([b[0], b[1], b[2], b[3]]);
146                Ok(GetRequest::Next { invoke_id_and_priority, block_number })
147            }
148            request_type::WITH_LIST => {
149                let (count, header) = read_length(&bytes[3..])?;
150                let mut pos = 3 + header;
151                let mut attributes = Vec::with_capacity(count);
152                for _ in 0..count {
153                    let (attribute, n) = AttributeDescriptor::decode(&bytes[pos..])?;
154                    pos += n;
155                    let (access_selection, m) = AccessSelection::decode_from(&bytes[pos..])?;
156                    pos += m;
157                    attributes.push((attribute, access_selection));
158                }
159                Ok(GetRequest::WithList { invoke_id_and_priority, attributes })
160            }
161            other => Err(ServiceError::UnexpectedType(other)),
162        }
163    }
164}
165
166/// The result carried by a GET-RESPONSE-NORMAL: either the attribute value or a
167/// data-access-result code.
168#[derive(Debug, Clone, PartialEq)]
169pub enum GetDataResult {
170    /// The attribute value was read successfully.
171    Data(CosemDataType),
172    /// The read failed with this data-access-result code.
173    AccessResult(u8),
174}
175
176/// A GET-Response APDU.
177#[derive(Debug, Clone, PartialEq)]
178pub enum GetResponse {
179    /// GET-RESPONSE-NORMAL: the full result fits in a single APDU.
180    Normal {
181        /// The invoke-id and priority byte.
182        invoke_id_and_priority: u8,
183        /// The result (value or data-access-result).
184        result: GetDataResult,
185    },
186    /// GET-RESPONSE-WITH-DATABLOCK: one block of a longer result.
187    WithDataBlock {
188        /// The invoke-id and priority byte.
189        invoke_id_and_priority: u8,
190        /// Whether this is the last block of the result.
191        last_block: bool,
192        /// The number of this block.
193        block_number: u32,
194        /// Raw data of this block, or a data-access-result code on failure.
195        raw_data: Result<Vec<u8>, u8>,
196    },
197    /// GET-RESPONSE-WITH-LIST: one result per requested attribute.
198    WithList {
199        /// The invoke-id and priority byte.
200        invoke_id_and_priority: u8,
201        /// One result per attribute of the request, in order.
202        results: Vec<GetDataResult>,
203    },
204}
205
206impl GetResponse {
207    /// Encodes the response APDU.
208    pub fn encode(&self) -> Result<Vec<u8>, ServiceError> {
209        let mut buf = vec![tag::GET_RESPONSE];
210        match self {
211            GetResponse::Normal { invoke_id_and_priority, result } => {
212                buf.push(response_type::NORMAL);
213                buf.push(*invoke_id_and_priority);
214                match result {
215                    GetDataResult::Data(data) => {
216                        buf.push(0x00);
217                        data.serialize_ber(&mut buf)?;
218                    }
219                    GetDataResult::AccessResult(code) => {
220                        buf.push(0x01);
221                        buf.push(*code);
222                    }
223                }
224            }
225            GetResponse::WithDataBlock { invoke_id_and_priority, last_block, block_number, raw_data } => {
226                buf.push(response_type::WITH_DATABLOCK);
227                buf.push(*invoke_id_and_priority);
228                buf.push(u8::from(*last_block));
229                buf.extend_from_slice(&block_number.to_be_bytes());
230                match raw_data {
231                    Ok(data) => {
232                        buf.push(0x00);
233                        push_length(data.len(), &mut buf);
234                        buf.extend_from_slice(data);
235                    }
236                    Err(code) => {
237                        buf.push(0x01);
238                        buf.push(*code);
239                    }
240                }
241            }
242            GetResponse::WithList { invoke_id_and_priority, results } => {
243                buf.push(response_type::WITH_LIST);
244                buf.push(*invoke_id_and_priority);
245                push_length(results.len(), &mut buf);
246                for result in results {
247                    match result {
248                        GetDataResult::Data(data) => {
249                            buf.push(0x00);
250                            data.serialize_ber(&mut buf)?;
251                        }
252                        GetDataResult::AccessResult(code) => {
253                            buf.push(0x01);
254                            buf.push(*code);
255                        }
256                    }
257                }
258            }
259        }
260        Ok(buf)
261    }
262
263    /// Decodes a response APDU.
264    pub fn decode(bytes: &[u8]) -> Result<GetResponse, ServiceError> {
265        if bytes.len() < 3 {
266            return Err(ServiceError::Truncated);
267        }
268        if bytes[0] != tag::GET_RESPONSE {
269            return Err(ServiceError::UnexpectedTag(bytes[0]));
270        }
271        let invoke_id_and_priority = bytes[2];
272        match bytes[1] {
273            response_type::NORMAL => {
274                let choice = *bytes.get(3).ok_or(ServiceError::Truncated)?;
275                let result = match choice {
276                    0x00 => {
277                        let (data, _) = CosemDataType::deserialize_ber(&bytes[4..])?;
278                        GetDataResult::Data(data)
279                    }
280                    0x01 => GetDataResult::AccessResult(*bytes.get(4).ok_or(ServiceError::Truncated)?),
281                    other => return Err(ServiceError::UnexpectedType(other)),
282                };
283                Ok(GetResponse::Normal { invoke_id_and_priority, result })
284            }
285            response_type::WITH_DATABLOCK => {
286                let last_block = *bytes.get(3).ok_or(ServiceError::Truncated)? != 0;
287                let b = bytes.get(4..8).ok_or(ServiceError::Truncated)?;
288                let block_number = u32::from_be_bytes([b[0], b[1], b[2], b[3]]);
289                let choice = *bytes.get(8).ok_or(ServiceError::Truncated)?;
290                let raw_data = match choice {
291                    0x00 => {
292                        let (len, header) = read_length(&bytes[9..])?;
293                        let start = 9 + header;
294                        let slice = bytes.get(start..start + len).ok_or(ServiceError::Truncated)?;
295                        Ok(slice.to_vec())
296                    }
297                    0x01 => Err(*bytes.get(9).ok_or(ServiceError::Truncated)?),
298                    other => return Err(ServiceError::UnexpectedType(other)),
299                };
300                Ok(GetResponse::WithDataBlock { invoke_id_and_priority, last_block, block_number, raw_data })
301            }
302            response_type::WITH_LIST => {
303                let (count, header) = read_length(&bytes[3..])?;
304                let mut pos = 3 + header;
305                let mut results = Vec::with_capacity(count);
306                for _ in 0..count {
307                    let choice = *bytes.get(pos).ok_or(ServiceError::Truncated)?;
308                    pos += 1;
309                    match choice {
310                        0x00 => {
311                            let (data, rest) = CosemDataType::deserialize_ber(&bytes[pos..])?;
312                            pos = bytes.len() - rest.len();
313                            results.push(GetDataResult::Data(data));
314                        }
315                        0x01 => {
316                            results.push(GetDataResult::AccessResult(*bytes.get(pos).ok_or(ServiceError::Truncated)?));
317                            pos += 1;
318                        }
319                        other => return Err(ServiceError::UnexpectedType(other)),
320                    }
321                }
322                Ok(GetResponse::WithList { invoke_id_and_priority, results })
323            }
324            other => Err(ServiceError::UnexpectedType(other)),
325        }
326    }
327}
328
329/// Writes an A-XDR length octet (short or long form).
330#[allow(clippy::cast_possible_truncation)] // length < 128 and n in 1..=8 always fit u8
331fn push_length(length: usize, buf: &mut Vec<u8>) {
332    if length < 128 {
333        buf.push(length as u8);
334    } else {
335        let bytes = (length as u64).to_be_bytes();
336        let first = bytes.iter().position(|&b| b != 0).unwrap_or(7);
337        let n = 8 - first;
338        buf.push(0x80 | n as u8);
339        buf.extend_from_slice(&bytes[first..]);
340    }
341}
342
343/// Reads an A-XDR length octet, returning the length and the octets consumed.
344fn read_length(bytes: &[u8]) -> Result<(usize, usize), ServiceError> {
345    let first = *bytes.first().ok_or(ServiceError::Truncated)?;
346    if first < 128 {
347        Ok((first as usize, 1))
348    } else {
349        let n = (first & 0x7F) as usize;
350        let slice = bytes.get(1..1 + n).ok_or(ServiceError::Truncated)?;
351        let mut len = 0usize;
352        for &b in slice {
353            len = (len << 8) | b as usize;
354        }
355        Ok((len, 1 + n))
356    }
357}
358
359#[cfg(test)]
360mod tests {
361    use super::*;
362    use crate::obis::ObisCode;
363    use crate::service::invoke_id_and_priority;
364
365    #[test]
366    fn get_request_normal_matches_reference_bytes() {
367        // IEC 62056-5-3 Annex F.1: C0 01 C1 0001 0000800000FF 02 00.
368        let req = GetRequest::Normal {
369            invoke_id_and_priority: invoke_id_and_priority(1, true, true),
370            attribute: AttributeDescriptor::new(1, ObisCode::new(0, 0, 0x80, 0, 0, 0xFF), 2),
371            access_selection: None,
372        };
373        assert_eq!(
374            req.encode().unwrap(),
375            vec![0xC0, 0x01, 0xC1, 0x00, 0x01, 0x00, 0x00, 0x80, 0x00, 0x00, 0xFF, 0x02, 0x00]
376        );
377        assert_eq!(GetRequest::decode(&req.encode().unwrap()).unwrap(), req);
378    }
379
380    #[test]
381    fn get_request_next_round_trips() {
382        let req = GetRequest::Next { invoke_id_and_priority: 0xC1, block_number: 1 };
383        let bytes = req.encode().unwrap();
384        assert_eq!(bytes, vec![0xC0, 0x02, 0xC1, 0x00, 0x00, 0x00, 0x01]);
385        assert_eq!(GetRequest::decode(&bytes).unwrap(), req);
386    }
387
388    #[test]
389    fn get_response_normal_with_data_round_trips() {
390        let resp = GetResponse::Normal {
391            invoke_id_and_priority: 0xC1,
392            result: GetDataResult::Data(CosemDataType::LongUnsigned(0x1234)),
393        };
394        let bytes = resp.encode().unwrap();
395        // C4 01 C1 00 <12 12 34> ; long-unsigned tag 0x12.
396        assert_eq!(bytes, vec![0xC4, 0x01, 0xC1, 0x00, 0x12, 0x12, 0x34]);
397        assert_eq!(GetResponse::decode(&bytes).unwrap(), resp);
398    }
399
400    #[test]
401    fn get_response_normal_with_access_result_round_trips() {
402        let resp = GetResponse::Normal {
403            invoke_id_and_priority: 0xC1,
404            result: GetDataResult::AccessResult(super::super::data_access_result::OBJECT_UNDEFINED),
405        };
406        let bytes = resp.encode().unwrap();
407        assert_eq!(bytes, vec![0xC4, 0x01, 0xC1, 0x01, 0x04]);
408        assert_eq!(GetResponse::decode(&bytes).unwrap(), resp);
409    }
410
411    #[test]
412    fn get_request_with_list_round_trips() {
413        let req = GetRequest::WithList {
414            invoke_id_and_priority: 0xC1,
415            attributes: vec![
416                (AttributeDescriptor::new(1, ObisCode::new(0, 0, 0x80, 0, 0, 0xFF), 2), None),
417                (AttributeDescriptor::new(8, ObisCode::new(0, 0, 1, 0, 0, 0xFF), 2), None),
418            ],
419        };
420        let bytes = req.encode().unwrap();
421        // C0 03 C1 02 <attr1 9> 00 <attr2 9> 00.
422        assert_eq!(bytes[..4], [0xC0, 0x03, 0xC1, 0x02]);
423        assert_eq!(GetRequest::decode(&bytes).unwrap(), req);
424    }
425
426    #[test]
427    fn get_response_with_list_round_trips() {
428        let resp = GetResponse::WithList {
429            invoke_id_and_priority: 0xC1,
430            results: vec![
431                GetDataResult::Data(CosemDataType::LongUnsigned(0x1234)),
432                GetDataResult::AccessResult(super::super::data_access_result::OBJECT_UNDEFINED),
433            ],
434        };
435        let bytes = resp.encode().unwrap();
436        // C4 03 C1 02 00 <12 12 34> 01 04.
437        assert_eq!(bytes, vec![0xC4, 0x03, 0xC1, 0x02, 0x00, 0x12, 0x12, 0x34, 0x01, 0x04]);
438        assert_eq!(GetResponse::decode(&bytes).unwrap(), resp);
439    }
440
441    #[test]
442    fn get_response_with_datablock_round_trips() {
443        let resp = GetResponse::WithDataBlock {
444            invoke_id_and_priority: 0xC1,
445            last_block: false,
446            block_number: 1,
447            raw_data: Ok(vec![0x02, 0x00, 0x09]),
448        };
449        let bytes = resp.encode().unwrap();
450        // C4 02 C1 00 00000001 00 03 020009.
451        assert_eq!(bytes, vec![0xC4, 0x02, 0xC1, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x02, 0x00, 0x09]);
452        assert_eq!(GetResponse::decode(&bytes).unwrap(), resp);
453    }
454}