Skip to main content

dlms_cosem_kit/xdlms/
initiate.rs

1//! The xDLMS association negotiation, carried inside the ACSE user information.
2
3use crate::codec::{Decode, Encode, ErrorKind, Reader, Result, Writer};
4
5use super::conformance::Conformance;
6use super::descriptor::{decode_optional, encode_optional};
7
8/// The DLMS version this crate speaks. Every deployed meter uses 6.
9pub const DLMS_VERSION: u8 = 6;
10
11/// The variable-access-specification name a logical-name association reports.
12pub const VAA_NAME_LN: u16 = 0x0007;
13
14/// Wrapper making an octet string encode length-prefixed.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16struct Octets<'a>(&'a [u8]);
17
18impl Encode for Octets<'_> {
19    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
20        w.write_length_prefixed(self.0)
21    }
22}
23
24impl<'a> Decode<'a> for Octets<'a> {
25    fn decode(r: &mut Reader<'a>) -> Result<Self> {
26        Ok(Self(r.length_prefixed()?))
27    }
28}
29
30/// What the client proposes when the association is established.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub struct InitiateRequest<'a> {
33    /// A key for this association only, carried encrypted inside the ciphered
34    /// InitiateRequest. Present only in a ciphered application context.
35    pub dedicated_key: Option<&'a [u8]>,
36    /// Whether the client wants responses. Absent means yes.
37    pub response_allowed: Option<bool>,
38    /// A quality-of-service value; nothing in the field uses it.
39    pub proposed_quality_of_service: Option<i8>,
40    /// The DLMS version, [`DLMS_VERSION`] in practice.
41    pub proposed_dlms_version: u8,
42    /// The services the client can perform.
43    pub proposed_conformance: Conformance,
44    /// The largest APDU the client will accept.
45    pub client_max_receive_pdu_size: u16,
46}
47
48impl Default for InitiateRequest<'_> {
49    fn default() -> Self {
50        Self {
51            dedicated_key: None,
52            response_allowed: None,
53            proposed_quality_of_service: None,
54            proposed_dlms_version: DLMS_VERSION,
55            proposed_conformance: Conformance::CLIENT_DEFAULT,
56            client_max_receive_pdu_size: 1024,
57        }
58    }
59}
60
61impl Encode for InitiateRequest<'_> {
62    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
63        encode_optional(w, self.dedicated_key.map(Octets).as_ref())?;
64        match self.response_allowed {
65            None => w.write_u8(0)?,
66            Some(v) => {
67                w.write_u8(1)?;
68                w.write_u8(u8::from(v))?;
69            }
70        }
71        match self.proposed_quality_of_service {
72            None => w.write_u8(0)?,
73            Some(v) => {
74                w.write_u8(1)?;
75                w.write_u8(v as u8)?;
76            }
77        }
78        w.write_u8(self.proposed_dlms_version)?;
79        self.proposed_conformance.encode_tagged(w)?;
80        w.write_u16(self.client_max_receive_pdu_size)
81    }
82}
83
84impl<'a> Decode<'a> for InitiateRequest<'a> {
85    fn decode(r: &mut Reader<'a>) -> Result<Self> {
86        let dedicated_key = decode_optional::<Octets<'a>>(r)?.map(|o| o.0);
87        let response_allowed = if r.u8()? == 0 { None } else { Some(r.u8()? != 0) };
88        let proposed_quality_of_service = if r.u8()? == 0 { None } else { Some(r.i8()?) };
89        Ok(Self {
90            dedicated_key,
91            response_allowed,
92            proposed_quality_of_service,
93            proposed_dlms_version: r.u8()?,
94            proposed_conformance: Conformance::decode_tagged(r)?,
95            client_max_receive_pdu_size: r.u16()?,
96        })
97    }
98}
99
100/// What the server agrees to.
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub struct InitiateResponse {
103    /// A quality-of-service value; nothing in the field uses it.
104    pub negotiated_quality_of_service: Option<i8>,
105    /// The DLMS version both sides will use.
106    pub negotiated_dlms_version: u8,
107    /// The services both sides can perform — the intersection.
108    pub negotiated_conformance: Conformance,
109    /// The largest APDU the server will accept. Every buffer this crate sizes for the
110    /// association comes from here.
111    pub server_max_receive_pdu_size: u16,
112    /// [`VAA_NAME_LN`] for a logical-name association.
113    pub vaa_name: u16,
114}
115
116impl Default for InitiateResponse {
117    fn default() -> Self {
118        Self {
119            negotiated_quality_of_service: None,
120            negotiated_dlms_version: DLMS_VERSION,
121            negotiated_conformance: Conformance::empty(),
122            server_max_receive_pdu_size: 1024,
123            vaa_name: VAA_NAME_LN,
124        }
125    }
126}
127
128impl Encode for InitiateResponse {
129    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
130        match self.negotiated_quality_of_service {
131            None => w.write_u8(0)?,
132            Some(v) => {
133                w.write_u8(1)?;
134                w.write_u8(v as u8)?;
135            }
136        }
137        w.write_u8(self.negotiated_dlms_version)?;
138        self.negotiated_conformance.encode_tagged(w)?;
139        w.write_u16(self.server_max_receive_pdu_size)?;
140        w.write_u16(self.vaa_name)
141    }
142}
143
144impl<'a> Decode<'a> for InitiateResponse {
145    fn decode(r: &mut Reader<'a>) -> Result<Self> {
146        let negotiated_quality_of_service = if r.u8()? == 0 { None } else { Some(r.i8()?) };
147        Ok(Self {
148            negotiated_quality_of_service,
149            negotiated_dlms_version: r.u8()?,
150            negotiated_conformance: Conformance::decode_tagged(r)?,
151            server_max_receive_pdu_size: r.u16()?,
152            vaa_name: r.u16()?,
153        })
154    }
155}
156
157impl InitiateResponse {
158    /// Fail unless the negotiated version is one this crate speaks.
159    pub fn check_version(&self) -> Result<()> {
160        if self.negotiated_dlms_version == DLMS_VERSION {
161            Ok(())
162        } else {
163            Err(crate::codec::Error::new(ErrorKind::Unsupported, 0))
164        }
165    }
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171    use crate::codec::SliceWriter;
172
173    #[test]
174    fn an_initiate_request_encodes_the_shape_the_standard_prints() {
175        let req = InitiateRequest {
176            proposed_conformance: Conformance::from_bytes([0x00, 0x7E, 0x1F]),
177            client_max_receive_pdu_size: 0xFFFF,
178            ..Default::default()
179        };
180        let mut buf = [0u8; 32];
181        let mut w = SliceWriter::new(&mut buf);
182        req.encode(&mut w).unwrap();
183        assert_eq!(
184            w.as_slice(),
185            [
186                0x00, // no dedicated key
187                0x00, // response-allowed absent (defaults to true)
188                0x00, // no proposed quality of service
189                0x06, // DLMS version 6
190                0x5F, 0x1F, 0x04, 0x00, 0x00, 0x7E, 0x1F, // conformance
191                0xFF, 0xFF, // max receive PDU size
192            ]
193        );
194        assert_eq!(InitiateRequest::from_bytes(w.as_slice()).unwrap(), req);
195    }
196
197    #[test]
198    fn a_dedicated_key_is_carried_length_prefixed() {
199        let key = [0u8; 16];
200        let req = InitiateRequest { dedicated_key: Some(&key), ..Default::default() };
201        let mut buf = [0u8; 64];
202        let mut w = SliceWriter::new(&mut buf);
203        req.encode(&mut w).unwrap();
204        assert_eq!(w.as_slice()[0], 0x01);
205        assert_eq!(w.as_slice()[1], 16);
206        assert_eq!(InitiateRequest::from_bytes(w.as_slice()).unwrap().dedicated_key, Some(&key[..]));
207    }
208
209    #[test]
210    fn an_initiate_response_round_trips() {
211        let resp = InitiateResponse {
212            negotiated_conformance: Conformance::from_bytes([0x00, 0x7E, 0x1F]),
213            server_max_receive_pdu_size: 512,
214            ..Default::default()
215        };
216        let mut buf = [0u8; 32];
217        let mut w = SliceWriter::new(&mut buf);
218        resp.encode(&mut w).unwrap();
219        assert_eq!(
220            w.as_slice(),
221            [0x00, 0x06, 0x5F, 0x1F, 0x04, 0x00, 0x00, 0x7E, 0x1F, 0x02, 0x00, 0x00, 0x07]
222        );
223        assert_eq!(InitiateResponse::from_bytes(w.as_slice()).unwrap(), resp);
224        assert!(resp.check_version().is_ok());
225    }
226}