bacnet-objects 0.11.0

BACnet object model: traits, database, and standard object types
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
//! NotificationClass object per ASHRAE 135-2020 Clause 12.31.
//!
//! # Recipient-list day/time convention
//!
//! `RECIPIENT_LIST` entries are `BACnetDestination` (Clause 12.15.5). The
//! `valid_days` field is a `BACnetDaysOfWeek` bit string defined as
//! `BIT STRING { monday(0), tuesday(1), ..., sunday(6) }` (Clause 21): **bit 0
//! is Monday and bit 6 is Sunday** in the in-memory `u8`. Callers must build
//! `today_bit` with the same convention (`1 << dow` where `dow = 0` on
//! Monday). On the wire both bit strings are packed MSB-first per Clause
//! 20.2.10 — monday(0) at `0x80` of the `valid_days` octet (`unused_bits: 1`),
//! to-offnormal(0) at `0x80` of the `transitions` octet (`unused_bits: 5`) —
//! via [`bacnet_types::bitstring::pack_octet`]/[`unpack_octet`], which reverse
//! the in-memory bit0-first byte.
//!
//! [`unpack_octet`]: bacnet_types::bitstring::unpack_octet
//!
//! `from_time`/`to_time` are BACnet `Time` values interpreted in the device's
//! *local* time, derived from the wall clock plus the Device object's
//! `UTC_Offset` property (signed minutes) at the sender. A window with
//! `to_time < from_time` (e.g. 22:00–02:00) crosses midnight and is active
//! outside the `[from, to]` interval; see [`time_in_window`].

use bacnet_types::constructed::{BACnetAddress, BACnetDestination, BACnetRecipient};
use bacnet_types::enums::{ObjectType, PropertyIdentifier};
use bacnet_types::error::Error;
use bacnet_types::primitives::{ObjectIdentifier, PropertyValue, StatusFlags, Time};
use bacnet_types::MacAddr;
use std::borrow::Cow;

use crate::common::{self, read_common_properties};
use crate::database::ObjectDatabase;
use crate::event::EventTransition;
use crate::traits::BACnetObject;

mod enrollment_summary;
#[doc(hidden)]
pub use enrollment_summary::{
    resolve_enrollment_summary_class_internal, EnrollmentSummaryClassProjection,
    EnrollmentSummaryClassProjectionError,
};

/// BACnet NotificationClass object.
///
/// Stores notification routing configuration: which priorities, acknowledgement
/// requirements, and recipient destinations apply to event notifications
/// referencing this class number.
pub struct NotificationClass {
    oid: ObjectIdentifier,
    name: String,
    description: String,
    status_flags: StatusFlags,
    out_of_service: bool,
    reliability: u32,
    /// The notification class number.
    pub notification_class: u32,
    /// Priority: [TO_OFFNORMAL, TO_FAULT, TO_NORMAL]. Default [255, 255, 255].
    pub priority: [u8; 3],
    /// Ack required: [TO_OFFNORMAL, TO_FAULT, TO_NORMAL]. Default [false, false, false].
    pub ack_required: [bool; 3],
    /// Recipient list.
    pub recipient_list: Vec<BACnetDestination>,
}

impl NotificationClass {
    /// Create a new NotificationClass object.
    ///
    /// The `notification_class` number defaults to the instance number.
    pub fn new(instance: u32, name: impl Into<String>) -> Result<Self, Error> {
        let oid = ObjectIdentifier::new(ObjectType::NOTIFICATION_CLASS, instance)?;
        Ok(Self {
            oid,
            name: name.into(),
            description: String::new(),
            status_flags: StatusFlags::empty(),
            out_of_service: false,
            reliability: 0,
            notification_class: instance,
            priority: [255, 255, 255],
            ack_required: [false, false, false],
            recipient_list: Vec::new(),
        })
    }

    /// Set the description string.
    pub fn set_description(&mut self, desc: impl Into<String>) {
        self.description = desc.into();
    }

    /// Add a destination to the recipient list.
    pub fn add_destination(&mut self, dest: BACnetDestination) {
        self.recipient_list.push(dest);
    }
}

impl BACnetObject for NotificationClass {
    fn object_identifier(&self) -> ObjectIdentifier {
        self.oid
    }

    fn object_name(&self) -> &str {
        &self.name
    }

    fn read_property(
        &self,
        property: PropertyIdentifier,
        array_index: Option<u32>,
    ) -> Result<PropertyValue, Error> {
        if let Some(result) = read_common_properties!(self, property, array_index) {
            return result;
        }
        match property {
            p if p == PropertyIdentifier::OBJECT_TYPE => Ok(PropertyValue::Enumerated(
                ObjectType::NOTIFICATION_CLASS.to_raw(),
            )),
            p if p == PropertyIdentifier::EVENT_STATE => {
                Ok(PropertyValue::Enumerated(0)) // normal
            }
            p if p == PropertyIdentifier::NOTIFICATION_CLASS => {
                Ok(PropertyValue::Unsigned(self.notification_class as u64))
            }
            p if p == PropertyIdentifier::PRIORITY => match array_index {
                Some(0) => Ok(PropertyValue::Unsigned(3)),
                Some(idx) if (1..=3).contains(&idx) => Ok(PropertyValue::Unsigned(
                    self.priority[(idx - 1) as usize] as u64,
                )),
                None => Ok(PropertyValue::List(vec![
                    PropertyValue::Unsigned(self.priority[0] as u64),
                    PropertyValue::Unsigned(self.priority[1] as u64),
                    PropertyValue::Unsigned(self.priority[2] as u64),
                ])),
                _ => Err(common::invalid_array_index_error()),
            },
            p if p == PropertyIdentifier::ACK_REQUIRED => {
                // 3-bit bitstring: bit 0=TO_OFFNORMAL, bit 1=TO_FAULT, bit 2=TO_NORMAL
                let mut byte: u8 = 0;
                if self.ack_required[0] {
                    byte |= 0x80;
                } // bit 0 in MSB
                if self.ack_required[1] {
                    byte |= 0x40;
                } // bit 1
                if self.ack_required[2] {
                    byte |= 0x20;
                } // bit 2
                Ok(PropertyValue::BitString {
                    unused_bits: 5,
                    data: vec![byte],
                })
            }
            p if p == PropertyIdentifier::RECIPIENT_LIST => {
                // Full ASN.1 framing: BACnetLIST of BACnetDestination — each
                // entry a 7-element application-tagged SEQUENCE with the
                // recipient discriminated by context tag (device [0]
                // primitive / address [1] constructed), Clause 12.21 + 21.
                let mut buf = bytes::BytesMut::new();
                bacnet_encoding::constructed::encode_destination_list(
                    &mut buf,
                    &self.recipient_list,
                );
                Ok(PropertyValue::ApplicationData(buf.to_vec()))
            }
            _ => Err(common::unknown_property_error()),
        }
    }

    fn write_property(
        &mut self,
        property: PropertyIdentifier,
        array_index: Option<u32>,
        value: PropertyValue,
        _priority: Option<u8>,
    ) -> Result<(), Error> {
        if property == PropertyIdentifier::NOTIFICATION_CLASS {
            if let PropertyValue::Unsigned(v) = value {
                self.notification_class = common::u64_to_u32(v)?;
                return Ok(());
            }
            return Err(common::invalid_data_type_error());
        }
        if property == PropertyIdentifier::RECIPIENT_LIST {
            // Indexed (array-element) access: Recipient_List is a BACnetLIST
            // (Table 12-24), not an array, so Clause 12.1.5.2 makes ReadRange
            // the only positional access. The RP/RPM/WP/WPM handlers gate
            // indexed access to PROPERTY / PROPERTY_IS_NOT_AN_ARRAY
            // (Clause 15.5.1.3 / 15.9.1.3) via `is_array_property`; mirror
            // the same classification here for direct object-layer calls.
            if array_index.is_some() {
                return Err(common::property_is_not_an_array_error());
            }
            self.recipient_list = match &value {
                // Framed wire form (Clause 12.21 BACnetLIST of
                // BACnetDestination): strict — one malformed entry rejects
                // the whole write.
                PropertyValue::ApplicationData(bytes) => {
                    match bacnet_encoding::constructed::decode_destination_list(bytes) {
                        Ok(list) => list,
                        Err(_) => return Err(common::invalid_data_type_error()),
                    }
                }
                // Legacy flat application-tagged form (pre-#152 layout):
                // still accepted so older internal clients keep working.
                PropertyValue::List(entries) => {
                    let mut new_list = Vec::with_capacity(entries.len());
                    for entry in entries {
                        let PropertyValue::List(fields) = entry else {
                            return Err(common::invalid_data_type_error());
                        };
                        match destination_from_flat_fields(fields) {
                            Some(dest) => new_list.push(dest),
                            None => return Err(common::invalid_data_type_error()),
                        }
                    }
                    new_list
                }
                _ => return Err(common::invalid_data_type_error()),
            };
            return Ok(());
        }
        if let Some(result) =
            common::write_out_of_service(&mut self.out_of_service, property, &value)
        {
            return result;
        }
        if let Some(result) = common::write_description(&mut self.description, property, &value) {
            return result;
        }
        Err(common::write_access_denied_error())
    }

    fn property_list(&self) -> Cow<'static, [PropertyIdentifier]> {
        static PROPS: &[PropertyIdentifier] = &[
            PropertyIdentifier::OBJECT_IDENTIFIER,
            PropertyIdentifier::OBJECT_NAME,
            PropertyIdentifier::DESCRIPTION,
            PropertyIdentifier::OBJECT_TYPE,
            PropertyIdentifier::STATUS_FLAGS,
            PropertyIdentifier::EVENT_STATE,
            PropertyIdentifier::OUT_OF_SERVICE,
            PropertyIdentifier::RELIABILITY,
            PropertyIdentifier::NOTIFICATION_CLASS,
            PropertyIdentifier::PRIORITY,
            PropertyIdentifier::ACK_REQUIRED,
            PropertyIdentifier::RECIPIENT_LIST,
        ];
        Cow::Borrowed(PROPS)
    }
}

/// Convert a `Time` to centiseconds (hundredths of a second since midnight).
fn time_to_centiseconds(t: &Time) -> u32 {
    let h = if t.hour == Time::UNSPECIFIED {
        0
    } else {
        t.hour as u32
    };
    let m = if t.minute == Time::UNSPECIFIED {
        0
    } else {
        t.minute as u32
    };
    let s = if t.second == Time::UNSPECIFIED {
        0
    } else {
        t.second as u32
    };
    let cs = if t.hundredths == Time::UNSPECIFIED {
        0
    } else {
        t.hundredths as u32
    };
    h * 360_000 + m * 6_000 + s * 100 + cs
}

/// Check if `current` falls within the `[from, to]` time window.
///
/// If either bound has an unspecified hour (0xFF), the window is treated as
/// "all day". A window whose `to` is earlier than its `from` (e.g.
/// 22:00–02:00) crosses midnight: it is active from `from` up to midnight and
/// again from midnight up to `to`, i.e. when `current >= from || current <= to`.
/// This matches the ASHRAE 135-2020 reading that `To_Time` is the end of the
/// active period; a wrap-around pair denotes an overnight schedule.
fn time_in_window(current: &Time, from: &Time, to: &Time) -> bool {
    if from.hour == Time::UNSPECIFIED || to.hour == Time::UNSPECIFIED {
        return true;
    }
    let cur = time_to_centiseconds(current);
    let from_cs = time_to_centiseconds(from);
    let to_cs = time_to_centiseconds(to);
    if to_cs < from_cs {
        // Overnight window crossing midnight.
        cur >= from_cs || cur <= to_cs
    } else {
        cur >= from_cs && cur <= to_cs
    }
}

/// Derive the local day-of-week bit and time-of-day for recipient filtering.
///
/// `utc_secs` is seconds since the Unix epoch (1970-01-01, a Thursday).
/// `utc_offset_minutes` is the Device object's `UTC_Offset` (signed minutes
/// west of UTC); 0 keeps UTC. The day-of-week follows
/// `BACnetDaysOfWeek` (monday(0)..sunday(6), Clause 21): the `+3` makes
/// Monday=0 because the epoch was a Thursday, and `today_bit = 1 << dow`
/// uses the same convention as `valid_days`. The returned `Time` is the
/// local time of day (hundredths are supplied by the caller via `subsec`).
pub fn local_day_and_time(utc_secs: u64, utc_offset_minutes: i32) -> (u8, Time) {
    // BACnet UTC_Offset is signed minutes west of UTC, so local standard time
    // subtracts it. Saturation only affects values close to the Unix epoch.
    let local_secs = utc_secs.saturating_add_signed(-i64::from(utc_offset_minutes) * 60);
    let dow = ((local_secs / 86400 + 3) % 7) as u8;
    let today_bit = 1u8 << dow;
    let day_secs = (local_secs % 86400) as u32;
    let current_time = Time {
        hour: (day_secs / 3600) as u8,
        minute: ((day_secs % 3600) / 60) as u8,
        second: (day_secs % 60) as u8,
        hundredths: 0,
    };
    (today_bit, current_time)
}

/// Resolve the NotificationClass object whose `Notification_Class` property
/// equals `notification_class`.
///
/// Tries a direct OID lookup first (instance == notification_class is the
/// common case), then falls back to scanning every NotificationClass object.
/// Returns `None` when no matching class is configured.
fn find_notification_class(
    db: &ObjectDatabase,
    notification_class: u32,
) -> Option<&dyn BACnetObject> {
    // Try direct OID lookup first (instance == notification_class is the common case)
    if let Ok(nc_oid) = ObjectIdentifier::new(ObjectType::NOTIFICATION_CLASS, notification_class) {
        if let Some(obj) = db.get(&nc_oid) {
            if matches!(
                obj.read_property(PropertyIdentifier::NOTIFICATION_CLASS, None),
                Ok(PropertyValue::Unsigned(n)) if n as u32 == notification_class
            ) {
                return Some(obj);
            }
        }
    }

    // Fall back to scanning all NotificationClass objects
    db.find_by_type(ObjectType::NOTIFICATION_CLASS)
        .iter()
        .find_map(|oid| {
            let obj = db.get(oid)?;
            match obj.read_property(PropertyIdentifier::NOTIFICATION_CLASS, None) {
                Ok(PropertyValue::Unsigned(n)) if n as u32 == notification_class => Some(obj),
                _ => None,
            }
        })
}

/// Resolve the per-transition `Priority` and `Ack_Required` for an event
/// notification from the referenced NotificationClass.
///
/// Per ASHRAE 135-2020 Clause 13.2.1, the `Priority` and `Ack_Required`
/// projected into an `EventNotification` come from the NotificationClass
/// referenced by the event-generating object's `Notification_Class` property,
/// selected by the transition coordinate (TO_OFFNORMAL, TO_FAULT, or
/// TO_NORMAL). Both properties are 3-element arrays ordered
/// `[TO_OFFNORMAL, TO_FAULT, TO_NORMAL]`.
///
/// When no NotificationClass matches the given number (the object's
/// `Notification_Class` was never configured or points at a missing class),
/// the spec leaves the projection undefined; we fall back to the BACnet
/// defaults — `Priority = 255` (lowest) and `Ack_Required = false`.
///
/// Those defaults no longer reach the wire on the server's send path. A class
/// that does not exist also names no recipients, and the sender distributes
/// nothing when the recipient set is empty, so the fallback survives only for
/// direct callers of this function.
pub fn resolve_transition_priority_ack(
    db: &ObjectDatabase,
    notification_class: u32,
    transition: EventTransition,
) -> (u8, bool) {
    let Some(nc) = find_notification_class(db, notification_class) else {
        return (255, false);
    };
    let idx = transition.index();

    // PRIORITY is a 3-element array; index 0 is the array length, 1..=3 the
    // per-transition values. Read the slot directly, defaulting to 255 when
    // the property is absent or malformed (matches the NotificationClass
    // default and the missing-class fallback).
    let priority = nc
        .read_property(PropertyIdentifier::PRIORITY, Some(idx as u32 + 1))
        .ok()
        .and_then(|v| match v {
            PropertyValue::Unsigned(n) => Some(n as u8),
            _ => None,
        })
        .unwrap_or(255);

    // ACK_REQUIRED is a 3-bit bitstring: bit 0 (0x80) = TO_OFFNORMAL,
    // bit 1 (0x40) = TO_FAULT, bit 2 (0x20) = TO_NORMAL.
    let ack_required = nc
        .read_property(PropertyIdentifier::ACK_REQUIRED, None)
        .ok()
        .and_then(|v| match v {
            PropertyValue::BitString { data, .. } => data.first().copied(),
            _ => None,
        })
        .map(|byte| byte & (0x80 >> idx) != 0)
        .unwrap_or(false);

    (priority, ack_required)
}

/// The complete outcome of looking up and selecting Notification Class recipients.
///
/// Broadcast is not an outcome. It is represented only by an address inside
/// [`Matched`](Self::Matched), after that configured destination passes the
/// day, time, and transition filters. Device recipients are also successful
/// matches here; resolving them to network addresses is a later routing step.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RecipientLookupOutcome {
    /// No Notification Class has the requested class number.
    NotificationClassMissing,
    /// The class exists, but its recipient-list property could not be read.
    RecipientListUnavailable,
    /// The complete recipient-list value could not be decoded.
    RecipientListInvalid,
    /// The class contains a valid list with zero configured destinations.
    NoConfiguredDestinations,
    /// Destinations are configured, but none is eligible for this selection.
    NoMatchingDestinations,
    /// Eligible configured destinations and their delivery settings.
    Matched(Vec<(BACnetRecipient, u32, bool)>),
}

/// Look up and select recipients for a Notification Class transition.
///
/// This is the canonical recipient lookup API and distinguishes configuration
/// failures from valid empty or ineligible configuration. Selection uses the
/// configured destination's day mask, local time window, and transition mask.
/// `today_bit` uses bit 0 for Monday through bit 6 for Sunday.
///
/// A malformed complete list returns
/// [`RecipientListInvalid`](RecipientLookupOutcome::RecipientListInvalid);
/// no decodable prefix is selected. Every non-matched outcome is fail-closed
/// and names no implicit destination.
pub fn lookup_notification_recipients(
    db: &ObjectDatabase,
    notification_class: u32,
    transition: EventTransition,
    today_bit: u8,
    current_time: &Time,
) -> RecipientLookupOutcome {
    let Some(nc) = find_notification_class(db, notification_class) else {
        return RecipientLookupOutcome::NotificationClassMissing;
    };
    let Ok(recipient_list_value) = nc.read_property(PropertyIdentifier::RECIPIENT_LIST, None)
    else {
        return RecipientLookupOutcome::RecipientListUnavailable;
    };
    let Ok(destinations) = decode_destination_list_pv(&recipient_list_value) else {
        return RecipientLookupOutcome::RecipientListInvalid;
    };
    if destinations.is_empty() {
        return RecipientLookupOutcome::NoConfiguredDestinations;
    }

    let recipients = filter_destinations(destinations, transition, today_bit, current_time);
    if recipients.is_empty() {
        RecipientLookupOutcome::NoMatchingDestinations
    } else {
        RecipientLookupOutcome::Matched(recipients)
    }
}

/// Get notification recipients for a given class number and transition.
///
/// This source-compatible wrapper delegates to
/// [`lookup_notification_recipients`] and returns the matched recipient tuples.
/// Every other outcome maps to an empty vector, preserving the legacy API.
pub fn get_notification_recipients(
    db: &ObjectDatabase,
    notification_class: u32,
    transition: EventTransition,
    today_bit: u8,
    current_time: &Time,
) -> Vec<(BACnetRecipient, u32, bool)> {
    match lookup_notification_recipients(
        db,
        notification_class,
        transition,
        today_bit,
        current_time,
    ) {
        RecipientLookupOutcome::Matched(recipients) => recipients,
        RecipientLookupOutcome::NotificationClassMissing
        | RecipientLookupOutcome::RecipientListUnavailable
        | RecipientLookupOutcome::RecipientListInvalid
        | RecipientLookupOutcome::NoConfiguredDestinations
        | RecipientLookupOutcome::NoMatchingDestinations => Vec::new(),
    }
}

/// Strict variant of [`get_notification_recipients`] for fail-closed routing.
///
/// This source-compatible wrapper delegates to
/// [`lookup_notification_recipients`]. It preserves `None` for an invalid or
/// undecodable complete list and `Some([])` for missing class, property-read
/// failure, configured empty, and no-match outcomes. Successful matches return
/// `Some(recipients)`.
pub fn get_notification_recipients_strict(
    db: &ObjectDatabase,
    notification_class: u32,
    transition: EventTransition,
    today_bit: u8,
    current_time: &Time,
) -> Option<Vec<(BACnetRecipient, u32, bool)>> {
    match lookup_notification_recipients(
        db,
        notification_class,
        transition,
        today_bit,
        current_time,
    ) {
        RecipientLookupOutcome::RecipientListInvalid => None,
        RecipientLookupOutcome::Matched(recipients) => Some(recipients),
        RecipientLookupOutcome::NotificationClassMissing
        | RecipientLookupOutcome::RecipientListUnavailable
        | RecipientLookupOutcome::NoConfiguredDestinations
        | RecipientLookupOutcome::NoMatchingDestinations => Some(Vec::new()),
    }
}

/// Decode ONE legacy flat `Recipient_List` entry (the pre-#152
/// application-tagged layout: seven `PropertyValue` fields in declaration
/// order, the address recipient as
/// `List[Unsigned network_number, OctetString mac]`).
///
/// Shared by the write path (where `None` aborts the whole write) and the
/// recipient filter (where a malformed entry is skipped): the two must not
/// grow apart again.
fn destination_from_flat_fields(fields: &[PropertyValue]) -> Option<BACnetDestination> {
    if fields.len() < 7 {
        return None;
    }
    // [0] valid_days: BitString (7 bits, 1 unused)
    let valid_days = match &fields[0] {
        PropertyValue::BitString { data, .. } if !data.is_empty() => {
            bacnet_types::bitstring::unpack_octet(data, 7)
        }
        _ => return None,
    };
    // [1] from_time
    let from_time = match fields[1] {
        PropertyValue::Time(t) => t,
        _ => return None,
    };
    // [2] to_time
    let to_time = match fields[2] {
        PropertyValue::Time(t) => t,
        _ => return None,
    };
    // [3] recipient: Device (ObjectIdentifier) or Address
    // (List[Unsigned network_number, OctetString mac]).
    let recipient = match &fields[3] {
        PropertyValue::ObjectIdentifier(oid) => BACnetRecipient::Device(*oid),
        PropertyValue::List(items) if items.len() == 2 => {
            let network_number = match &items[0] {
                PropertyValue::Unsigned(v) => *v as u16,
                _ => return None,
            };
            let mac_address = match &items[1] {
                PropertyValue::OctetString(mac) => MacAddr::from_slice(mac),
                _ => return None,
            };
            BACnetRecipient::Address(BACnetAddress {
                network_number,
                mac_address,
            })
        }
        _ => return None,
    };
    // [4] process_identifier
    let process_identifier = match fields[4] {
        PropertyValue::Unsigned(v) => u32::try_from(v).ok()?,
        _ => return None,
    };
    // [5] issue_confirmed_notifications
    let issue_confirmed_notifications = match fields[5] {
        PropertyValue::Boolean(b) => b,
        _ => return None,
    };
    // [6] transitions: BitString (3 bits, 5 unused)
    let transitions = match &fields[6] {
        PropertyValue::BitString { data, .. } if !data.is_empty() => {
            bacnet_types::bitstring::unpack_octet(data, 3)
        }
        _ => return None,
    };
    Some(BACnetDestination {
        valid_days,
        from_time,
        to_time,
        recipient,
        process_identifier,
        issue_confirmed_notifications,
        transitions,
    })
}

/// Strictly decode a `RECIPIENT_LIST` property value into its destinations.
///
/// Framed wire form ([`PropertyValue::ApplicationData`]): the strict
/// `BACnetLIST of BACnetDestination` codec. Legacy flat form
/// ([`PropertyValue::List`]): [`destination_from_flat_fields`]. Either way,
/// the FIRST malformed destination (or trailing bytes) fails the whole
/// decode — a prefix-tolerant walk would silently route notifications to
/// only a subset of the configured recipients (review blocker).
pub(super) fn decode_destination_list_pv(
    value: &PropertyValue,
) -> Result<Vec<BACnetDestination>, Error> {
    match value {
        PropertyValue::ApplicationData(bytes) => {
            bacnet_encoding::constructed::decode_destination_list(bytes)
        }
        PropertyValue::List(entries) => entries
            .iter()
            .map(|entry| match entry {
                PropertyValue::List(fields) => destination_from_flat_fields(fields)
                    .ok_or_else(|| Error::decoding(0, "Recipient_List: malformed legacy entry")),
                _ => Err(Error::decoding(
                    0,
                    "Recipient_List: entry is not a field list",
                )),
            })
            .collect(),
        _ => Err(Error::decoding(
            0,
            "Recipient_List: expected framed application data or a legacy list",
        )),
    }
}

/// Filter decoded destinations by day, time, and transition — the shared
/// selection step of [`filter_recipient_list`] and
/// [`lookup_notification_recipients`].
fn filter_destinations(
    destinations: Vec<BACnetDestination>,
    transition: EventTransition,
    today_bit: u8,
    current_time: &Time,
) -> Vec<(BACnetRecipient, u32, bool)> {
    let transition_mask = transition.bit_mask();
    destinations
        .into_iter()
        .filter(|dest| dest.valid_days & today_bit != 0)
        .filter(|dest| time_in_window(current_time, &dest.from_time, &dest.to_time))
        .filter(|dest| dest.transitions & transition_mask != 0)
        .map(|dest| {
            (
                dest.recipient,
                dest.process_identifier,
                dest.issue_confirmed_notifications,
            )
        })
        .collect()
}

/// Filter an encoded `RECIPIENT_LIST` property value by day, time, and transition.
///
/// Parses the value as returned by `read_property(RECIPIENT_LIST)` — the
/// framed `BACnetLIST of BACnetDestination` form, or the legacy flat form —
/// and returns only those recipients matching the given filters. A list
/// that fails to decode (even partially) yields NO recipients: routing
/// fails closed rather than notifying a silently-truncated prefix of the
/// configured destinations.
pub fn filter_recipient_list(
    recipient_list_value: &PropertyValue,
    transition: EventTransition,
    today_bit: u8,
    current_time: &Time,
) -> Vec<(BACnetRecipient, u32, bool)> {
    let Ok(destinations) = decode_destination_list_pv(recipient_list_value) else {
        return Vec::new();
    };
    filter_destinations(destinations, transition, today_bit, current_time)
}

#[cfg(test)]
mod tests;