Skip to main content

spodes_rs/service/
mod.rs

1//! Application-layer xDLMS services with LN referencing (IEC 62056-5-3).
2//!
3//! Each service is modelled as request/response APDUs that encode to and decode
4//! from the byte payloads carried by the [`crate::transport`] data-link layer.
5//! Common building blocks — the invoke-id-and-priority octet, the COSEM
6//! attribute/method descriptors and the data-access-result codes — live here;
7//! the individual services are in the sub-modules.
8
9use crate::obis::ObisCode;
10use crate::types::BerError;
11
12pub mod acse;
13pub mod action;
14pub mod ciphering;
15pub mod error;
16pub mod gbt;
17pub mod general_ciphering;
18pub mod get;
19pub mod initiate;
20pub mod notification;
21pub mod set;
22
23/// APDU tags of the xDLMS services (LN referencing), IEC 62056-5-3 Table 60.
24pub mod tag {
25    /// `data-notification` (tag 15).
26    pub const DATA_NOTIFICATION: u8 = 0x0F;
27    /// `get-request` (tag 192).
28    pub const GET_REQUEST: u8 = 0xC0;
29    /// `set-request` (tag 193).
30    pub const SET_REQUEST: u8 = 0xC1;
31    /// `event-notification-request` (tag 194).
32    pub const EVENT_NOTIFICATION_REQUEST: u8 = 0xC2;
33    /// `action-request` (tag 195).
34    pub const ACTION_REQUEST: u8 = 0xC3;
35    /// `get-response` (tag 196).
36    pub const GET_RESPONSE: u8 = 0xC4;
37    /// `set-response` (tag 197).
38    pub const SET_RESPONSE: u8 = 0xC5;
39    /// `action-response` (tag 199).
40    pub const ACTION_RESPONSE: u8 = 0xC7;
41    /// `exception-response` (tag 216).
42    pub const EXCEPTION_RESPONSE: u8 = 0xD8;
43    /// `confirmed-service-error` (tag 14).
44    pub const CONFIRMED_SERVICE_ERROR: u8 = 0x0E;
45}
46
47/// `Data-Access-Result` codes (IEC 62056-5-3). Returned by GET/SET and, for the
48/// optional return parameters, by ACTION.
49pub mod data_access_result {
50    /// The access succeeded.
51    pub const SUCCESS: u8 = 0;
52    /// Hardware fault.
53    pub const HARDWARE_FAULT: u8 = 1;
54    /// Temporary failure.
55    pub const TEMPORARY_FAILURE: u8 = 2;
56    /// Read or write denied.
57    pub const READ_WRITE_DENIED: u8 = 3;
58    /// The object is not defined.
59    pub const OBJECT_UNDEFINED: u8 = 4;
60    /// The object class is inconsistent with the request.
61    pub const OBJECT_CLASS_INCONSISTENT: u8 = 9;
62    /// The object is unavailable.
63    pub const OBJECT_UNAVAILABLE: u8 = 11;
64    /// The supplied type does not match the attribute.
65    pub const TYPE_UNMATCHED: u8 = 12;
66    /// The scope of access was violated.
67    pub const SCOPE_OF_ACCESS_VIOLATED: u8 = 13;
68    /// The requested data block is unavailable.
69    pub const DATA_BLOCK_UNAVAILABLE: u8 = 14;
70    /// The long GET was aborted.
71    pub const LONG_GET_ABORTED: u8 = 15;
72    /// No long GET is in progress.
73    pub const NO_LONG_GET_IN_PROGRESS: u8 = 16;
74    /// The long SET was aborted.
75    pub const LONG_SET_ABORTED: u8 = 17;
76    /// No long SET is in progress.
77    pub const NO_LONG_SET_IN_PROGRESS: u8 = 18;
78    /// The data-block number is invalid.
79    pub const DATA_BLOCK_NUMBER_INVALID: u8 = 19;
80    /// Other reason.
81    pub const OTHER_REASON: u8 = 250;
82}
83
84/// Errors that can occur while decoding a service APDU.
85#[derive(Debug, PartialEq, Eq)]
86pub enum ServiceError {
87    /// The APDU tag was not the expected one.
88    UnexpectedTag(u8),
89    /// The request/response type octet was not the expected one.
90    UnexpectedType(u8),
91    /// The APDU ended before all mandatory fields were read.
92    Truncated,
93    /// A value did not conform to the expected encoding.
94    InvalidData,
95}
96
97impl std::fmt::Display for ServiceError {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        write!(f, "{self:?}")
100    }
101}
102
103impl std::error::Error for ServiceError {}
104
105impl From<ServiceError> for std::io::Error {
106    fn from(e: ServiceError) -> Self {
107        std::io::Error::new(std::io::ErrorKind::InvalidData, e)
108    }
109}
110
111impl From<BerError> for ServiceError {
112    fn from(_: BerError) -> Self {
113        ServiceError::InvalidData
114    }
115}
116
117/// Builds the invoke-id-and-priority octet: bits 0..3 the invoke id, bit 6 the
118/// service class (1 = confirmed), bit 7 the priority (1 = high).
119pub fn invoke_id_and_priority(invoke_id: u8, confirmed: bool, high_priority: bool) -> u8 {
120    (invoke_id & 0x0F) | if confirmed { 0x40 } else { 0x00 } | if high_priority { 0x80 } else { 0x00 }
121}
122
123/// A COSEM attribute descriptor: the (class-id, instance-id, attribute-id)
124/// triple that references one attribute of one object instance. Encoded as
125/// 2 + 6 + 1 = 9 raw octets.
126#[derive(Debug, Clone, PartialEq)]
127pub struct AttributeDescriptor {
128    /// Interface class id of the referenced object.
129    pub class_id: u16,
130    /// Logical name (OBIS) of the object instance.
131    pub instance_id: ObisCode,
132    /// Attribute index within the object.
133    pub attribute_id: i8,
134}
135
136impl AttributeDescriptor {
137    /// Creates an attribute descriptor.
138    pub fn new(class_id: u16, instance_id: ObisCode, attribute_id: i8) -> Self {
139        AttributeDescriptor { class_id, instance_id, attribute_id }
140    }
141
142    /// Appends the 9-octet encoding to `buf`.
143    pub fn encode(&self, buf: &mut Vec<u8>) {
144        buf.extend_from_slice(&self.class_id.to_be_bytes());
145        buf.extend_from_slice(&self.instance_id.to_bytes());
146        // Raw octet round-tripped bit-for-bit via `as i8` on decode.
147        #[allow(clippy::cast_sign_loss)]
148        buf.push(self.attribute_id as u8);
149    }
150
151    /// Decodes a descriptor, returning it and the 9 octets consumed.
152    pub fn decode(bytes: &[u8]) -> Result<(AttributeDescriptor, usize), ServiceError> {
153        if bytes.len() < 9 {
154            return Err(ServiceError::Truncated);
155        }
156        let class_id = u16::from_be_bytes([bytes[0], bytes[1]]);
157        let o = &bytes[2..8];
158        let instance_id = ObisCode::new(o[0], o[1], o[2], o[3], o[4], o[5]);
159        // Raw octet round-tripped bit-for-bit from `attribute_id as u8` on encode.
160        #[allow(clippy::cast_possible_wrap)]
161        let attribute_id = bytes[8] as i8;
162        Ok((AttributeDescriptor { class_id, instance_id, attribute_id }, 9))
163    }
164}
165
166/// A COSEM method descriptor: the (class-id, instance-id, method-id) triple that
167/// references one method of one object instance. Encoded as 9 raw octets.
168#[derive(Debug, Clone, PartialEq)]
169pub struct MethodDescriptor {
170    /// Interface class id of the referenced object.
171    pub class_id: u16,
172    /// Logical name (OBIS) of the object instance.
173    pub instance_id: ObisCode,
174    /// Method index within the object.
175    pub method_id: i8,
176}
177
178impl MethodDescriptor {
179    /// Creates a method descriptor.
180    pub fn new(class_id: u16, instance_id: ObisCode, method_id: i8) -> Self {
181        MethodDescriptor { class_id, instance_id, method_id }
182    }
183
184    /// Appends the 9-octet encoding to `buf`.
185    pub fn encode(&self, buf: &mut Vec<u8>) {
186        buf.extend_from_slice(&self.class_id.to_be_bytes());
187        buf.extend_from_slice(&self.instance_id.to_bytes());
188        // Raw octet round-tripped bit-for-bit via `as i8` on decode.
189        #[allow(clippy::cast_sign_loss)]
190        buf.push(self.method_id as u8);
191    }
192
193    /// Decodes a descriptor, returning it and the 9 octets consumed.
194    pub fn decode(bytes: &[u8]) -> Result<(MethodDescriptor, usize), ServiceError> {
195        if bytes.len() < 9 {
196            return Err(ServiceError::Truncated);
197        }
198        let class_id = u16::from_be_bytes([bytes[0], bytes[1]]);
199        let o = &bytes[2..8];
200        let instance_id = ObisCode::new(o[0], o[1], o[2], o[3], o[4], o[5]);
201        // Raw octet round-tripped bit-for-bit from `method_id as u8` on encode.
202        #[allow(clippy::cast_possible_wrap)]
203        let method_id = bytes[8] as i8;
204        Ok((MethodDescriptor { class_id, instance_id, method_id }, 9))
205    }
206}
207
208/// `DataBlock-SA`: one block of a SET/ACTION block transfer. Encoded as
209/// `last-block (boolean) ‖ block-number (u32) ‖ raw-data (A-XDR octet-string)`.
210#[derive(Debug, Clone, PartialEq, Eq)]
211pub struct DataBlockSa {
212    /// Whether this is the last block of the transfer.
213    pub last_block: bool,
214    /// The block number.
215    pub block_number: u32,
216    /// The raw block data.
217    pub raw_data: Vec<u8>,
218}
219
220/// A raw APDU with an arbitrary tag and body.
221///
222/// This type allows sending and receiving APDUs without parsing their content,
223/// which is useful for manufacturer-specific or extension APDUs.
224#[derive(Debug, Clone, PartialEq, Eq)]
225pub struct RawApdu {
226    /// The APDU tag byte.
227    pub tag: u8,
228    /// The raw body bytes (after the length octet).
229    pub body: Vec<u8>,
230}
231
232impl RawApdu {
233    /// Creates a new raw APDU with the given tag and body.
234    pub fn new(tag: u8, body: Vec<u8>) -> Self {
235        RawApdu { tag, body }
236    }
237
238    /// Creates a raw APDU from a complete byte slice (tag + length + body).
239    pub fn from_bytes(bytes: &[u8]) -> Result<Self, ServiceError> {
240        if bytes.is_empty() {
241            return Err(ServiceError::Truncated);
242        }
243        let tag = bytes[0];
244        let (len, header) = read_length(&bytes[1..])?;
245        let start = 1 + header;
246        let body = bytes.get(start..start + len).ok_or(ServiceError::Truncated)?.to_vec();
247        Ok(RawApdu { tag, body })
248    }
249
250    /// Encodes the APDU to bytes (tag + length + body).
251    pub fn encode(&self) -> Vec<u8> {
252        let mut buf = Vec::with_capacity(2 + self.body.len());
253        buf.push(self.tag);
254        push_length(self.body.len(), &mut buf);
255        buf.extend_from_slice(&self.body);
256        buf
257    }
258
259    /// Returns the tag byte.
260    pub fn tag(&self) -> u8 {
261        self.tag
262    }
263
264    /// Returns the body bytes.
265    pub fn body(&self) -> &[u8] {
266        &self.body
267    }
268
269    /// Returns the body as a mutable slice.
270    pub fn body_mut(&mut self) -> &mut Vec<u8> {
271        &mut self.body
272    }
273
274    /// Consumes the APDU and returns the tag and body.
275    pub fn into_parts(self) -> (u8, Vec<u8>) {
276        (self.tag, self.body)
277    }
278}
279
280impl DataBlockSa {
281    /// Appends the block encoding to `buf`.
282    pub fn encode(&self, buf: &mut Vec<u8>) {
283        buf.push(u8::from(self.last_block));
284        buf.extend_from_slice(&self.block_number.to_be_bytes());
285        push_length(self.raw_data.len(), buf);
286        buf.extend_from_slice(&self.raw_data);
287    }
288
289    /// Decodes a block, returning it and the octets consumed.
290    pub fn decode(bytes: &[u8]) -> Result<(DataBlockSa, usize), ServiceError> {
291        let last_block = *bytes.first().ok_or(ServiceError::Truncated)? != 0;
292        let b = bytes.get(1..5).ok_or(ServiceError::Truncated)?;
293        let block_number = u32::from_be_bytes([b[0], b[1], b[2], b[3]]);
294        let (len, header) = read_length(&bytes[5..])?;
295        let start = 5 + header;
296        let raw_data = bytes.get(start..start + len).ok_or(ServiceError::Truncated)?.to_vec();
297        Ok((DataBlockSa { last_block, block_number, raw_data }, start + len))
298    }
299}
300
301/// Writes an A-XDR length octet (short or long form).
302#[allow(clippy::cast_possible_truncation)] // length < 128 and n in 1..=8 always fit u8
303pub(crate) fn push_length(length: usize, buf: &mut Vec<u8>) {
304    if length < 128 {
305        buf.push(length as u8);
306    } else {
307        let bytes = (length as u64).to_be_bytes();
308        let first = bytes.iter().position(|&b| b != 0).unwrap_or(7);
309        let n = 8 - first;
310        buf.push(0x80 | n as u8);
311        buf.extend_from_slice(&bytes[first..]);
312    }
313}
314
315/// Reads an A-XDR length octet, returning the length and octets consumed.
316pub(crate) fn read_length(bytes: &[u8]) -> Result<(usize, usize), ServiceError> {
317    let first = *bytes.first().ok_or(ServiceError::Truncated)?;
318    if first < 128 {
319        Ok((first as usize, 1))
320    } else {
321        let n = (first & 0x7F) as usize;
322        let slice = bytes.get(1..1 + n).ok_or(ServiceError::Truncated)?;
323        let mut len = 0usize;
324        for &b in slice {
325            len = (len << 8) | b as usize;
326        }
327        Ok((len, 1 + n))
328    }
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334
335    #[test]
336    fn invoke_id_and_priority_bits() {
337        // invoke-id 1, confirmed, high priority → 0xC1 (as in IEC 62056-5-3 Annex F).
338        assert_eq!(invoke_id_and_priority(1, true, true), 0xC1);
339        assert_eq!(invoke_id_and_priority(0, false, false), 0x00);
340    }
341
342    #[test]
343    fn attribute_descriptor_round_trips() {
344        let d = AttributeDescriptor::new(1, ObisCode::new(0, 0, 0x80, 0, 0, 0xFF), 2);
345        let mut buf = Vec::new();
346        d.encode(&mut buf);
347        // class-id 0001, instance 0000800000FF, attr 02.
348        assert_eq!(buf, vec![0x00, 0x01, 0x00, 0x00, 0x80, 0x00, 0x00, 0xFF, 0x02]);
349        let (decoded, n) = AttributeDescriptor::decode(&buf).unwrap();
350        assert_eq!(n, 9);
351        assert_eq!(decoded, d);
352    }
353
354    #[test]
355    fn method_descriptor_round_trips() {
356        let d = MethodDescriptor::new(70, ObisCode::new(0, 0, 96, 3, 10, 255), 1);
357        let mut buf = Vec::new();
358        d.encode(&mut buf);
359        let (decoded, n) = MethodDescriptor::decode(&buf).unwrap();
360        assert_eq!(n, 9);
361        assert_eq!(decoded, d);
362    }
363
364    #[test]
365    fn data_block_sa_round_trips() {
366        let block = DataBlockSa { last_block: true, block_number: 3, raw_data: vec![0x0A; 17] };
367        let mut buf = Vec::new();
368        block.encode(&mut buf);
369        // 01 00000003 11 <17 octets> — as in IEC 62056-5-3 Annex F.8.
370        assert_eq!(buf[..6], [0x01, 0x00, 0x00, 0x00, 0x03, 0x11]);
371        let (decoded, n) = DataBlockSa::decode(&buf).unwrap();
372        assert_eq!(n, buf.len());
373        assert_eq!(decoded, block);
374    }
375
376    #[test]
377    fn raw_apdu_encode_decode_round_trip() {
378        let raw = RawApdu::new(0xC0, vec![0x01, 0x02, 0x03]);
379        let encoded = raw.encode();
380        let decoded = RawApdu::from_bytes(&encoded).unwrap();
381        assert_eq!(decoded.tag(), 0xC0);
382        assert_eq!(decoded.body(), &[0x01, 0x02, 0x03]);
383    }
384
385    #[test]
386    fn raw_apdu_from_bytes_with_length() {
387        // tag=0xC1, length=5, body=[0xAA; 5]
388        let bytes = vec![0xC1, 0x05, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA];
389        let raw = RawApdu::from_bytes(&bytes).unwrap();
390        assert_eq!(raw.tag(), 0xC1);
391        assert_eq!(raw.body(), &[0xAA; 5]);
392    }
393
394    #[test]
395    fn raw_apdu_empty_body() {
396        let raw = RawApdu::new(0xC2, vec![]);
397        let encoded = raw.encode();
398        assert_eq!(encoded, vec![0xC2, 0x00]);
399        let decoded = RawApdu::from_bytes(&encoded).unwrap();
400        assert!(decoded.body().is_empty());
401    }
402
403    #[test]
404    fn raw_apdu_truncated_returns_error() {
405        let bytes = vec![0xC0]; // tag only, no length
406        assert!(RawApdu::from_bytes(&bytes).is_err());
407    }
408
409    #[test]
410    fn raw_apdu_mutable_body() {
411        let mut raw = RawApdu::new(0xC3, vec![0x01]);
412        raw.body_mut().push(0x02);
413        assert_eq!(raw.body(), &[0x01, 0x02]);
414    }
415}