1use 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
29pub 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 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 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 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 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 pub fn records(&self) -> &VecDeque<BACnetLogMultipleRecord> {
172 self.log_buffer.records()
173 }
174
175 pub fn clear(&mut self) {
177 self.log_buffer.clear();
178 }
179
180 pub fn set_description(&mut self, desc: impl Into<String>) {
182 self.description = desc.into();
183 }
184
185 pub fn set_logging_type(&mut self, logging_type: LoggingType) -> Result<(), Error> {
192 self.acquisition.set_logging_type(logging_type)
193 }
194
195 pub fn set_log_interval(&mut self, hundredths: u32) -> Result<(), Error> {
198 self.acquisition.set_log_interval(hundredths)
199 }
200
201 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 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 pub fn set_align_intervals(&mut self, align: bool) {
225 self.acquisition.set_align_intervals(align);
226 }
227
228 pub fn set_interval_offset(&mut self, hundredths: u32) {
231 self.acquisition.set_interval_offset(hundredths);
232 }
233
234 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 pub fn set_notification_threshold(&mut self, threshold: u32) {
248 self.reporting.set_notification_threshold(threshold);
249 }
250
251 pub fn set_notification_class(&mut self, class: u32) {
254 self.reporting.set_notification_class(class);
255 }
256
257 pub fn set_event_enable(&mut self, enable: EventTransitionBits) {
260 self.reporting.set_event_enable(enable);
261 }
262
263 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 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 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 p if p == PropertyIdentifier::LOG_BUFFER => Err(log_buffer_read_denied()),
348 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 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}