Skip to main content

dlms_cosem_kit/xdlms/
sn.rs

1//! Short-name referencing: the Read, Write and report services.
2//!
3//! Logical-name referencing names an attribute by `(class_id, logical name, index)` —
4//! sixteen bytes. Short-name referencing names the same attribute by a **sixteen-bit
5//! number**. An installed base of meters built before logical names became universal
6//! speaks it, and nothing else.
7//!
8//! [`ReadRequest`], [`WriteRequest`], [`UnconfirmedWriteRequest`] and
9//! [`InformationReportRequest`] are the four services. All are lists, and all address
10//! their targets through [`VariableAccess`].
11//!
12//! There is no ACTION service: a method is invoked by *writing* its short name, with the
13//! value as the parameter. [`crate::cosem::ShortName`] turns a base name into a short
14//! name and back.
15
16use crate::axdr::Data;
17use crate::codec::{Decode, Encode, ErrorKind, Reader, Result, Writer};
18
19use super::result::{DataAccessResult, List};
20
21/// A sixteen-bit short name.
22///
23/// The Blue Book calls this an `ObjectName`. The low three bits of a *named-variable*
24/// short name are zero, and `0xFA00` is the base name of the current association object
25/// in every short-name logical device.
26pub type ObjectName = u16;
27
28/// The base name of the current association object in a short-name logical device.
29pub const CURRENT_ASSOCIATION_SN: ObjectName = 0xFA00;
30
31/// How far apart consecutive attributes of one object sit.
32///
33/// Confirmed twice: attribute *n* of an object based at `x` is `x + (n − 1) × 8`.
34pub const ATTRIBUTE_STRIDE: u16 = 8;
35
36/// What a Read, Write or report entry addresses.
37///
38/// The `detailed-access` choice `[3]` is defined in the ASN.1 and explicitly not used in
39/// DLMS/COSEM, so it is not here: decoding a tag no conformant peer sends buys nothing
40/// and widens a parser that faces the network.
41#[derive(Debug, Clone, Copy, PartialEq)]
42pub enum VariableAccess<'a> {
43    /// An attribute or a method, by short name.
44    VariableName(ObjectName),
45    /// An attribute with a selective-access descriptor, or a method with its parameter —
46    /// short-name referencing has one shape for both.
47    Parameterized {
48        /// Which attribute or method.
49        name: ObjectName,
50        /// Which selector, or which method invocation the profile defines.
51        selector: u8,
52        /// The selector's parameter.
53        parameter: Data<'a>,
54    },
55    /// Ask for the next block of a long read.
56    BlockNumber(u16),
57    /// One block of a long write going up.
58    ReadDataBlock {
59        /// True when no further block follows.
60        last_block: bool,
61        /// This block's number.
62        block_number: u16,
63        /// The fragment.
64        raw_data: &'a [u8],
65    },
66    /// Acknowledge a block of a long write.
67    WriteDataBlock {
68        /// True when no further block follows.
69        last_block: bool,
70        /// The block being acknowledged.
71        block_number: u16,
72    },
73}
74
75impl VariableAccess<'_> {
76    /// The short name this entry addresses, for the two forms that name one.
77    #[must_use]
78    pub const fn name(&self) -> Option<ObjectName> {
79        match self {
80            Self::VariableName(n) | Self::Parameterized { name: n, .. } => Some(*n),
81            _ => None,
82        }
83    }
84}
85
86impl Encode for VariableAccess<'_> {
87    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
88        match self {
89            Self::VariableName(name) => {
90                w.write_u8(2)?;
91                w.write_u16(*name)
92            }
93            Self::Parameterized { name, selector, parameter } => {
94                w.write_u8(4)?;
95                w.write_u16(*name)?;
96                w.write_u8(*selector)?;
97                parameter.encode(w)
98            }
99            Self::BlockNumber(n) => {
100                w.write_u8(5)?;
101                w.write_u16(*n)
102            }
103            Self::ReadDataBlock { last_block, block_number, raw_data } => {
104                w.write_u8(6)?;
105                w.write_u8(u8::from(*last_block))?;
106                w.write_u16(*block_number)?;
107                w.write_length_prefixed(raw_data)
108            }
109            Self::WriteDataBlock { last_block, block_number } => {
110                w.write_u8(7)?;
111                w.write_u8(u8::from(*last_block))?;
112                w.write_u16(*block_number)
113            }
114        }
115    }
116}
117
118impl<'a> Decode<'a> for VariableAccess<'a> {
119    fn decode(r: &mut Reader<'a>) -> Result<Self> {
120        Ok(match r.u8()? {
121            2 => Self::VariableName(r.u16()?),
122            4 => Self::Parameterized { name: r.u16()?, selector: r.u8()?, parameter: Data::decode(r)? },
123            5 => Self::BlockNumber(r.u16()?),
124            6 => Self::ReadDataBlock {
125                last_block: r.u8()? != 0,
126                block_number: r.u16()?,
127                raw_data: r.length_prefixed()?,
128            },
129            7 => Self::WriteDataBlock { last_block: r.u8()? != 0, block_number: r.u16()? },
130            other => return Err(r.err_back(ErrorKind::InvalidTag(other), 1)),
131        })
132    }
133}
134
135/// Read one or more attributes by short name.
136#[derive(Debug, Clone, Copy, PartialEq)]
137pub struct ReadRequest<'a> {
138    /// What to read, in order. The answers come back in the same order.
139    pub specification: List<'a, VariableAccess<'a>>,
140}
141
142impl Encode for ReadRequest<'_> {
143    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
144        self.specification.encode(w)
145    }
146}
147
148impl<'a> Decode<'a> for ReadRequest<'a> {
149    fn decode(r: &mut Reader<'a>) -> Result<Self> {
150        Ok(Self { specification: List::decode(r)? })
151    }
152}
153
154/// One answer inside a [`ReadResponse`].
155#[derive(Debug, Clone, Copy, PartialEq)]
156pub enum ReadResult<'a> {
157    /// The value.
158    Data(Data<'a>),
159    /// Why there is none.
160    Error(DataAccessResult),
161    /// One fragment of a value too large for the negotiated PDU size. Ask for the next
162    /// with [`VariableAccess::BlockNumber`].
163    Block {
164        /// True when no further block follows.
165        last_block: bool,
166        /// This block's number.
167        block_number: u16,
168        /// The fragment.
169        raw_data: &'a [u8],
170    },
171    /// The server has accepted a block of a long *write* and names it.
172    BlockNumber(u16),
173}
174
175impl Encode for ReadResult<'_> {
176    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
177        match self {
178            Self::Data(d) => {
179                w.write_u8(0)?;
180                d.encode(w)
181            }
182            Self::Error(e) => {
183                w.write_u8(1)?;
184                w.write_u8(e.as_u8())
185            }
186            Self::Block { last_block, block_number, raw_data } => {
187                w.write_u8(2)?;
188                w.write_u8(u8::from(*last_block))?;
189                w.write_u16(*block_number)?;
190                w.write_length_prefixed(raw_data)
191            }
192            Self::BlockNumber(n) => {
193                w.write_u8(3)?;
194                w.write_u16(*n)
195            }
196        }
197    }
198}
199
200impl<'a> Decode<'a> for ReadResult<'a> {
201    fn decode(r: &mut Reader<'a>) -> Result<Self> {
202        Ok(match r.u8()? {
203            0 => Self::Data(Data::decode(r)?),
204            1 => Self::Error(DataAccessResult::from_u8(r.u8()?)),
205            2 => Self::Block {
206                last_block: r.u8()? != 0,
207                block_number: r.u16()?,
208                raw_data: r.length_prefixed()?,
209            },
210            3 => Self::BlockNumber(r.u16()?),
211            other => return Err(r.err_back(ErrorKind::InvalidTag(other), 1)),
212        })
213    }
214}
215
216/// The answer to a [`ReadRequest`]: one result per entry, in order.
217#[derive(Debug, Clone, Copy, PartialEq)]
218pub struct ReadResponse<'a> {
219    /// One per entry of the request.
220    pub results: List<'a, ReadResult<'a>>,
221}
222
223impl Encode for ReadResponse<'_> {
224    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
225        self.results.encode(w)
226    }
227}
228
229impl<'a> Decode<'a> for ReadResponse<'a> {
230    fn decode(r: &mut Reader<'a>) -> Result<Self> {
231        Ok(Self { results: List::decode(r)? })
232    }
233}
234
235/// Write one or more attributes by short name.
236///
237/// The two lists are **positional**: value *i* is written to entry *i*. A request whose
238/// lists are different lengths names writes whose values cannot be found, and is refused
239/// rather than paired up as far as it goes.
240#[derive(Debug, Clone, Copy, PartialEq)]
241pub struct WriteRequest<'a> {
242    /// What to write to, in order.
243    pub specification: List<'a, VariableAccess<'a>>,
244    /// The values, in the same order.
245    pub values: List<'a, Data<'a>>,
246}
247
248impl Encode for WriteRequest<'_> {
249    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
250        self.specification.encode(w)?;
251        self.values.encode(w)
252    }
253}
254
255impl<'a> Decode<'a> for WriteRequest<'a> {
256    fn decode(r: &mut Reader<'a>) -> Result<Self> {
257        Ok(Self { specification: List::decode(r)?, values: List::decode(r)? })
258    }
259}
260
261/// One outcome inside a [`WriteResponse`].
262#[derive(Debug, Clone, Copy, PartialEq, Eq)]
263pub enum WriteResult {
264    /// The write succeeded.
265    Success,
266    /// Why it did not.
267    Error(DataAccessResult),
268    /// A block of a long write was accepted, and this is its number.
269    BlockNumber(u16),
270}
271
272impl Encode for WriteResult {
273    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
274        match self {
275            Self::Success => w.write_u8(0),
276            Self::Error(e) => {
277                w.write_u8(1)?;
278                w.write_u8(e.as_u8())
279            }
280            Self::BlockNumber(n) => {
281                w.write_u8(2)?;
282                w.write_u16(*n)
283            }
284        }
285    }
286
287    fn encoded_len(&self) -> usize {
288        match self {
289            Self::Success => 1,
290            Self::Error(_) => 2,
291            Self::BlockNumber(_) => 3,
292        }
293    }
294}
295
296impl<'a> Decode<'a> for WriteResult {
297    fn decode(r: &mut Reader<'a>) -> Result<Self> {
298        Ok(match r.u8()? {
299            0 => Self::Success,
300            1 => Self::Error(DataAccessResult::from_u8(r.u8()?)),
301            2 => Self::BlockNumber(r.u16()?),
302            other => return Err(r.err_back(ErrorKind::InvalidTag(other), 1)),
303        })
304    }
305}
306
307/// The answer to a [`WriteRequest`]: one outcome per entry, in order.
308#[derive(Debug, Clone, Copy, PartialEq)]
309pub struct WriteResponse<'a> {
310    /// One per entry of the request.
311    pub results: List<'a, WriteResult>,
312}
313
314impl Encode for WriteResponse<'_> {
315    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
316        self.results.encode(w)
317    }
318}
319
320impl<'a> Decode<'a> for WriteResponse<'a> {
321    fn decode(r: &mut Reader<'a>) -> Result<Self> {
322        Ok(Self { results: List::decode(r)? })
323    }
324}
325
326/// A write the server does not answer.
327///
328/// The same body as [`WriteRequest`] under a tag of its own. Worth having as a distinct
329/// type rather than a flag: a caller that sends one must not then wait for a reply, and
330/// a type that cannot produce a response is how that is said.
331#[derive(Debug, Clone, Copy, PartialEq)]
332pub struct UnconfirmedWriteRequest<'a> {
333    /// What to write to, in order.
334    pub specification: List<'a, VariableAccess<'a>>,
335    /// The values, in the same order.
336    pub values: List<'a, Data<'a>>,
337}
338
339impl Encode for UnconfirmedWriteRequest<'_> {
340    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
341        self.specification.encode(w)?;
342        self.values.encode(w)
343    }
344}
345
346impl<'a> Decode<'a> for UnconfirmedWriteRequest<'a> {
347    fn decode(r: &mut Reader<'a>) -> Result<Self> {
348        Ok(Self { specification: List::decode(r)?, values: List::decode(r)? })
349    }
350}
351
352/// The short-name push: values a server sends unasked.
353///
354/// The sibling of `DataNotification`, from the era before logical names. `current_time`
355/// is an `OPTIONAL GeneralizedTime`, so A-XDR puts a usage flag in front of it; the time
356/// itself is carried as the octets the peer sent, because the encoding of a
357/// `GeneralizedTime` inside A-XDR is not stated in material this project can read and a
358/// timestamp decoded under a guessed grammar is a reading dated wrongly.
359#[derive(Debug, Clone, Copy, PartialEq)]
360pub struct InformationReportRequest<'a> {
361    /// When, as the peer sent it, or `None` when it did not say.
362    pub current_time: Option<&'a [u8]>,
363    /// What the values are, in order.
364    pub specification: List<'a, VariableAccess<'a>>,
365    /// The values, in the same order.
366    pub values: List<'a, Data<'a>>,
367}
368
369impl Encode for InformationReportRequest<'_> {
370    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
371        match self.current_time {
372            None => w.write_u8(0)?,
373            Some(t) => {
374                w.write_u8(1)?;
375                w.write_length_prefixed(t)?;
376            }
377        }
378        self.specification.encode(w)?;
379        self.values.encode(w)
380    }
381}
382
383impl<'a> Decode<'a> for InformationReportRequest<'a> {
384    fn decode(r: &mut Reader<'a>) -> Result<Self> {
385        let current_time = if r.u8()? == 0 { None } else { Some(r.length_prefixed()?) };
386        Ok(Self { current_time, specification: List::decode(r)?, values: List::decode(r)? })
387    }
388}
389
390#[cfg(test)]
391mod tests {
392    use super::*;
393    use crate::codec::SliceWriter;
394
395    fn round_trip<'a, T: Encode + Decode<'a> + PartialEq + core::fmt::Debug>(v: &T, buf: &'a mut [u8]) {
396        let n = {
397            let mut w = SliceWriter::new(buf);
398            v.encode(&mut w).unwrap();
399            w.written()
400        };
401        assert_eq!(v.encoded_len(), n, "encoded_len must agree with encode");
402        let decoded = T::from_bytes(buf.get(..n).unwrap()).unwrap();
403        assert_eq!(&decoded, v);
404    }
405
406    #[test]
407    fn every_variable_access_form_round_trips() {
408        let forms = [
409            VariableAccess::VariableName(0xFA00),
410            VariableAccess::Parameterized { name: 0x0028, selector: 1, parameter: Data::LongUnsigned(7) },
411            VariableAccess::BlockNumber(3),
412            VariableAccess::ReadDataBlock { last_block: false, block_number: 2, raw_data: &[1, 2, 3] },
413            VariableAccess::WriteDataBlock { last_block: true, block_number: 9 },
414        ];
415        for form in forms {
416            let mut buf = [0u8; 32];
417            round_trip(&form, &mut buf);
418        }
419    }
420
421    /// The one encoding worth pinning by hand: `variable-name` is choice 2 and a
422    /// big-endian sixteen-bit number, which is the whole point of short names.
423    #[test]
424    fn a_variable_name_is_three_bytes() {
425        let mut buf = [0u8; 8];
426        let mut w = SliceWriter::new(&mut buf);
427        VariableAccess::VariableName(0xFA00).encode(&mut w).unwrap();
428        assert_eq!(w.as_slice(), [0x02, 0xFA, 0x00]);
429    }
430
431    #[test]
432    fn every_read_result_form_round_trips() {
433        for form in [
434            ReadResult::Data(Data::DoubleLongUnsigned(1234)),
435            ReadResult::Error(DataAccessResult::ObjectUndefined),
436            ReadResult::Block { last_block: true, block_number: 1, raw_data: &[0xAA] },
437            ReadResult::BlockNumber(4),
438        ] {
439            let mut buf = [0u8; 32];
440            round_trip(&form, &mut buf);
441        }
442    }
443
444    #[test]
445    fn every_write_result_form_round_trips() {
446        for form in [
447            WriteResult::Success,
448            WriteResult::Error(DataAccessResult::ReadWriteDenied),
449            WriteResult::BlockNumber(2),
450        ] {
451            let mut buf = [0u8; 8];
452            round_trip(&form, &mut buf);
453        }
454    }
455
456    #[test]
457    fn a_report_without_a_time_still_says_so() {
458        let mut buf = [0u8; 64];
459        let mut w = SliceWriter::new(&mut buf);
460        InformationReportRequest {
461            current_time: None,
462            specification: List::from_raw(0, &[]),
463            values: List::from_raw(0, &[]),
464        }
465        .encode(&mut w)
466        .unwrap();
467        assert_eq!(w.as_slice(), [0x00, 0x00, 0x00], "usage flag, then two empty lists");
468    }
469}