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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
//! AuditLog (type 61) and AuditReporter (type 62) objects per Addendum 135-2016bj.

use std::borrow::Cow;
use std::collections::VecDeque;
use std::sync::Arc;

use bacnet_types::bitstring::{AuditOperationFlags, BACnetPriorityFilter};
use bacnet_types::constructed::{
    BACnetAuditLogDatum, BACnetAuditLogQueryParameters, BACnetAuditLogRecord,
    BACnetAuditLogRecordResult, BACnetAuditNotification, BACnetRecipient,
};
use bacnet_types::enums::{
    AuditLevel, ErrorClass, ErrorCode, EventState, ObjectType, PropertyIdentifier, Reliability,
};
use bacnet_types::error::Error;
use bacnet_types::primitives::{ObjectIdentifier, PropertyValue, StatusFlags};

use crate::clock::ClockReader;
use crate::common::read_property_list_property;
use crate::property_metadata::PropertyMetadata;
use crate::traits::{BACnetObject, WritePropertyRollback};

mod notification;
mod persistence;
mod receipt;
mod reporter_metadata;
pub use notification::AuditLogNotificationSink;
use persistence::{validate_record, validate_snapshot};
pub use persistence::{
    AuditLogPersistence, AuditLogSnapshot, FileAuditLogPersistence, MAX_AUDIT_RECORDS,
};
pub use receipt::{
    CompletedAuditReceipt, ConfirmedAuditNotificationOutcome, MAX_AUDIT_RECEIPT_KEY_BYTES,
    MAX_COMPLETED_AUDIT_RECEIPTS,
};

/// One owned page returned by an object-level AuditLogQuery capability.
#[derive(Debug, Clone, PartialEq)]
pub struct AuditLogQueryPage {
    /// Matching records in newest-first retained insertion order.
    pub records: Vec<BACnetAuditLogRecordResult>,
    /// Whether a complete retained-buffer scan found no unreturned match.
    pub no_more_items: bool,
}

/// Read-only query capability for an object's retained Audit Log records.
///
/// Implementations return owned pages so the server can release its object
/// database read guard before building and encoding the ComplexACK. This
/// interface never performs persistence I/O or mutates the log.
pub trait AuditLogStorage: Send + Sync {
    /// Filter and page the currently retained in-memory records.
    ///
    /// A present start is the existing Clause-21 `Unsigned32` model and admits
    /// only literal sequence identities below it. This intentionally does not
    /// add a modular cursor across `u64::MAX -> 1`.
    fn query(
        &self,
        parameters: &BACnetAuditLogQueryParameters,
        start_at_sequence_number: Option<u32>,
        requested_count: u16,
    ) -> AuditLogQueryPage;
}

// ---------------------------------------------------------------------------
// AuditLog (type 61)
// ---------------------------------------------------------------------------

/// BACnet AuditLog object with explicit application-owned durable storage.
pub struct AuditLogObject {
    oid: ObjectIdentifier,
    name: String,
    description: String,
    log_enable: bool,
    buffer_size: u32,
    buffer: VecDeque<BACnetAuditLogRecordResult>,
    completed_receipts: Vec<CompletedAuditReceipt>,
    total_record_count: u64,
    status_flags: StatusFlags,
    generation: u64,
    persistence: Arc<dyn AuditLogPersistence>,
    clock: Option<Arc<dyn ClockReader>>,
}

struct AuditLogWriteRollback {
    snapshot: AuditLogSnapshot,
}

const LOG_DISABLED_STATUS: u8 = 0b001;
const BUFFER_PURGED_STATUS: u8 = 0b010;

impl AuditLogObject {
    /// Open or initialize one AuditLog using the explicitly supplied storage.
    pub fn new(
        instance: u32,
        name: impl Into<String>,
        buffer_size: u32,
        persistence: Arc<dyn AuditLogPersistence>,
    ) -> Result<Self, Error> {
        let oid = ObjectIdentifier::new(ObjectType::AUDIT_LOG, instance)?;
        if buffer_size > MAX_AUDIT_RECORDS {
            return Err(Error::OutOfRange(format!(
                "AuditLog capacity {buffer_size} exceeds {MAX_AUDIT_RECORDS}"
            )));
        }
        let snapshot = match persistence.load(oid)? {
            Some(snapshot) => {
                if snapshot.object_identifier != oid || snapshot.capacity != buffer_size {
                    return Err(Error::Encoding(
                        "AuditLog persisted identity or capacity does not match configuration"
                            .into(),
                    ));
                }
                validate_snapshot(&snapshot)?;
                snapshot
            }
            None => {
                let snapshot = AuditLogSnapshot {
                    object_identifier: oid,
                    generation: 1,
                    capacity: buffer_size,
                    log_enable: true,
                    total_record_count: 0,
                    records: Vec::new(),
                    completed_receipts: Vec::new(),
                };
                validate_snapshot(&snapshot)?;
                persistence.commit(&snapshot)?;
                snapshot
            }
        };
        Ok(Self {
            oid,
            name: name.into(),
            description: String::new(),
            log_enable: snapshot.log_enable,
            buffer_size: snapshot.capacity,
            buffer: snapshot.records.into(),
            completed_receipts: snapshot.completed_receipts,
            total_record_count: snapshot.total_record_count,
            status_flags: StatusFlags::empty(),
            generation: snapshot.generation,
            persistence,
            clock: None,
        })
    }

    /// Append one application-supplied record when logging is enabled.
    pub fn add_record(&mut self, record: BACnetAuditLogRecord) -> Result<Option<u64>, Error> {
        if !self.log_enable {
            return Ok(None);
        }
        validate_record(&record)?;
        let mut prospective = self.snapshot_for_next_generation()?;
        let sequence_number = append_record(&mut prospective, record);
        self.commit_and_apply(prospective)?;
        Ok(Some(sequence_number))
    }

    /// Get the current buffer contents.
    pub fn records(&self) -> &VecDeque<BACnetAuditLogRecordResult> {
        &self.buffer
    }

    /// Configured and persisted ring capacity.
    pub fn buffer_size(&self) -> u32 {
        self.buffer_size
    }

    /// Persisted logging enable policy.
    pub fn log_enable(&self) -> bool {
        self.log_enable
    }

    /// Monotonic record identity counter with BACnet MAX-to-one wrap.
    pub fn total_record_count(&self) -> u64 {
        self.total_record_count
    }

    /// Current durable snapshot generation.
    pub fn generation(&self) -> u64 {
        self.generation
    }

    /// Clear buffered records and append the internal BUFFER_PURGED status.
    fn purge(&mut self) -> Result<u64, Error> {
        let timestamp = self.valid_timestamp()?;
        let mut prospective = self.snapshot_for_next_generation()?;
        prospective.records.clear();
        let sequence_number = append_record(
            &mut prospective,
            BACnetAuditLogRecord {
                timestamp,
                datum: BACnetAuditLogDatum::LogStatus(BUFFER_PURGED_STATUS),
            },
        );
        self.commit_and_apply(prospective)?;
        Ok(sequence_number)
    }

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

    fn valid_timestamp(
        &self,
    ) -> Result<
        (
            bacnet_types::primitives::Date,
            bacnet_types::primitives::Time,
        ),
        Error,
    > {
        let frame = self
            .clock
            .as_ref()
            .and_then(|clock| clock.read_clock())
            .filter(|frame| frame.is_valid_actual_datetime())
            .ok_or(Error::Protocol {
                class: ErrorClass::DEVICE.to_raw() as u32,
                code: ErrorCode::OPERATIONAL_PROBLEM.to_raw() as u32,
            })?;
        Ok((frame.local_date, frame.local_time))
    }

    fn snapshot_for_next_generation(&self) -> Result<AuditLogSnapshot, Error> {
        let generation = self
            .generation
            .checked_add(1)
            .ok_or_else(|| Error::OutOfRange("AuditLog persistence generation exhausted".into()))?;
        let mut snapshot = self.current_snapshot();
        snapshot.generation = generation;
        Ok(snapshot)
    }

    fn current_snapshot(&self) -> AuditLogSnapshot {
        AuditLogSnapshot {
            object_identifier: self.oid,
            generation: self.generation,
            capacity: self.buffer_size,
            log_enable: self.log_enable,
            total_record_count: self.total_record_count,
            records: self.buffer.iter().cloned().collect(),
            completed_receipts: self.completed_receipts.clone(),
        }
    }

    fn commit_and_apply(&mut self, snapshot: AuditLogSnapshot) -> Result<(), Error> {
        validate_snapshot(&snapshot)?;
        self.persistence.commit(&snapshot)?;
        self.generation = snapshot.generation;
        self.log_enable = snapshot.log_enable;
        self.total_record_count = snapshot.total_record_count;
        self.buffer = snapshot.records.into();
        self.completed_receipts = snapshot.completed_receipts;
        Ok(())
    }
}

fn append_record(snapshot: &mut AuditLogSnapshot, record: BACnetAuditLogRecord) -> u64 {
    let sequence_number = if snapshot.total_record_count == u64::MAX {
        1
    } else {
        snapshot.total_record_count + 1
    };
    snapshot.total_record_count = sequence_number;
    if snapshot.capacity != 0 {
        if snapshot.records.len() >= snapshot.capacity as usize {
            snapshot.records.remove(0);
        }
        snapshot.records.push(BACnetAuditLogRecordResult {
            sequence_number,
            record,
        });
    }
    sequence_number
}

fn recipient_matches(
    actual: &BACnetRecipient,
    required_identifier: ObjectIdentifier,
    optional_address: Option<&bacnet_types::constructed::BACnetAddress>,
) -> bool {
    match actual {
        BACnetRecipient::Device(identifier) => *identifier == required_identifier,
        BACnetRecipient::Address(address) => {
            optional_address.is_some_and(|filter| address == filter)
        }
    }
}

fn operation_matches(
    notification: &BACnetAuditNotification,
    operations: Option<bacnet_types::bitstring::AuditOperationFlags>,
    successful_actions_only: bool,
) -> bool {
    operations.is_none_or(|flags| flags.contains(notification.operation))
        && (!successful_actions_only || notification.result.is_none())
}

fn query_matches(
    notification: &BACnetAuditNotification,
    parameters: &BACnetAuditLogQueryParameters,
) -> bool {
    match parameters {
        BACnetAuditLogQueryParameters::ByTarget {
            target_device_identifier,
            target_device_address,
            target_object_identifier,
            target_property_identifier,
            target_array_index,
            target_priority,
            operations,
            successful_actions_only,
        } => {
            recipient_matches(
                &notification.target_device,
                *target_device_identifier,
                target_device_address.as_ref(),
            ) && target_object_identifier
                .is_none_or(|filter| notification.target_object == Some(filter))
                && target_property_identifier.is_none_or(|filter| {
                    notification.target_property.as_ref().is_some_and(|property| {
                        property.property_identifier == filter
                    })
                })
                && target_array_index.is_none_or(|filter| {
                    notification.target_property.as_ref().is_some_and(|property| {
                        property.property_array_index == Some(filter)
                    })
                })
                // Clause 13.19 says a record without Priority matches any
                // requested Target Priority.
                && target_priority.is_none_or(|filter| {
                    notification
                        .target_priority
                        .is_none_or(|priority| priority == filter)
                })
                && operation_matches(notification, *operations, *successful_actions_only)
        }
        BACnetAuditLogQueryParameters::BySource {
            source_device_identifier,
            source_device_address,
            source_object_identifier,
            operations,
            successful_actions_only,
        } => {
            recipient_matches(
                &notification.source_device,
                *source_device_identifier,
                source_device_address.as_ref(),
            ) && source_object_identifier
                .is_none_or(|filter| notification.source_object == Some(filter))
                && operation_matches(notification, *operations, *successful_actions_only)
        }
    }
}

impl AuditLogStorage for AuditLogObject {
    fn query(
        &self,
        parameters: &BACnetAuditLogQueryParameters,
        start_at_sequence_number: Option<u32>,
        requested_count: u16,
    ) -> AuditLogQueryPage {
        let limit = usize::from(requested_count).min(MAX_AUDIT_RECORDS as usize);
        let mut records = Vec::with_capacity(limit.min(self.buffer.len()));
        let mut unreturned_match = false;

        // The ring is stored oldest-to-newest. Reverse insertion order is the
        // query order even across sequence wrap; numeric sorting would turn
        // retained [MAX, 1] into the wrong chronology.
        for result in self.buffer.iter().rev() {
            if start_at_sequence_number
                .is_some_and(|start| result.sequence_number >= u64::from(start))
            {
                continue;
            }
            let BACnetAuditLogDatum::AuditNotification(notification) = &result.record.datum else {
                continue;
            };
            if !query_matches(notification, parameters) {
                continue;
            }
            if records.len() < limit {
                records.push(result.clone());
            } else {
                // Keep scanning the complete retained snapshot so a full page
                // can still truthfully distinguish exhaustion from a later
                // eligible match. This also defines count=0.
                unreturned_match = true;
            }
        }

        AuditLogQueryPage {
            records,
            no_more_items: !unreturned_match,
        }
    }
}

impl BACnetObject for AuditLogObject {
    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> {
        match property {
            p if p == PropertyIdentifier::OBJECT_IDENTIFIER => {
                Ok(PropertyValue::ObjectIdentifier(self.oid))
            }
            p if p == PropertyIdentifier::OBJECT_NAME => {
                Ok(PropertyValue::CharacterString(self.name.clone()))
            }
            p if p == PropertyIdentifier::DESCRIPTION => {
                Ok(PropertyValue::CharacterString(self.description.clone()))
            }
            p if p == PropertyIdentifier::OBJECT_TYPE => {
                Ok(PropertyValue::Enumerated(ObjectType::AUDIT_LOG.to_raw()))
            }
            p if p == PropertyIdentifier::LOG_ENABLE => Ok(PropertyValue::Boolean(self.log_enable)),
            p if p == PropertyIdentifier::BUFFER_SIZE => {
                Ok(PropertyValue::Unsigned(self.buffer_size as u64))
            }
            p if p == PropertyIdentifier::RECORD_COUNT => {
                Ok(PropertyValue::Unsigned(self.buffer.len() as u64))
            }
            p if p == PropertyIdentifier::TOTAL_RECORD_COUNT => {
                Ok(PropertyValue::Unsigned(self.total_record_count))
            }
            p if p == PropertyIdentifier::STATUS_FLAGS => Ok(PropertyValue::BitString {
                unused_bits: 4,
                data: vec![self.status_flags.bits() << 4],
            }),
            p if p == PropertyIdentifier::EVENT_STATE => Ok(PropertyValue::Enumerated(0)),
            p if p == PropertyIdentifier::PROPERTY_LIST => {
                read_property_list_property(&self.property_list(), array_index)
            }
            _ => Err(Error::Protocol {
                class: ErrorClass::PROPERTY.to_raw() as u32,
                code: ErrorCode::UNKNOWN_PROPERTY.to_raw() as u32,
            }),
        }
    }

    fn write_property(
        &mut self,
        property: PropertyIdentifier,
        _array_index: Option<u32>,
        value: PropertyValue,
        _priority: Option<u8>,
    ) -> Result<(), Error> {
        if property == PropertyIdentifier::LOG_ENABLE {
            if let PropertyValue::Boolean(v) = value {
                if v == self.log_enable {
                    return Ok(());
                }
                let timestamp = self.valid_timestamp()?;
                let mut prospective = self.snapshot_for_next_generation()?;
                prospective.log_enable = v;
                append_record(
                    &mut prospective,
                    BACnetAuditLogRecord {
                        timestamp,
                        datum: BACnetAuditLogDatum::LogStatus(if v {
                            0
                        } else {
                            LOG_DISABLED_STATUS
                        }),
                    },
                );
                self.commit_and_apply(prospective)?;
                return Ok(());
            }
            return Err(Error::Protocol {
                class: ErrorClass::PROPERTY.to_raw() as u32,
                code: ErrorCode::INVALID_DATA_TYPE.to_raw() as u32,
            });
        }
        if property == PropertyIdentifier::RECORD_COUNT {
            return Err(Error::Protocol {
                class: ErrorClass::PROPERTY.to_raw() as u32,
                code: ErrorCode::WRITE_ACCESS_DENIED.to_raw() as u32,
            });
        }
        if property == PropertyIdentifier::DESCRIPTION {
            if let PropertyValue::CharacterString(s) = value {
                self.description = s;
                return Ok(());
            }
            return Err(Error::Protocol {
                class: ErrorClass::PROPERTY.to_raw() as u32,
                code: ErrorCode::INVALID_DATA_TYPE.to_raw() as u32,
            });
        }
        Err(Error::Protocol {
            class: ErrorClass::PROPERTY.to_raw() as u32,
            code: ErrorCode::WRITE_ACCESS_DENIED.to_raw() as u32,
        })
    }

    fn property_list(&self) -> Cow<'static, [PropertyIdentifier]> {
        static PROPS: &[PropertyIdentifier] = &[
            PropertyIdentifier::OBJECT_IDENTIFIER,
            PropertyIdentifier::OBJECT_NAME,
            PropertyIdentifier::DESCRIPTION,
            PropertyIdentifier::OBJECT_TYPE,
            PropertyIdentifier::LOG_ENABLE,
            PropertyIdentifier::BUFFER_SIZE,
            PropertyIdentifier::RECORD_COUNT,
            PropertyIdentifier::TOTAL_RECORD_COUNT,
            PropertyIdentifier::STATUS_FLAGS,
            PropertyIdentifier::EVENT_STATE,
        ];
        Cow::Borrowed(PROPS)
    }

    fn bind_clock_internal(&mut self, clock: Option<Arc<dyn ClockReader>>) {
        self.clock = clock;
    }

    fn audit_log_storage_internal(&self) -> Option<&dyn AuditLogStorage> {
        Some(self)
    }

    fn audit_log_notification_sink_internal(
        &mut self,
    ) -> Option<&mut dyn AuditLogNotificationSink> {
        Some(self)
    }

    fn capture_write_property_rollback(
        &mut self,
        property: PropertyIdentifier,
        value: &PropertyValue,
    ) -> Option<WritePropertyRollback> {
        let PropertyValue::Boolean(requested) = value else {
            return None;
        };
        (property == PropertyIdentifier::LOG_ENABLE && *requested != self.log_enable).then(|| {
            WritePropertyRollback::new(AuditLogWriteRollback {
                snapshot: self.current_snapshot(),
            })
        })
    }

    fn restore_write_property_rollback(
        &mut self,
        rollback: WritePropertyRollback,
    ) -> Result<(), Error> {
        let mut snapshot = rollback.downcast::<AuditLogWriteRollback>()?.snapshot;
        if snapshot.object_identifier != self.oid || snapshot.capacity != self.buffer_size {
            return Err(Error::Encoding(
                "AuditLog rollback snapshot does not belong to this object".into(),
            ));
        }
        snapshot.generation = self
            .generation
            .checked_add(1)
            .ok_or_else(|| Error::OutOfRange("AuditLog persistence generation exhausted".into()))?;
        self.commit_and_apply(snapshot)
    }
}

// ---------------------------------------------------------------------------
// AuditReporter (type 62)
// ---------------------------------------------------------------------------

/// BACnet AuditReporter object — configures which audit notifications to send.
pub struct AuditReporterObject {
    oid: ObjectIdentifier,
    name: String,
    description: String,
    status_flags: StatusFlags,
    audit_level: AuditLevel,
    auditable_operations: AuditOperationFlags,
    audit_priority_filter: BACnetPriorityFilter,
    issue_confirmed_notifications: bool,
}

impl AuditReporterObject {
    pub fn new(instance: u32, name: impl Into<String>) -> Result<Self, Error> {
        let oid = ObjectIdentifier::new(ObjectType::AUDIT_REPORTER, instance)?;
        Ok(Self {
            oid,
            name: name.into(),
            description: String::new(),
            status_flags: StatusFlags::empty(),
            audit_level: AuditLevel::NONE,
            auditable_operations: AuditOperationFlags::empty(),
            audit_priority_filter: BACnetPriorityFilter::all(),
            issue_confirmed_notifications: false,
        })
    }

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

    /// Set the locally managed audit level.
    pub fn set_audit_level(&mut self, level: AuditLevel) -> Result<(), Error> {
        if level == AuditLevel::DEFAULT {
            return Err(Error::OutOfRange(
                "Audit Reporter audit level must not be DEFAULT".into(),
            ));
        }
        self.audit_level = level;
        Ok(())
    }

    /// Set the locally managed operation filter.
    pub fn set_auditable_operations(&mut self, operations: AuditOperationFlags) {
        self.auditable_operations = operations;
    }

    /// Set the locally managed command-priority filter.
    pub fn set_audit_priority_filter(&mut self, filter: BACnetPriorityFilter) {
        self.audit_priority_filter = filter;
    }

    /// Select confirmed or unconfirmed audit notifications for future producers.
    pub fn set_issue_confirmed_notifications(&mut self, confirmed: bool) {
        self.issue_confirmed_notifications = confirmed;
    }
}

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

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

    fn property_metadata(&self) -> Cow<'_, [PropertyMetadata]> {
        Cow::Borrowed(reporter_metadata::AUDIT_REPORTER_PROPERTIES)
    }

    fn read_property(
        &self,
        property: PropertyIdentifier,
        array_index: Option<u32>,
    ) -> Result<PropertyValue, Error> {
        match property {
            p if p == PropertyIdentifier::OBJECT_IDENTIFIER => {
                Ok(PropertyValue::ObjectIdentifier(self.oid))
            }
            p if p == PropertyIdentifier::OBJECT_NAME => {
                Ok(PropertyValue::CharacterString(self.name.clone()))
            }
            p if p == PropertyIdentifier::DESCRIPTION => {
                Ok(PropertyValue::CharacterString(self.description.clone()))
            }
            p if p == PropertyIdentifier::OBJECT_TYPE => Ok(PropertyValue::Enumerated(
                ObjectType::AUDIT_REPORTER.to_raw(),
            )),
            p if p == PropertyIdentifier::STATUS_FLAGS => Ok(PropertyValue::BitString {
                unused_bits: 4,
                data: vec![self.status_flags.bits() << 4],
            }),
            p if p == PropertyIdentifier::RELIABILITY => Ok(PropertyValue::Enumerated(
                Reliability::NO_FAULT_DETECTED.to_raw(),
            )),
            p if p == PropertyIdentifier::EVENT_STATE => {
                Ok(PropertyValue::Enumerated(EventState::NORMAL.to_raw()))
            }
            p if p == PropertyIdentifier::AUDIT_LEVEL => {
                Ok(PropertyValue::Enumerated(self.audit_level.to_raw()))
            }
            p if p == PropertyIdentifier::AUDIT_SOURCE_REPORTER => {
                Ok(PropertyValue::Boolean(false))
            }
            p if p == PropertyIdentifier::AUDITABLE_OPERATIONS => {
                let (unused_bits, data) = self.auditable_operations.to_bacnet();
                Ok(PropertyValue::BitString { unused_bits, data })
            }
            p if p == PropertyIdentifier::AUDIT_PRIORITY_FILTER => {
                let (unused_bits, data) = self.audit_priority_filter.to_bacnet();
                Ok(PropertyValue::BitString { unused_bits, data })
            }
            p if p == PropertyIdentifier::ISSUE_CONFIRMED_NOTIFICATIONS => {
                Ok(PropertyValue::Boolean(self.issue_confirmed_notifications))
            }
            p if p == PropertyIdentifier::PROPERTY_LIST => {
                read_property_list_property(&self.property_list(), array_index)
            }
            _ => Err(Error::Protocol {
                class: ErrorClass::PROPERTY.to_raw() as u32,
                code: ErrorCode::UNKNOWN_PROPERTY.to_raw() as u32,
            }),
        }
    }

    fn write_property(
        &mut self,
        property: PropertyIdentifier,
        _array_index: Option<u32>,
        value: PropertyValue,
        _priority: Option<u8>,
    ) -> Result<(), Error> {
        if property == PropertyIdentifier::DESCRIPTION {
            if let PropertyValue::CharacterString(s) = value {
                self.description = s;
                return Ok(());
            }
            return Err(Error::Protocol {
                class: ErrorClass::PROPERTY.to_raw() as u32,
                code: ErrorCode::INVALID_DATA_TYPE.to_raw() as u32,
            });
        }
        Err(Error::Protocol {
            class: ErrorClass::PROPERTY.to_raw() as u32,
            code: ErrorCode::WRITE_ACCESS_DENIED.to_raw() as u32,
        })
    }

    fn property_list(&self) -> Cow<'static, [PropertyIdentifier]> {
        crate::property_metadata::property_list_from_metadata(
            reporter_metadata::AUDIT_REPORTER_PROPERTIES,
        )
    }
}

#[cfg(test)]
#[path = "audit/tests.rs"]
mod tests;

#[cfg(test)]
#[path = "audit/query_tests.rs"]
mod query_tests;

#[cfg(test)]
#[path = "audit/notification_tests.rs"]
mod notification_tests;

#[cfg(test)]
#[path = "audit/receipt_tests.rs"]
mod receipt_tests;

#[cfg(test)]
#[path = "audit/persistence_receipt_tests.rs"]
mod persistence_receipt_tests;