Skip to main content

bacnet_objects/
event_log.rs

1//! EventLog (type 25) object per ASHRAE 135-2020 Clause 12.27.
2
3use std::borrow::Cow;
4use std::collections::VecDeque;
5use std::sync::Arc;
6
7use bacnet_types::bitstring::EventTransitionBits;
8use bacnet_types::constructed::BACnetEventLogRecord;
9use bacnet_types::enums::{NotifyType, ObjectType, PropertyIdentifier, Reliability};
10use bacnet_types::error::Error;
11use bacnet_types::primitives::{Date, ObjectIdentifier, PropertyValue, StatusFlags, Time};
12
13use crate::clock::ClockReader;
14use crate::common::{self, read_common_properties};
15use crate::log_buffer::{
16    log_buffer_read_denied, LogBufferRecords, LogRecordBuffer, LogRecordIdentity,
17};
18use crate::log_lifecycle::LogLifecycle;
19use crate::log_reporting::{impl_buffer_ready_reporting, BufferReadyReporting};
20use crate::log_window::LogWindow;
21use crate::traits::BACnetObject;
22
23mod metadata;
24
25/// BACnet EventLog object.
26///
27/// Ring buffer of timestamped event log records. A server running the
28/// database logs the event notifications the device builds into its Event
29/// Logs ([`ObjectDatabase::log_event_notification`]), and those it receives
30/// into the logs that opt in with
31/// [`set_log_received_notifications`](Self::set_log_received_notifications);
32/// the application calls `add_record()` for anything else, such as a clock
33/// change. The log adds its own status records. Records are kept only while
34/// Enable is TRUE and the local time lies between Start_Time and Stop_Time;
35/// the database's trend poller looks at that window on every pass, so an
36/// opening or closing is recorded even when no record arrives.
37///
38/// The log reports intrinsically with the BUFFER_READY algorithm (Clause
39/// 13.3.7): once Notification_Threshold is set, the server tells the
40/// recipients of its Notification Class each time that many more records
41/// have been collected. No log takes a record for such a report.
42///
43/// [`ObjectDatabase::log_event_notification`]: crate::database::ObjectDatabase::log_event_notification
44pub struct EventLogObject {
45    oid: ObjectIdentifier,
46    name: String,
47    description: String,
48    log_enable: bool,
49    stop_when_full: bool,
50    buffer_size: u32,
51    log_buffer: LogRecordBuffer<BACnetEventLogRecord>,
52    status_flags: StatusFlags,
53    reliability: Reliability,
54    window: LogWindow,
55    reporting: BufferReadyReporting,
56    log_received_notifications: bool,
57    clock: Option<Arc<dyn ClockReader>>,
58}
59
60impl EventLogObject {
61    /// Create a new EventLog object.
62    pub fn new(instance: u32, name: impl Into<String>, buffer_size: u32) -> Result<Self, Error> {
63        let oid = ObjectIdentifier::new(ObjectType::EVENT_LOG, instance)?;
64        Ok(Self {
65            oid,
66            name: name.into(),
67            description: String::new(),
68            log_enable: true,
69            stop_when_full: false,
70            buffer_size,
71            log_buffer: LogRecordBuffer::new(buffer_size),
72            status_flags: StatusFlags::empty(),
73            reliability: Reliability::NO_FAULT_DETECTED,
74            window: LogWindow::default(),
75            reporting: BufferReadyReporting::default(),
76            log_received_notifications: false,
77            clock: None,
78        })
79    }
80
81    /// Add a record to the event log buffer.
82    ///
83    /// The record is kept as given; ReadRange serves its encoding, which for
84    /// an ACK_NOTIFICATION leaves out ack-required, from-state and event
85    /// values (see `EventLogDatum::Notification`).
86    ///
87    /// Success does not guarantee a resident ordinary record: disabled logging
88    /// and a record outside the Start_Time / Stop_Time window are ignored,
89    /// zero-capacity logging may only count, and a stop-before-full
90    /// transition records status instead. Missing/invalid status clocks fail
91    /// atomically with DEVICE / OPERATIONAL_PROBLEM.
92    pub fn add_record(&mut self, record: BACnetEventLogRecord) -> Result<(), Error> {
93        self.lifecycle().try_add_ordinary(record).map(|_| ())
94    }
95
96    /// Get the current buffer contents.
97    pub fn records(&self) -> &VecDeque<BACnetEventLogRecord> {
98        self.log_buffer.records()
99    }
100
101    /// Clear the buffer.
102    pub fn clear(&mut self) {
103        self.log_buffer.clear();
104    }
105
106    /// Set the description string.
107    pub fn set_description(&mut self, desc: impl Into<String>) {
108        self.description = desc.into();
109    }
110
111    /// Set Start_Time, the local date and time from which records are kept,
112    /// as local configuration: nothing is recorded for the change itself,
113    /// but the log notes at once where the window stands, so a client's
114    /// write that then opens or shuts it is recorded. Every field
115    /// unspecified leaves the start open. Any other value has to name an
116    /// actual date and time, or it is PROPERTY / VALUE_OUT_OF_RANGE: the
117    /// weekday may stay unspecified, and unspecified seconds or hundredths
118    /// count as zero.
119    pub fn set_start_time(&mut self, date: Date, time: Time) -> Result<(), Error> {
120        self.lifecycle()
121            .configure_window(PropertyIdentifier::START_TIME, (date, time))
122    }
123
124    /// Set Stop_Time, the local date and time from which records are no
125    /// longer kept, under the same rules as
126    /// [`set_start_time`](Self::set_start_time).
127    pub fn set_stop_time(&mut self, date: Date, time: Time) -> Result<(), Error> {
128        self.lifecycle()
129            .configure_window(PropertyIdentifier::STOP_TIME, (date, time))
130    }
131
132    /// Whether the log takes the event notifications the device receives,
133    /// as well as those it builds. Off unless set.
134    pub fn logs_received_notifications(&self) -> bool {
135        self.log_received_notifications
136    }
137
138    /// Have the log take the Confirmed and UnconfirmedEventNotifications the
139    /// device receives, unicast or broadcast, each kept as it decoded, or
140    /// stop it doing so. Clause 12.27 leaves the choice to the device, and
141    /// it's off by default. A running server holds what it logs to a small
142    /// number of records per source each second; see
143    /// [`ObjectDatabase::log_received_event_notification`](crate::database::ObjectDatabase::log_received_event_notification).
144    pub fn set_log_received_notifications(&mut self, log: bool) {
145        self.log_received_notifications = log;
146    }
147
148    /// Set Notification_Threshold, the number of records that makes a
149    /// BUFFER_READY report; zero, the default, makes none.
150    pub fn set_notification_threshold(&mut self, threshold: u32) {
151        self.reporting.set_notification_threshold(threshold);
152    }
153
154    /// Set Notification_Class: the number of the Notification Class whose
155    /// recipients get the log's reports (0 by default).
156    pub fn set_notification_class(&mut self, class: u32) {
157        self.reporting.set_notification_class(class);
158    }
159
160    /// Set Event_Enable; a report goes out only while its TO_NORMAL flag is
161    /// set, as it is by default.
162    pub fn set_event_enable(&mut self, enable: EventTransitionBits) {
163        self.reporting.set_event_enable(enable);
164    }
165
166    /// Set Notify_Type, sent with each report (EVENT by default).
167    pub fn set_notify_type(&mut self, notify_type: NotifyType) {
168        self.reporting.set_notify_type(notify_type);
169    }
170
171    fn lifecycle(&mut self) -> LogLifecycle<'_, BACnetEventLogRecord> {
172        LogLifecycle::new(
173            &mut self.log_buffer,
174            &mut self.log_enable,
175            &mut self.stop_when_full,
176            self.clock.as_ref(),
177            &mut self.window,
178            &mut self.reporting,
179        )
180    }
181}
182
183impl BACnetObject for EventLogObject {
184    fn object_identifier(&self) -> ObjectIdentifier {
185        self.oid
186    }
187
188    fn object_name(&self) -> &str {
189        &self.name
190    }
191
192    fn read_property(
193        &self,
194        property: PropertyIdentifier,
195        array_index: Option<u32>,
196    ) -> Result<PropertyValue, Error> {
197        // Table 12-31 has neither Out_Of_Service nor Log_Interval (#1064), and
198        // Clause 12.27 holds the OUT_OF_SERVICE flag FALSE.
199        if let Some(result) =
200            read_common_properties!(self, property, array_index, no_out_of_service)
201        {
202            return result;
203        }
204        if let Some(value) = self.window.read(property) {
205            return Ok(value);
206        }
207        let total = self.log_buffer.total_record_count();
208        if let Some(result) = self.reporting.read(property, array_index, total) {
209            return result;
210        }
211        match property {
212            p if p == PropertyIdentifier::OBJECT_TYPE => {
213                Ok(PropertyValue::Enumerated(ObjectType::EVENT_LOG.to_raw()))
214            }
215            p if p == PropertyIdentifier::LOG_ENABLE => Ok(PropertyValue::Boolean(self.log_enable)),
216            p if p == PropertyIdentifier::STOP_WHEN_FULL => {
217                Ok(PropertyValue::Boolean(self.stop_when_full))
218            }
219            p if p == PropertyIdentifier::BUFFER_SIZE => {
220                Ok(PropertyValue::Unsigned(self.buffer_size as u64))
221            }
222            // ReadRange pages it through `log_buffer_internal`.
223            p if p == PropertyIdentifier::LOG_BUFFER => Err(log_buffer_read_denied()),
224            p if p == PropertyIdentifier::RECORD_COUNT => {
225                Ok(PropertyValue::Unsigned(self.records().len() as u64))
226            }
227            p if p == PropertyIdentifier::TOTAL_RECORD_COUNT => {
228                Ok(PropertyValue::Unsigned(u64::from(total)))
229            }
230            _ => Err(common::unknown_property_error()),
231        }
232    }
233
234    fn write_property(
235        &mut self,
236        property: PropertyIdentifier,
237        array_index: Option<u32>,
238        value: PropertyValue,
239        _priority: Option<u8>,
240    ) -> Result<(), Error> {
241        if property == PropertyIdentifier::LOG_ENABLE {
242            if let PropertyValue::Boolean(v) = value {
243                return self.lifecycle().write_enable(v);
244            }
245            return Err(common::invalid_data_type_error());
246        }
247        if let Some(result) = self.window.write(property, &value) {
248            // A change that opens or closes the window is recorded at once.
249            result?;
250            self.lifecycle().refresh_window();
251            return Ok(());
252        }
253        if property == PropertyIdentifier::STOP_WHEN_FULL {
254            if let PropertyValue::Boolean(v) = value {
255                return self.lifecycle().write_stop_when_full(v);
256            }
257            return Err(common::invalid_data_type_error());
258        }
259        if property == PropertyIdentifier::RECORD_COUNT {
260            if let PropertyValue::Unsigned(0) = value {
261                return self.lifecycle().purge();
262            }
263            return Err(common::invalid_data_type_error());
264        }
265        let total = self.log_buffer.total_record_count();
266        if let Some(result) = self.reporting.write(property, array_index, &value, total) {
267            return result;
268        }
269        if let Some(result) = common::write_description(&mut self.description, property, &value) {
270            return result;
271        }
272        Err(crate::common::unhandled_write_error(
273            self.property_metadata().as_ref(),
274            property,
275            array_index,
276        ))
277    }
278
279    fn property_metadata(&self) -> Cow<'_, [crate::property_metadata::PropertyMetadata]> {
280        metadata::for_object(self)
281    }
282
283    fn property_list(&self) -> Cow<'static, [PropertyIdentifier]> {
284        crate::property_metadata::property_list_from_metadata(self.property_metadata().as_ref())
285    }
286
287    fn bind_clock_internal(&mut self, clock: Option<Arc<dyn ClockReader>>) {
288        self.clock = clock;
289    }
290
291    fn log_record_identities_internal(&self) -> Option<Vec<LogRecordIdentity>> {
292        Some(self.log_buffer.identities())
293    }
294
295    fn log_buffer_internal(&self) -> Option<&dyn LogBufferRecords> {
296        Some(&self.log_buffer)
297    }
298
299    fn add_event_log_record(&mut self, record: BACnetEventLogRecord) -> Result<(), Error> {
300        self.add_record(record)
301    }
302
303    fn refresh_log_window_internal(&mut self) -> bool {
304        self.lifecycle().refresh_window()
305    }
306
307    fn logs_received_event_notifications_internal(&self) -> bool {
308        self.log_received_notifications
309    }
310
311    impl_buffer_ready_reporting!(reporting, log_buffer);
312}
313
314#[cfg(test)]
315mod tests;