Skip to main content

bacnet_objects/trend/
multiple.rs

1//! TrendLogMultiple (type 27, Clause 12.30).
2
3use std::borrow::Cow;
4use std::collections::VecDeque;
5use std::sync::Arc;
6
7use bacnet_types::bitstring::EventTransitionBits;
8use bacnet_types::constructed::{BACnetDeviceObjectPropertyReference, BACnetLogMultipleRecord};
9use bacnet_types::enums::{
10    ErrorClass, ErrorCode, LoggingType, NotifyType, ObjectType, PropertyIdentifier, Reliability,
11};
12use bacnet_types::error::Error;
13use bacnet_types::primitives::{Date, ObjectIdentifier, PropertyValue, StatusFlags, Time};
14
15use super::acquisition::{Acquisition, Rules};
16use super::multiple_metadata;
17use super::references::{self, MAX_LOG_DEVICE_OBJECT_PROPERTIES};
18use crate::clock::ClockReader;
19use crate::common::{self, read_property_list_property};
20use crate::device_reference;
21use crate::log_buffer::{
22    log_buffer_read_denied, LogBufferRecords, LogRecordBuffer, LogRecordIdentity,
23};
24use crate::log_lifecycle::LogLifecycle;
25use crate::log_reporting::{impl_buffer_ready_reporting, BufferReadyReporting};
26use crate::log_window::LogWindow;
27use crate::traits::BACnetObject;
28
29/// BACnet TrendLogMultiple object (type 27).
30///
31/// Multi-channel trending. Unlike TrendLog, which monitors a single property,
32/// TrendLogMultiple monitors a list of device-object-property references and
33/// logs one value per reference in each record. The database's trend poller
34/// samples every reference every Log_Interval while Logging_Type is POLLED,
35/// at clock-aligned times when Align_Intervals asks for them, and once for
36/// each Trigger while it is TRIGGERED. Records are kept only while Enable is
37/// TRUE and the local time lies between Start_Time and Stop_Time.
38pub struct TrendLogMultipleObject {
39    oid: ObjectIdentifier,
40    name: String,
41    description: String,
42    log_enable: bool,
43    stop_when_full: bool,
44    buffer_size: u32,
45    log_buffer: LogRecordBuffer<BACnetLogMultipleRecord>,
46    log_device_object_property: Vec<BACnetDeviceObjectPropertyReference>,
47    acquisition: Acquisition,
48    window: LogWindow,
49    reporting: BufferReadyReporting,
50    reliability: Reliability,
51    clock: Option<Arc<dyn ClockReader>>,
52}
53
54impl TrendLogMultipleObject {
55    /// Build a log with logging enabled that holds at most `buffer_size`
56    /// records.
57    pub fn new(instance: u32, name: impl Into<String>, buffer_size: u32) -> Result<Self, Error> {
58        let oid = ObjectIdentifier::new(ObjectType::TREND_LOG_MULTIPLE, instance)?;
59        Ok(Self {
60            oid,
61            name: name.into(),
62            description: String::new(),
63            log_enable: true,
64            stop_when_full: false,
65            buffer_size,
66            log_buffer: LogRecordBuffer::new(buffer_size),
67            log_device_object_property: Vec::new(),
68            acquisition: Acquisition::new(Rules::TrendLogMultiple),
69            window: LogWindow::default(),
70            reporting: BufferReadyReporting::default(),
71            reliability: Reliability::NO_FAULT_DETECTED,
72            clock: None,
73        })
74    }
75
76    /// Add a record to the log buffer.
77    ///
78    /// Success does not guarantee a resident ordinary record: disabled logging
79    /// and a record outside the Start_Time / Stop_Time window are ignored,
80    /// zero-capacity logging may only count, and a stop-before-full
81    /// transition records status instead. Missing/invalid status clocks fail
82    /// atomically with DEVICE / OPERATIONAL_PROBLEM. A successful call serves
83    /// a pending Trigger, which reads FALSE again, even when the record is
84    /// ignored (Enable FALSE, or outside the window): the acquisition was
85    /// made.
86    pub fn add_record(&mut self, record: BACnetLogMultipleRecord) -> Result<(), Error> {
87        self.lifecycle().try_add_ordinary(record)?;
88        self.acquisition.acquired();
89        Ok(())
90    }
91
92    /// Append a reference to Log_DeviceObjectProperty as local configuration:
93    /// the log buffer is left as it is.
94    ///
95    /// A reference may name another device; the poller then logs a failure
96    /// in its slot of each record instead of reading it. A Device member that
97    /// isn't a Device identifier fails with PROPERTY / VALUE_OUT_OF_RANGE, and
98    /// a reference past [`MAX_LOG_DEVICE_OBJECT_PROPERTIES`] with RESOURCES /
99    /// NO_SPACE_TO_WRITE_PROPERTY; either leaves the array unchanged.
100    pub fn add_property_reference(
101        &mut self,
102        reference: BACnetDeviceObjectPropertyReference,
103    ) -> Result<(), Error> {
104        device_reference::check_device_member(reference.device_identifier)?;
105        if self.log_device_object_property.len() >= MAX_LOG_DEVICE_OBJECT_PROPERTIES {
106            return Err(references::no_space_error());
107        }
108        self.log_device_object_property.push(reference);
109        Ok(())
110    }
111
112    /// A client's write of Log_DeviceObjectProperty (#1234).
113    ///
114    /// A whole write replaces the array, at any length up to
115    /// [`MAX_LOG_DEVICE_OBJECT_PROPERTIES`]; an indexed write replaces one
116    /// element. Writing index 0 resizes the array (Clause 12.1.5.1): a smaller
117    /// Unsigned drops the trailing elements, a larger one appends empty
118    /// elements, one past the cap is RESOURCES / NO_SPACE_TO_WRITE_PROPERTY and
119    /// another datatype PROPERTY / INVALID_DATA_TYPE. Each written reference
120    /// goes through [`references::check_written`], where an element naming
121    /// instance 4194303 is an empty one. A new value purges the buffer,
122    /// leaving a BUFFER_PURGED status record, which is the first of the two
123    /// actions Clause 12.30.11 offers; without a valid clock the purge fails
124    /// with DEVICE / OPERATIONAL_PROBLEM and nothing changes. Writing the value
125    /// already held changes nothing.
126    fn write_log_device_object_property(
127        &mut self,
128        array_index: Option<u32>,
129        value: PropertyValue,
130    ) -> Result<(), Error> {
131        let mut candidate = self.log_device_object_property.clone();
132        match array_index {
133            None => {
134                let written = device_reference::decode_references(&value)?;
135                if written.len() > MAX_LOG_DEVICE_OBJECT_PROPERTIES {
136                    return Err(references::no_space_error());
137                }
138                for reference in &written {
139                    references::check_written(reference)?;
140                }
141                candidate = written;
142            }
143            Some(0) => {
144                let PropertyValue::Unsigned(size) = value else {
145                    return Err(common::invalid_data_type_error());
146                };
147                let size = usize::try_from(size)
148                    .ok()
149                    .filter(|size| *size <= MAX_LOG_DEVICE_OBJECT_PROPERTIES)
150                    .ok_or_else(references::no_space_error)?;
151                candidate.resize_with(size, references::empty_element);
152            }
153            Some(index) => {
154                let slot = usize::try_from(index - 1)
155                    .ok()
156                    .and_then(|slot| candidate.get_mut(slot))
157                    .ok_or_else(common::invalid_array_index_error)?;
158                let reference = device_reference::decode_reference(&value)?;
159                references::check_written(&reference)?;
160                *slot = reference;
161            }
162        }
163        if candidate != self.log_device_object_property {
164            self.lifecycle().purge()?;
165            self.log_device_object_property = candidate;
166        }
167        Ok(())
168    }
169
170    /// Get the current buffer contents.
171    pub fn records(&self) -> &VecDeque<BACnetLogMultipleRecord> {
172        self.log_buffer.records()
173    }
174
175    /// Clear the buffer.
176    pub fn clear(&mut self) {
177        self.log_buffer.clear();
178    }
179
180    /// Set the description string.
181    pub fn set_description(&mut self, desc: impl Into<String>) {
182        self.description = desc.into();
183    }
184
185    /// Set Logging_Type, as a client's write does: POLLED or TRIGGERED. COV
186    /// logging isn't allowed for this object type (Clause 12.30.12), so COV,
187    /// like any other value, is PROPERTY / VALUE_OUT_OF_RANGE and changes
188    /// nothing. POLLED with a zero Log_Interval sets
189    /// [`DEFAULT_LOG_INTERVAL`](super::DEFAULT_LOG_INTERVAL); TRIGGERED sets
190    /// Log_Interval to zero.
191    pub fn set_logging_type(&mut self, logging_type: LoggingType) -> Result<(), Error> {
192        self.acquisition.set_logging_type(logging_type)
193    }
194
195    /// Set Log_Interval in hundredths of a second. While Logging_Type is
196    /// TRIGGERED it is read-only and this is PROPERTY / WRITE_ACCESS_DENIED.
197    pub fn set_log_interval(&mut self, hundredths: u32) -> Result<(), Error> {
198        self.acquisition.set_log_interval(hundredths)
199    }
200
201    /// Set Start_Time, the local date and time from which records are kept,
202    /// as local configuration: nothing is recorded for the change itself,
203    /// but the log notes at once where the window stands, so a client's
204    /// write that then opens or shuts it is recorded. Every field
205    /// unspecified leaves the start open. Any other value has to name an
206    /// actual date and time, or it is PROPERTY / VALUE_OUT_OF_RANGE: the
207    /// weekday may stay unspecified, and unspecified seconds or hundredths
208    /// count as zero.
209    pub fn set_start_time(&mut self, date: Date, time: Time) -> Result<(), Error> {
210        self.lifecycle()
211            .configure_window(PropertyIdentifier::START_TIME, (date, time))
212    }
213
214    /// Set Stop_Time, the local date and time from which records are no
215    /// longer kept, under the same rules as
216    /// [`set_start_time`](Self::set_start_time).
217    pub fn set_stop_time(&mut self, date: Date, time: Time) -> Result<(), Error> {
218        self.lifecycle()
219            .configure_window(PropertyIdentifier::STOP_TIME, (date, time))
220    }
221
222    /// Set Align_Intervals: whether a POLLED log acquires at clock-aligned
223    /// times.
224    pub fn set_align_intervals(&mut self, align: bool) {
225        self.acquisition.set_align_intervals(align);
226    }
227
228    /// Set Interval_Offset, the delay after each aligned boundary, in
229    /// hundredths; it applies modulo Log_Interval.
230    pub fn set_interval_offset(&mut self, hundredths: u32) {
231        self.acquisition.set_interval_offset(hundredths);
232    }
233
234    /// Ask for one acquisition, as a local process writing Trigger TRUE does.
235    /// Only a TRIGGERED log takes it; any other is PROPERTY /
236    /// NOT_CONFIGURED_FOR_TRIGGERED_LOGGING.
237    pub fn trigger(&mut self) -> Result<(), Error> {
238        self.acquisition.trigger()
239    }
240
241    pub(super) fn logging_type(&self) -> LoggingType {
242        self.acquisition.logging_type()
243    }
244
245    /// Set Notification_Threshold, the number of records that makes a
246    /// BUFFER_READY report; zero, the default, makes none.
247    pub fn set_notification_threshold(&mut self, threshold: u32) {
248        self.reporting.set_notification_threshold(threshold);
249    }
250
251    /// Set Notification_Class: the number of the Notification Class whose
252    /// recipients get the log's reports (0 by default).
253    pub fn set_notification_class(&mut self, class: u32) {
254        self.reporting.set_notification_class(class);
255    }
256
257    /// Set Event_Enable; a report goes out only while its TO_NORMAL flag is
258    /// set, as it is by default.
259    pub fn set_event_enable(&mut self, enable: EventTransitionBits) {
260        self.reporting.set_event_enable(enable);
261    }
262
263    /// Set Notify_Type, sent with each report (EVENT by default).
264    pub fn set_notify_type(&mut self, notify_type: NotifyType) {
265        self.reporting.set_notify_type(notify_type);
266    }
267
268    fn lifecycle(&mut self) -> LogLifecycle<'_, BACnetLogMultipleRecord> {
269        LogLifecycle::new(
270            &mut self.log_buffer,
271            &mut self.log_enable,
272            &mut self.stop_when_full,
273            self.clock.as_ref(),
274            &mut self.window,
275            &mut self.reporting,
276        )
277    }
278}
279
280impl BACnetObject for TrendLogMultipleObject {
281    fn object_identifier(&self) -> ObjectIdentifier {
282        self.oid
283    }
284
285    fn object_name(&self) -> &str {
286        &self.name
287    }
288
289    fn read_property(
290        &self,
291        property: PropertyIdentifier,
292        array_index: Option<u32>,
293    ) -> Result<PropertyValue, Error> {
294        // Logging_Type, Log_Interval, Align_Intervals, Interval_Offset and
295        // Trigger, then Start_Time and Stop_Time.
296        if let Some(value) = self
297            .acquisition
298            .read(property)
299            .or_else(|| self.window.read(property))
300        {
301            return Ok(value);
302        }
303        let total = self.log_buffer.total_record_count();
304        if let Some(result) = self.reporting.read(property, array_index, total) {
305            return result;
306        }
307        match property {
308            p if p == PropertyIdentifier::OBJECT_IDENTIFIER => {
309                Ok(PropertyValue::ObjectIdentifier(self.oid))
310            }
311            p if p == PropertyIdentifier::OBJECT_NAME => {
312                Ok(PropertyValue::CharacterString(self.name.clone()))
313            }
314            p if p == PropertyIdentifier::DESCRIPTION => {
315                Ok(PropertyValue::CharacterString(self.description.clone()))
316            }
317            p if p == PropertyIdentifier::OBJECT_TYPE => Ok(PropertyValue::Enumerated(
318                ObjectType::TREND_LOG_MULTIPLE.to_raw(),
319            )),
320            p if p == PropertyIdentifier::LOG_ENABLE => Ok(PropertyValue::Boolean(self.log_enable)),
321            p if p == PropertyIdentifier::STOP_WHEN_FULL => {
322                Ok(PropertyValue::Boolean(self.stop_when_full))
323            }
324            p if p == PropertyIdentifier::BUFFER_SIZE => {
325                Ok(PropertyValue::Unsigned(self.buffer_size as u64))
326            }
327            p if p == PropertyIdentifier::RECORD_COUNT => {
328                Ok(PropertyValue::Unsigned(self.records().len() as u64))
329            }
330            p if p == PropertyIdentifier::TOTAL_RECORD_COUNT => {
331                Ok(PropertyValue::Unsigned(u64::from(total)))
332            }
333            // Clause 12.30.5 lets only IN_ALARM (from Event_State) and FAULT
334            // (from Reliability) move on a Trend Log Multiple; OVERRIDDEN and
335            // OUT_OF_SERVICE are always FALSE. Table 12-35 has no
336            // Out_Of_Service property (#985).
337            p if p == PropertyIdentifier::STATUS_FLAGS => Ok(common::compute_status_flags(
338                StatusFlags::empty(),
339                self.reliability,
340                false,
341                self.reporting.event_state(),
342            )),
343            p if p == PropertyIdentifier::RELIABILITY => {
344                Ok(PropertyValue::Enumerated(self.reliability.to_raw()))
345            }
346            // ReadRange pages it through `log_buffer_internal`.
347            p if p == PropertyIdentifier::LOG_BUFFER => Err(log_buffer_read_denied()),
348            // A BACnetARRAY: one Clause 21 encoding per element (#1234).
349            p if p == PropertyIdentifier::LOG_DEVICE_OBJECT_PROPERTY => common::read_array(
350                device_reference::reference_elements(&self.log_device_object_property),
351                array_index,
352            ),
353            p if p == PropertyIdentifier::PROPERTY_LIST => {
354                read_property_list_property(&self.property_list(), array_index)
355            }
356            _ => Err(Error::Protocol {
357                class: ErrorClass::PROPERTY.to_raw() as u32,
358                code: ErrorCode::UNKNOWN_PROPERTY.to_raw() as u32,
359            }),
360        }
361    }
362
363    fn write_property(
364        &mut self,
365        property: PropertyIdentifier,
366        array_index: Option<u32>,
367        value: PropertyValue,
368        _priority: Option<u8>,
369    ) -> Result<(), Error> {
370        if property == PropertyIdentifier::LOG_ENABLE {
371            if let PropertyValue::Boolean(v) = value {
372                return self.lifecycle().write_enable(v);
373            }
374            return Err(Error::Protocol {
375                class: ErrorClass::PROPERTY.to_raw() as u32,
376                code: ErrorCode::INVALID_DATA_TYPE.to_raw() as u32,
377            });
378        }
379        if let Some(result) = self.acquisition.write(property, &value) {
380            return result;
381        }
382        if let Some(result) = self.window.write(property, &value) {
383            // A change that opens or closes the window is recorded at once.
384            result?;
385            self.lifecycle().refresh_window();
386            return Ok(());
387        }
388        if property == PropertyIdentifier::STOP_WHEN_FULL {
389            if let PropertyValue::Boolean(v) = value {
390                return self.lifecycle().write_stop_when_full(v);
391            }
392            return Err(Error::Protocol {
393                class: ErrorClass::PROPERTY.to_raw() as u32,
394                code: ErrorCode::INVALID_DATA_TYPE.to_raw() as u32,
395            });
396        }
397        if property == PropertyIdentifier::RECORD_COUNT {
398            if let PropertyValue::Unsigned(0) = value {
399                return self.lifecycle().purge();
400            }
401            return Err(Error::Protocol {
402                class: ErrorClass::PROPERTY.to_raw() as u32,
403                code: ErrorCode::INVALID_DATA_TYPE.to_raw() as u32,
404            });
405        }
406        if property == PropertyIdentifier::LOG_DEVICE_OBJECT_PROPERTY {
407            return self.write_log_device_object_property(array_index, value);
408        }
409        let total = self.log_buffer.total_record_count();
410        if let Some(result) = self.reporting.write(property, array_index, &value, total) {
411            return result;
412        }
413        if let Some(result) = common::write_description(&mut self.description, property, &value) {
414            return result;
415        }
416        Err(crate::common::unhandled_write_error(
417            self.property_metadata().as_ref(),
418            property,
419            array_index,
420        ))
421    }
422
423    fn property_metadata(&self) -> Cow<'_, [crate::property_metadata::PropertyMetadata]> {
424        multiple_metadata::for_object(self)
425    }
426
427    fn property_list(&self) -> Cow<'static, [PropertyIdentifier]> {
428        crate::property_metadata::property_list_from_metadata(self.property_metadata().as_ref())
429    }
430
431    fn bind_clock_internal(&mut self, clock: Option<Arc<dyn ClockReader>>) {
432        self.clock = clock;
433    }
434
435    fn log_record_identities_internal(&self) -> Option<Vec<LogRecordIdentity>> {
436        Some(self.log_buffer.identities())
437    }
438
439    fn log_buffer_internal(&self) -> Option<&dyn LogBufferRecords> {
440        Some(&self.log_buffer)
441    }
442
443    fn add_trend_multiple_record(&mut self, record: BACnetLogMultipleRecord) -> Result<(), Error> {
444        self.add_record(record)
445    }
446
447    fn refresh_log_window_internal(&mut self) -> bool {
448        self.lifecycle().refresh_window()
449    }
450
451    impl_buffer_ready_reporting!(reporting, log_buffer);
452}