bacnet-services 0.4.0

BACnet service request/response encode/decode per ASHRAE 135-2020
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//! GetEnrollmentSummary service per ASHRAE 135-2020 Clause 13.8.

use bacnet_encoding::primitives;
use bacnet_encoding::tags;
use bacnet_types::enums::{EventState, EventType};
use bacnet_types::error::Error;
use bacnet_types::primitives::ObjectIdentifier;
use bytes::BytesMut;

use crate::common::MAX_DECODED_ITEMS;

// ---------------------------------------------------------------------------
// GetEnrollmentSummaryRequest (Clause 13.8.1)
// ---------------------------------------------------------------------------

/// Priority filter sub-structure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PriorityFilter {
    pub min_priority: u8,
    pub max_priority: u8,
}

/// GetEnrollmentSummary-Request service parameters.
///
/// `enrollmentFilter` ([1] BACnetRecipientProcess) is omitted — it requires
/// the full Recipient/RecipientProcess types which are rarely used in
/// practice. A compliant implementation would extend this struct.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GetEnrollmentSummaryRequest {
    /// [0] acknowledgmentFilter: all(0), acked(1), not-acked(2).
    pub acknowledgment_filter: u32,
    /// [2] eventStateFilter (optional).
    pub event_state_filter: Option<EventState>,
    /// [3] eventTypeFilter (optional).
    pub event_type_filter: Option<EventType>,
    /// [4] priorityFilter { [0] minPriority, [1] maxPriority } (optional).
    pub priority_filter: Option<PriorityFilter>,
    /// [5] notificationClassFilter (optional).
    pub notification_class_filter: Option<u16>,
}

impl GetEnrollmentSummaryRequest {
    pub fn encode(&self, buf: &mut BytesMut) {
        // [0] acknowledgmentFilter
        primitives::encode_ctx_enumerated(buf, 0, self.acknowledgment_filter);
        // [1] enrollmentFilter — not implemented (skip)
        // [2] eventStateFilter (optional)
        if let Some(es) = self.event_state_filter {
            primitives::encode_ctx_enumerated(buf, 2, es.to_raw());
        }
        // [3] eventTypeFilter (optional)
        if let Some(et) = self.event_type_filter {
            primitives::encode_ctx_enumerated(buf, 3, et.to_raw());
        }
        // [4] priorityFilter (optional, constructed)
        if let Some(pf) = self.priority_filter {
            tags::encode_opening_tag(buf, 4);
            primitives::encode_ctx_unsigned(buf, 0, pf.min_priority as u64);
            primitives::encode_ctx_unsigned(buf, 1, pf.max_priority as u64);
            tags::encode_closing_tag(buf, 4);
        }
        // [5] notificationClassFilter (optional)
        if let Some(nc) = self.notification_class_filter {
            primitives::encode_ctx_unsigned(buf, 5, nc as u64);
        }
    }

    pub fn decode(data: &[u8]) -> Result<Self, Error> {
        let mut offset = 0;

        // [0] acknowledgmentFilter
        let (tag, pos) = tags::decode_tag(data, offset)?;
        let end = pos + tag.length as usize;
        if end > data.len() {
            return Err(Error::decoding(
                pos,
                "EnrollmentSummary truncated at acknowledgmentFilter",
            ));
        }
        let acknowledgment_filter = primitives::decode_unsigned(&data[pos..end])? as u32;
        offset = end;

        // [1] enrollmentFilter — skip if present
        if offset < data.len() {
            let (tag, _) = tags::decode_tag(data, offset)?;
            if tag.is_opening_tag(1) {
                // Skip over the entire constructed value
                let (_, new_offset) = tags::extract_context_value(data, offset + 1, 1)?;
                offset = new_offset;
            }
        }

        // [2] eventStateFilter (optional)
        let mut event_state_filter = None;
        let (opt_data, new_offset) = tags::decode_optional_context(data, offset, 2)?;
        if let Some(content) = opt_data {
            event_state_filter = Some(EventState::from_raw(
                primitives::decode_unsigned(content)? as u32
            ));
            offset = new_offset;
        }

        // [3] eventTypeFilter (optional)
        let mut event_type_filter = None;
        let (opt_data, new_offset) = tags::decode_optional_context(data, offset, 3)?;
        if let Some(content) = opt_data {
            event_type_filter = Some(EventType::from_raw(
                primitives::decode_unsigned(content)? as u32
            ));
            offset = new_offset;
        }

        // [4] priorityFilter (optional, constructed)
        let mut priority_filter = None;
        if offset < data.len() {
            let (tag, tag_end) = tags::decode_tag(data, offset)?;
            if tag.is_opening_tag(4) {
                // [0] minPriority
                let (inner_tag, inner_pos) = tags::decode_tag(data, tag_end)?;
                let inner_end = inner_pos + inner_tag.length as usize;
                if inner_end > data.len() {
                    return Err(Error::decoding(
                        inner_pos,
                        "EnrollmentSummary truncated at minPriority",
                    ));
                }
                let min_priority = primitives::decode_unsigned(&data[inner_pos..inner_end])? as u8;

                // [1] maxPriority
                let (inner_tag, inner_pos) = tags::decode_tag(data, inner_end)?;
                let inner_end = inner_pos + inner_tag.length as usize;
                if inner_end > data.len() {
                    return Err(Error::decoding(
                        inner_pos,
                        "EnrollmentSummary truncated at maxPriority",
                    ));
                }
                let max_priority = primitives::decode_unsigned(&data[inner_pos..inner_end])? as u8;

                // closing tag 4
                let (close_tag, close_end) = tags::decode_tag(data, inner_end)?;
                if !close_tag.is_closing_tag(4) {
                    return Err(Error::decoding(
                        inner_end,
                        "EnrollmentSummary expected closing tag 4",
                    ));
                }
                priority_filter = Some(PriorityFilter {
                    min_priority,
                    max_priority,
                });
                offset = close_end;
            }
        }

        // [5] notificationClassFilter (optional)
        let mut notification_class_filter = None;
        if offset < data.len() {
            let (opt_data, _new_offset) = tags::decode_optional_context(data, offset, 5)?;
            if let Some(content) = opt_data {
                notification_class_filter = Some(primitives::decode_unsigned(content)? as u16);
            }
        }

        Ok(Self {
            acknowledgment_filter,
            event_state_filter,
            event_type_filter,
            priority_filter,
            notification_class_filter,
        })
    }
}

// ---------------------------------------------------------------------------
// GetEnrollmentSummaryAck (Clause 13.8.2)
// ---------------------------------------------------------------------------

/// One entry in the GetEnrollmentSummary-ACK sequence.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnrollmentSummaryEntry {
    pub object_identifier: ObjectIdentifier,
    pub event_type: EventType,
    pub event_state: EventState,
    pub priority: u8,
    pub notification_class: u16,
}

/// GetEnrollmentSummary-ACK: a sequence of summary entries.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GetEnrollmentSummaryAck {
    pub entries: Vec<EnrollmentSummaryEntry>,
}

impl GetEnrollmentSummaryAck {
    pub fn encode(&self, buf: &mut BytesMut) {
        for entry in &self.entries {
            primitives::encode_app_object_id(buf, &entry.object_identifier);
            primitives::encode_app_enumerated(buf, entry.event_type.to_raw());
            primitives::encode_app_enumerated(buf, entry.event_state.to_raw());
            primitives::encode_app_unsigned(buf, entry.priority as u64);
            primitives::encode_app_unsigned(buf, entry.notification_class as u64);
        }
    }

    pub fn decode(data: &[u8]) -> Result<Self, Error> {
        let mut entries = Vec::new();
        let mut offset = 0;

        while offset < data.len() {
            if entries.len() >= MAX_DECODED_ITEMS {
                return Err(Error::decoding(
                    offset,
                    "EnrollmentSummaryAck too many entries",
                ));
            }

            // objectIdentifier (app)
            let (tag, pos) = tags::decode_tag(data, offset)?;
            let end = pos + tag.length as usize;
            if end > data.len() {
                return Err(Error::decoding(
                    pos,
                    "EnrollmentSummaryAck truncated at object-id",
                ));
            }
            let object_identifier = ObjectIdentifier::decode(&data[pos..end])?;
            offset = end;

            // eventType (app enumerated)
            let (tag, pos) = tags::decode_tag(data, offset)?;
            let end = pos + tag.length as usize;
            if end > data.len() {
                return Err(Error::decoding(
                    pos,
                    "EnrollmentSummaryAck truncated at eventType",
                ));
            }
            let event_type =
                EventType::from_raw(primitives::decode_unsigned(&data[pos..end])? as u32);
            offset = end;

            // eventState (app enumerated)
            let (tag, pos) = tags::decode_tag(data, offset)?;
            let end = pos + tag.length as usize;
            if end > data.len() {
                return Err(Error::decoding(
                    pos,
                    "EnrollmentSummaryAck truncated at eventState",
                ));
            }
            let event_state =
                EventState::from_raw(primitives::decode_unsigned(&data[pos..end])? as u32);
            offset = end;

            // priority (app unsigned)
            let (tag, pos) = tags::decode_tag(data, offset)?;
            let end = pos + tag.length as usize;
            if end > data.len() {
                return Err(Error::decoding(
                    pos,
                    "EnrollmentSummaryAck truncated at priority",
                ));
            }
            let priority = primitives::decode_unsigned(&data[pos..end])? as u8;
            offset = end;

            // notificationClass (app unsigned)
            let (tag, pos) = tags::decode_tag(data, offset)?;
            let end = pos + tag.length as usize;
            if end > data.len() {
                return Err(Error::decoding(
                    pos,
                    "EnrollmentSummaryAck truncated at notificationClass",
                ));
            }
            let notification_class = primitives::decode_unsigned(&data[pos..end])? as u16;
            offset = end;

            entries.push(EnrollmentSummaryEntry {
                object_identifier,
                event_type,
                event_state,
                priority,
                notification_class,
            });
        }

        Ok(Self { entries })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bacnet_types::enums::ObjectType;

    #[test]
    fn request_round_trip() {
        let req = GetEnrollmentSummaryRequest {
            acknowledgment_filter: 0, // all
            event_state_filter: Some(EventState::OFFNORMAL),
            event_type_filter: None,
            priority_filter: Some(PriorityFilter {
                min_priority: 1,
                max_priority: 10,
            }),
            notification_class_filter: Some(5),
        };
        let mut buf = BytesMut::new();
        req.encode(&mut buf);
        let decoded = GetEnrollmentSummaryRequest::decode(&buf).unwrap();
        assert_eq!(req, decoded);
    }

    #[test]
    fn request_minimal_round_trip() {
        let req = GetEnrollmentSummaryRequest {
            acknowledgment_filter: 2, // not-acked
            event_state_filter: None,
            event_type_filter: None,
            priority_filter: None,
            notification_class_filter: None,
        };
        let mut buf = BytesMut::new();
        req.encode(&mut buf);
        let decoded = GetEnrollmentSummaryRequest::decode(&buf).unwrap();
        assert_eq!(req, decoded);
    }

    #[test]
    fn ack_round_trip() {
        let ack = GetEnrollmentSummaryAck {
            entries: vec![
                EnrollmentSummaryEntry {
                    object_identifier: ObjectIdentifier::new(ObjectType::ANALOG_INPUT, 1).unwrap(),
                    event_type: EventType::OUT_OF_RANGE,
                    event_state: EventState::HIGH_LIMIT,
                    priority: 3,
                    notification_class: 10,
                },
                EnrollmentSummaryEntry {
                    object_identifier: ObjectIdentifier::new(ObjectType::BINARY_INPUT, 5).unwrap(),
                    event_type: EventType::CHANGE_OF_STATE,
                    event_state: EventState::NORMAL,
                    priority: 7,
                    notification_class: 20,
                },
            ],
        };
        let mut buf = BytesMut::new();
        ack.encode(&mut buf);
        let decoded = GetEnrollmentSummaryAck::decode(&buf).unwrap();
        assert_eq!(ack, decoded);
    }

    #[test]
    fn ack_empty_round_trip() {
        let ack = GetEnrollmentSummaryAck { entries: vec![] };
        let mut buf = BytesMut::new();
        ack.encode(&mut buf);
        let decoded = GetEnrollmentSummaryAck::decode(&buf).unwrap();
        assert_eq!(ack, decoded);
    }

    // -----------------------------------------------------------------------
    // Malformed-input decode error tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_decode_request_empty_input() {
        assert!(GetEnrollmentSummaryRequest::decode(&[]).is_err());
    }

    #[test]
    fn test_decode_request_truncated_1_byte() {
        let req = GetEnrollmentSummaryRequest {
            acknowledgment_filter: 0,
            event_state_filter: Some(EventState::FAULT),
            event_type_filter: None,
            priority_filter: None,
            notification_class_filter: None,
        };
        let mut buf = BytesMut::new();
        req.encode(&mut buf);
        assert!(GetEnrollmentSummaryRequest::decode(&buf[..1]).is_err());
    }

    #[test]
    fn test_decode_request_invalid_tag() {
        assert!(GetEnrollmentSummaryRequest::decode(&[0xFF, 0xFF, 0xFF]).is_err());
    }

    #[test]
    fn test_decode_ack_truncated_1_byte() {
        let ack = GetEnrollmentSummaryAck {
            entries: vec![EnrollmentSummaryEntry {
                object_identifier: ObjectIdentifier::new(ObjectType::ANALOG_INPUT, 1).unwrap(),
                event_type: EventType::OUT_OF_RANGE,
                event_state: EventState::HIGH_LIMIT,
                priority: 3,
                notification_class: 10,
            }],
        };
        let mut buf = BytesMut::new();
        ack.encode(&mut buf);
        assert!(GetEnrollmentSummaryAck::decode(&buf[..1]).is_err());
    }

    #[test]
    fn test_decode_ack_truncated_half() {
        let ack = GetEnrollmentSummaryAck {
            entries: vec![EnrollmentSummaryEntry {
                object_identifier: ObjectIdentifier::new(ObjectType::ANALOG_INPUT, 1).unwrap(),
                event_type: EventType::OUT_OF_RANGE,
                event_state: EventState::HIGH_LIMIT,
                priority: 3,
                notification_class: 10,
            }],
        };
        let mut buf = BytesMut::new();
        ack.encode(&mut buf);
        let half = buf.len() / 2;
        assert!(GetEnrollmentSummaryAck::decode(&buf[..half]).is_err());
    }

    #[test]
    fn test_decode_ack_invalid_tag() {
        assert!(GetEnrollmentSummaryAck::decode(&[0xFF, 0xFF, 0xFF]).is_err());
    }
}