Skip to main content

dlms_cosem_kit/xdlms/
descriptor.rs

1//! Attribute and method descriptors, and selective access.
2
3use crate::codec::{Decode, Encode, Reader, Result, Writer};
4use crate::obis::Obis;
5
6/// Which attribute of which object: class, logical name, attribute index.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub struct AttributeDescriptor {
9    /// The interface class.
10    pub class_id: u16,
11    /// The object's logical name.
12    pub instance_id: Obis,
13    /// The attribute index. Attribute 1 is always the logical name; index 0 addresses
14    /// every attribute at once, which a server only accepts if it said so in the
15    /// conformance block.
16    pub attribute_id: i8,
17}
18
19impl AttributeDescriptor {
20    /// A descriptor.
21    #[must_use]
22    pub const fn new(class_id: u16, instance_id: Obis, attribute_id: i8) -> Self {
23        Self { class_id, instance_id, attribute_id }
24    }
25}
26
27impl Encode for AttributeDescriptor {
28    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
29        w.write_u16(self.class_id)?;
30        w.write_bytes(self.instance_id.as_bytes())?;
31        w.write_u8(self.attribute_id as u8)
32    }
33
34    fn encoded_len(&self) -> usize {
35        9
36    }
37}
38
39impl<'a> Decode<'a> for AttributeDescriptor {
40    fn decode(r: &mut Reader<'a>) -> Result<Self> {
41        Ok(Self { class_id: r.u16()?, instance_id: Obis::decode(r)?, attribute_id: r.i8()? })
42    }
43}
44
45/// Which method of which object.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct MethodDescriptor {
48    /// The interface class.
49    pub class_id: u16,
50    /// The object's logical name.
51    pub instance_id: Obis,
52    /// The method index, counting from 1.
53    pub method_id: i8,
54}
55
56impl MethodDescriptor {
57    /// A descriptor.
58    #[must_use]
59    pub const fn new(class_id: u16, instance_id: Obis, method_id: i8) -> Self {
60        Self { class_id, instance_id, method_id }
61    }
62}
63
64impl Encode for MethodDescriptor {
65    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
66        w.write_u16(self.class_id)?;
67        w.write_bytes(self.instance_id.as_bytes())?;
68        w.write_u8(self.method_id as u8)
69    }
70
71    fn encoded_len(&self) -> usize {
72        9
73    }
74}
75
76impl<'a> Decode<'a> for MethodDescriptor {
77    fn decode(r: &mut Reader<'a>) -> Result<Self> {
78        Ok(Self { class_id: r.u16()?, instance_id: Obis::decode(r)?, method_id: r.i8()? })
79    }
80}
81
82pub use crate::cosem::SelectiveAccess;
83
84/// Write an A-XDR `OPTIONAL` field: a usage flag, then the value when present.
85pub(crate) fn encode_optional<T: Encode>(w: &mut dyn Writer, v: Option<&T>) -> Result<()> {
86    match v {
87        None => w.write_u8(0),
88        Some(v) => {
89            w.write_u8(1)?;
90            v.encode(w)
91        }
92    }
93}
94
95/// Read an A-XDR `OPTIONAL` field.
96pub(crate) fn decode_optional<'a, T: Decode<'a>>(r: &mut Reader<'a>) -> Result<Option<T>> {
97    if r.u8()? == 0 { Ok(None) } else { Ok(Some(T::decode(r)?)) }
98}
99
100/// An attribute descriptor together with an optional selective access descriptor, as
101/// the `with-list` services carry them.
102#[derive(Debug, Clone, Copy, PartialEq)]
103pub struct AttributeDescriptorWithSelection<'a> {
104    /// Which attribute.
105    pub descriptor: AttributeDescriptor,
106    /// Which part of it.
107    pub access: Option<SelectiveAccess<'a>>,
108}
109
110impl Encode for AttributeDescriptorWithSelection<'_> {
111    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
112        self.descriptor.encode(w)?;
113        encode_optional(w, self.access.as_ref())
114    }
115}
116
117impl<'a> Decode<'a> for AttributeDescriptorWithSelection<'a> {
118    fn decode(r: &mut Reader<'a>) -> Result<Self> {
119        Ok(Self { descriptor: AttributeDescriptor::decode(r)?, access: decode_optional(r)? })
120    }
121}
122
123/// The invoke id and priority byte carried by every confirmed service.
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub struct InvokeId(pub u8);
126
127impl InvokeId {
128    /// A confirmed request at normal priority with invoke id `id` (0–15).
129    #[must_use]
130    pub const fn confirmed(id: u8) -> Self {
131        Self((id & 0x0F) | 0x40)
132    }
133
134    /// The invoke id, 0–15.
135    #[must_use]
136    pub const fn id(self) -> u8 {
137        self.0 & 0x0F
138    }
139
140    /// True when a response is expected.
141    #[must_use]
142    pub const fn is_confirmed(self) -> bool {
143        self.0 & 0x40 != 0
144    }
145
146    /// True when the request asked for high priority.
147    #[must_use]
148    pub const fn is_high_priority(self) -> bool {
149        self.0 & 0x80 != 0
150    }
151
152    /// The same invoke id at high priority.
153    #[must_use]
154    pub const fn with_high_priority(self) -> Self {
155        Self(self.0 | 0x80)
156    }
157}
158
159/// The four-byte invoke id and priority used by the ACCESS and notification services.
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub struct LongInvokeId(pub u32);
162
163impl LongInvokeId {
164    /// A long invoke id, 24 bits.
165    #[must_use]
166    pub const fn new(id: u32) -> Self {
167        Self(id & 0x00FF_FFFF)
168    }
169
170    /// The invoke id.
171    #[must_use]
172    pub const fn id(self) -> u32 {
173        self.0 & 0x00FF_FFFF
174    }
175
176    /// True when a response is expected.
177    #[must_use]
178    pub const fn is_confirmed(self) -> bool {
179        self.0 & 0x2000_0000 != 0
180    }
181
182    /// True when the sender marked the message self-descriptive.
183    #[must_use]
184    pub const fn is_self_descriptive(self) -> bool {
185        self.0 & 0x8000_0000 != 0
186    }
187
188    /// The same id, marked confirmed.
189    #[must_use]
190    pub const fn confirmed(self) -> Self {
191        Self(self.0 | 0x2000_0000)
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198    use crate::codec::SliceWriter;
199
200    #[test]
201    fn an_attribute_descriptor_is_nine_bytes_in_order() {
202        let d = AttributeDescriptor::new(3, Obis::new(1, 0, 1, 8, 0, 255), 2);
203        let mut buf = [0u8; 16];
204        let mut w = SliceWriter::new(&mut buf);
205        d.encode(&mut w).unwrap();
206        assert_eq!(w.as_slice(), [0x00, 0x03, 1, 0, 1, 8, 0, 255, 2]);
207        assert_eq!(d.encoded_len(), 9);
208        assert_eq!(AttributeDescriptor::from_bytes(w.as_slice()).unwrap(), d);
209    }
210
211    #[test]
212    fn a_negative_attribute_index_survives_the_round_trip() {
213        // Attribute ids are signed in the ASN.1; a server that reads them as unsigned
214        // turns attribute -1 into 255 and addresses a different thing.
215        let d = AttributeDescriptor::new(7, Obis::new(1, 0, 99, 1, 0, 255), -1);
216        let mut buf = [0u8; 16];
217        let mut w = SliceWriter::new(&mut buf);
218        d.encode(&mut w).unwrap();
219        assert_eq!(w.as_slice()[8], 0xFF);
220        assert_eq!(AttributeDescriptor::from_bytes(w.as_slice()).unwrap().attribute_id, -1);
221    }
222
223    #[test]
224    fn invoke_id_bits() {
225        let i = InvokeId::confirmed(3);
226        assert_eq!(i.id(), 3);
227        assert!(i.is_confirmed());
228        assert!(!i.is_high_priority());
229        assert!(i.with_high_priority().is_high_priority());
230        assert_eq!(i.0, 0x43);
231    }
232
233    #[test]
234    fn long_invoke_id_bits() {
235        let i = LongInvokeId::new(0x01_0203).confirmed();
236        assert_eq!(i.id(), 0x01_0203);
237        assert!(i.is_confirmed());
238        assert!(!i.is_self_descriptive());
239    }
240}