Skip to main content

bacnet_objects/binary/
value.rs

1use super::*;
2use crate::object_profile::{ObjectProfile, ProfileState, TagsPersistence};
3use crate::present_value_access::PresentValueAccess;
4use crate::property_metadata::PropertyMetadata;
5use std::sync::Arc;
6
7#[path = "value/metadata.rs"]
8mod metadata;
9
10// ---------------------------------------------------------------------------
11// BinaryValue (type 5)
12// ---------------------------------------------------------------------------
13
14/// BACnet Binary Value object.
15///
16/// Uses Enumerated values: 0 = inactive, 1 = active.
17pub struct BinaryValueObject {
18    profile: ProfileState,
19    audit_policy: crate::audit::ObjectAuditPolicy,
20    oid: ObjectIdentifier,
21    name: String,
22    description: String,
23    present_value: u32, // 0 = inactive, 1 = active
24    out_of_service: bool,
25    status_flags: StatusFlags,
26    access: PresentValueAccess,
27    priority_array: [Option<u32>; 16],
28    relinquish_default: u32,
29    /// Reliability; NO_FAULT_DETECTED until a fault is evaluated or simulated.
30    reliability: Reliability,
31    reliability_before_out_of_service: Option<Reliability>,
32    reliability_inhibit: common::ReliabilityInhibitState,
33    active_text: String,
34    inactive_text: String,
35    /// CHANGE_OF_STATE event detector.
36    event_detector: ChangeOfStateDetector,
37    /// Event_Detection_Enable (Clause 12.8). A FALSE value suspends
38    /// event-state-machine evaluation under Clause 13.2.2.1.
39    event_detection_enable: bool,
40    pub(crate) event_history: EventHistory,
41    /// Implemented paired command-source tracking (Clause 19.5).
42    value_source: crate::command_source::ValueSourceTracking,
43    /// The last writer of a noncommandable Present_Value, once tracked (#1552).
44    write_source: crate::command_source::SingleValueSource,
45}
46
47impl BinaryValueObject {
48    /// Provision independently optional Audit properties before registration.
49    /// Raw object configuration bypasses server notification ownership; use
50    /// BACnetServer::write_local or WP/WPM for live property mutations.
51    pub fn set_audit_policy(&mut self, policy: crate::audit::ObjectAuditPolicy) {
52        self.audit_policy = policy;
53    }
54
55    /// Create a new Binary Value object with a commandable Present_Value.
56    pub fn new(instance: u32, name: impl Into<String>) -> Result<Self, Error> {
57        Self::with_access(instance, name, PresentValueAccess::Commandable)
58    }
59
60    /// Create a new Binary Value object whose Present_Value is written as `access` says.
61    pub fn with_access(
62        instance: u32,
63        name: impl Into<String>,
64        access: PresentValueAccess,
65    ) -> Result<Self, Error> {
66        let oid = ObjectIdentifier::new(ObjectType::BINARY_VALUE, instance)?;
67        Ok(Self {
68            profile: ProfileState::default(),
69            audit_policy: crate::audit::ObjectAuditPolicy::default(),
70            oid,
71            name: name.into(),
72            description: String::new(),
73            present_value: 0, // inactive
74            out_of_service: false,
75            status_flags: StatusFlags::empty(),
76            access,
77            priority_array: [None; 16],
78            relinquish_default: 0,
79            reliability: Reliability::NO_FAULT_DETECTED,
80            reliability_before_out_of_service: None,
81            reliability_inhibit: common::ReliabilityInhibitState::default(),
82            active_text: "Active".into(),
83            inactive_text: "Inactive".into(),
84            event_detector: ChangeOfStateDetector {
85                alarm_values: vec![1],
86                ..Default::default()
87            },
88            event_detection_enable: true,
89            event_history: EventHistory::default(),
90            value_source: crate::command_source::ValueSourceTracking::default(),
91            write_source: crate::command_source::SingleValueSource::default(),
92        })
93    }
94
95    /// Build with application-owned Tags storage and the requested Present_Value access.
96    /// Saved Tags override configured Tags only while [`Self::set_profile`]
97    /// provisions the row. Loaded data must satisfy the shared Tags rules and
98    /// the opt-in 1 MiB snapshot limit.
99    pub fn with_tags_persistence(
100        instance: u32,
101        name: impl Into<String>,
102        access: PresentValueAccess,
103        persistence: Arc<dyn TagsPersistence>,
104    ) -> Result<Self, Error> {
105        let mut object = Self::with_access(instance, name, access)?;
106        object.profile = ProfileState::persistent(object.oid, persistence)?;
107        Ok(object)
108    }
109
110    /// Provision independent optional Tags, Profile_Location and Profile_Name
111    /// rows before registration, in every Present_Value access mode. Tags is
112    /// writable; the text rows are network read-only. Invalid configuration
113    /// leaves the previous profile and its attached storage unchanged.
114    pub fn set_profile(&mut self, profile: ObjectProfile) -> Result<(), Error> {
115        self.profile.provision(profile)
116    }
117
118    /// Wait for queued save attempts to finish; writes report their own outcomes.
119    /// This is not a success receipt. Unstaged synchronous writes block their caller.
120    pub fn wait_for_tag_saves(&self) {
121        self.profile.wait_for_saves();
122    }
123
124    /// Track the source of a noncommandable Present_Value (Clause 19.5,
125    /// #1552), as [`AnalogValueObject::set_value_source_tracking`] does.
126    ///
127    /// [`AnalogValueObject::set_value_source_tracking`]: crate::analog::AnalogValueObject::set_value_source_tracking
128    pub fn set_value_source_tracking(&mut self, enabled: bool) {
129        self.write_source.set_enabled(enabled);
130    }
131
132    /// Set the description string.
133    pub fn set_description(&mut self, desc: impl Into<String>) {
134        self.description = desc.into();
135    }
136
137    fn recalculate_present_value(&mut self) {
138        self.present_value =
139            common::recalculate_from_priority_array(&self.priority_array, self.relinquish_default);
140    }
141
142    /// Set the Relinquish_Default (#270).
143    ///
144    /// Validated the same way a commanded Present_Value is (BinaryPV 0 or 1);
145    /// after the store, Present_Value is resolved anew from the priority
146    /// array so an empty array falls back to the new default immediately.
147    pub fn set_relinquish_default(&mut self, value: u32) -> Result<(), Error> {
148        if self.access != PresentValueAccess::Commandable {
149            return Err(common::unknown_property_error());
150        }
151        if value > 1 {
152            return Err(common::value_out_of_range_error());
153        }
154        self.relinquish_default = value;
155        self.recalculate_present_value();
156        Ok(())
157    }
158
159    /// A noncommandable Present_Value write, network-equivalent.
160    fn write_direct_present_value(
161        &mut self,
162        array_index: Option<u32>,
163        value: PropertyValue,
164    ) -> Result<(), Error> {
165        if array_index.is_some() {
166            return Err(common::property_is_not_an_array_error());
167        }
168        if self.access == PresentValueAccess::ReadOnly && !self.out_of_service {
169            return Err(common::write_access_denied_error());
170        }
171        // Clause 19.2: an otherwise permitted noncommandable NULL is a no-op.
172        if value == PropertyValue::Null {
173            return Ok(());
174        }
175        self.present_value = Self::checked_present_value(value)?;
176        Ok(())
177    }
178
179    fn checked_present_value(value: PropertyValue) -> Result<u32, Error> {
180        let PropertyValue::Enumerated(e) = value else {
181            return Err(common::invalid_data_type_error());
182        };
183        if e > 1 {
184            return Err(common::value_out_of_range_error());
185        }
186        Ok(e)
187    }
188}
189
190impl BACnetObject for BinaryValueObject {
191    fn audit_policy_authority_internal(
192        &mut self,
193    ) -> Option<crate::audit::AuditPolicyAuthority<'_>> {
194        Some(crate::audit::AuditPolicyAuthority::new(
195            &mut self.audit_policy,
196        ))
197    }
198
199    fn audit_object_policy_internal(&self) -> crate::audit::ObjectAuditPolicy {
200        self.audit_policy
201    }
202
203    fn object_identifier(&self) -> ObjectIdentifier {
204        self.oid
205    }
206
207    fn object_name(&self) -> &str {
208        &self.name
209    }
210
211    fn supports_cov(&self) -> bool {
212        true
213    }
214
215    crate::event::impl_builtin_intrinsic_reporting!(
216        event_detector,
217        event_history,
218        [present_value],
219        reliability,
220        event_detection_enable,
221        ChangeOfStateDetector::ALGORITHM
222    );
223
224    fn acknowledge_alarm_correlated_internal(
225        &mut self,
226        event_state: EventState,
227        timestamp: &BACnetTimeStamp,
228    ) -> Result<(), Error> {
229        if !self.event_detection_enable {
230            return Err(Error::Protocol {
231                class: ErrorClass::OBJECT.to_raw() as u32,
232                code: ErrorCode::NO_ALARM_CONFIGURED.to_raw() as u32,
233            });
234        }
235        self.event_history.acknowledge_correlated(
236            &mut self.event_detector.acked_transitions,
237            event_state,
238            timestamp,
239        )
240    }
241
242    fn read_property(
243        &self,
244        property: PropertyIdentifier,
245        array_index: Option<u32>,
246    ) -> Result<PropertyValue, Error> {
247        if metadata::excludes(self, property) {
248            return Err(common::unknown_property_error());
249        }
250        let source = match self.access {
251            PresentValueAccess::Commandable => {
252                self.value_source
253                    .read(property, array_index, &self.priority_array)
254            }
255            _ => self.write_source.read(property, array_index),
256        };
257        if let Some(result) = source {
258            return result;
259        }
260        if let Some(result) = self.profile.read(property, array_index) {
261            return result;
262        }
263
264        if let Some(result) = self.audit_policy.read(property, array_index) {
265            return result;
266        }
267        if property == PropertyIdentifier::STATUS_FLAGS {
268            return Ok(common::compute_status_flags(
269                self.status_flags,
270                self.reliability,
271                self.out_of_service,
272                self.event_detector.event_state,
273            ));
274        }
275        if let Some(value) = self.reliability_inhibit.read(property) {
276            return Ok(value);
277        }
278        if let Some(result) = read_common_properties!(self, property, array_index) {
279            return result;
280        }
281        if property == PropertyIdentifier::EVENT_DETECTION_ENABLE {
282            return Ok(PropertyValue::Boolean(self.event_detection_enable));
283        }
284        if let Some(result) = read_generic_event_properties!(self, property) {
285            return result;
286        }
287        if let Some(result) = self.event_history.read(property, array_index) {
288            return result;
289        }
290        match property {
291            p if p == PropertyIdentifier::OBJECT_TYPE => {
292                Ok(PropertyValue::Enumerated(ObjectType::BINARY_VALUE.to_raw()))
293            }
294            p if p == PropertyIdentifier::PRESENT_VALUE => {
295                Ok(PropertyValue::Enumerated(self.present_value))
296            }
297            p if p == PropertyIdentifier::PRIORITY_ARRAY => {
298                common::read_priority_array!(self, array_index, PropertyValue::Enumerated)
299            }
300            p if p == PropertyIdentifier::RELINQUISH_DEFAULT => {
301                Ok(PropertyValue::Enumerated(self.relinquish_default))
302            }
303            p if p == PropertyIdentifier::CURRENT_COMMAND_PRIORITY => {
304                Ok(common::current_command_priority(&self.priority_array))
305            }
306            p if p == PropertyIdentifier::ACTIVE_TEXT => {
307                Ok(PropertyValue::CharacterString(self.active_text.clone()))
308            }
309            p if p == PropertyIdentifier::INACTIVE_TEXT => {
310                Ok(PropertyValue::CharacterString(self.inactive_text.clone()))
311            }
312            p if p == PropertyIdentifier::ALARM_VALUE => {
313                // Construction and writes keep exactly one value; ACTIVE is the
314                // defensive construction default if a future reset empties it.
315                Ok(PropertyValue::Enumerated(
316                    self.event_detector
317                        .alarm_values
318                        .first()
319                        .copied()
320                        .unwrap_or(1),
321                ))
322            }
323            _ => Err(common::unknown_property_error()),
324        }
325    }
326
327    fn write_property_from(
328        &mut self,
329        property: PropertyIdentifier,
330        array_index: Option<u32>,
331        value: PropertyValue,
332        priority: Option<u8>,
333        origin: &crate::command_source::CommandOrigin,
334    ) -> Result<(), Error> {
335        if matches!(
336            property,
337            PropertyIdentifier::PRESENT_VALUE | PropertyIdentifier::VALUE_SOURCE
338        ) && array_index.is_some()
339        {
340            return Err(common::property_is_not_an_array_error());
341        }
342        if property == PropertyIdentifier::VALUE_SOURCE {
343            return match self.access {
344                PresentValueAccess::Commandable => {
345                    self.value_source.correct(value, priority, origin)
346                }
347                _ => self.write_source.correct(array_index, value, origin),
348            };
349        }
350        if property == PropertyIdentifier::PRESENT_VALUE {
351            return match self.access {
352                PresentValueAccess::Commandable => {
353                    crate::command_source::write_sourced_priority!(
354                        self,
355                        value,
356                        priority,
357                        origin,
358                        Self::checked_present_value
359                    )
360                }
361                PresentValueAccess::ReadOnly | PresentValueAccess::Writable => {
362                    self.write_source.admit(origin)?;
363                    // A NULL is a no-op (Clause 19.2), so it has no writer.
364                    let null = value == PropertyValue::Null;
365                    self.write_direct_present_value(array_index, value)?;
366                    if !null {
367                        self.write_source.record(origin);
368                    }
369                    Ok(())
370                }
371            };
372        }
373        self.write_property(property, array_index, value, priority)
374    }
375
376    fn write_property(
377        &mut self,
378        property: PropertyIdentifier,
379        array_index: Option<u32>,
380        value: PropertyValue,
381        priority: Option<u8>,
382    ) -> Result<(), Error> {
383        if metadata::excludes(self, property) {
384            return Err(common::unknown_property_error());
385        }
386        if let Some(result) = self.profile.write(property, array_index, &value) {
387            return result;
388        }
389        if let Some(result) = self
390            .audit_policy
391            .write(property, array_index, &value, priority)
392        {
393            return result;
394        }
395
396        if property == PropertyIdentifier::PRESENT_VALUE {
397            if self.access == PresentValueAccess::Commandable {
398                return Err(common::write_access_denied_error());
399            }
400            // A tracked source needs the writer (`write_property_from`).
401            self.write_source.unsourced()?;
402            return self.write_direct_present_value(array_index, value);
403        }
404        if property == PropertyIdentifier::VALUE_SOURCE {
405            return Err(common::write_access_denied_error());
406        }
407        if property == PropertyIdentifier::ACTIVE_TEXT {
408            if let PropertyValue::CharacterString(s) = value {
409                self.active_text = s;
410                return Ok(());
411            }
412            return Err(common::invalid_data_type_error());
413        }
414        if property == PropertyIdentifier::INACTIVE_TEXT {
415            if let PropertyValue::CharacterString(s) = value {
416                self.inactive_text = s;
417                return Ok(());
418            }
419            return Err(common::invalid_data_type_error());
420        }
421        if property == PropertyIdentifier::ALARM_VALUE {
422            if let PropertyValue::Enumerated(v) = value {
423                if v > 1 {
424                    return Err(common::value_out_of_range_error());
425                }
426                self.event_detector.alarm_values = vec![v];
427                return Ok(());
428            }
429            return Err(common::invalid_data_type_error());
430        }
431        if property == PropertyIdentifier::EVENT_DETECTION_ENABLE {
432            if let PropertyValue::Boolean(v) = value {
433                self.event_detection_enable = v;
434                if !v {
435                    self.event_detector.event_state = bacnet_types::enums::EventState::NORMAL;
436                    self.event_detector.acked_transitions =
437                        bacnet_types::bitstring::EventTransitionBits::all();
438                    self.event_detector.pending = None;
439                    self.event_detector.fault_reliability = None;
440                    self.event_history.reset();
441                }
442                return Ok(());
443            }
444            return Err(common::invalid_data_type_error());
445        }
446        if property == PropertyIdentifier::RELINQUISH_DEFAULT {
447            if let PropertyValue::Enumerated(e) = value {
448                return self.set_relinquish_default(e);
449            }
450            return Err(common::invalid_data_type_error());
451        }
452        // Event_Message_Texts_Config and the Event_Algorithm_Inhibit pair (#1329).
453        if let Some(result) =
454            self.event_history
455                .write(property, array_index, &value, self.event_detection_enable)
456        {
457            return result;
458        }
459        if let Some(result) = write_generic_event_properties!(self, property, value) {
460            return result;
461        }
462        if let Some(result) = self.reliability_inhibit.write_inhibit(
463            &mut self.reliability,
464            self.out_of_service,
465            property,
466            &value,
467        ) {
468            return result;
469        }
470        if let Some(result) = self.reliability_inhibit.write_out_of_service(
471            &mut self.out_of_service,
472            &mut self.reliability,
473            &mut self.reliability_before_out_of_service,
474            property,
475            &value,
476        ) {
477            return result.map(|_| ());
478        }
479        if let Some(result) = common::write_object_name(&mut self.name, property, &value) {
480            return result;
481        }
482        if let Some(result) = common::write_description(&mut self.description, property, &value) {
483            return result;
484        }
485        // Clause 12.8 requires simulation/test writes while Out_Of_Service is TRUE:
486        // Present_Value is writable, as is Reliability when that property exists
487        // and supports values beyond NO_FAULT_DETECTED.
488        // `is_writable_property` stays statically true because it describes capability.
489        if let Some(result) = self.reliability_inhibit.write_client_reliability(
490            self.out_of_service,
491            &mut self.reliability,
492            property,
493            &value,
494        ) {
495            return result;
496        }
497        Err(crate::common::unhandled_write_error(
498            self.property_metadata().as_ref(),
499            property,
500            array_index,
501        ))
502    }
503
504    fn durable_writes_internal(&mut self) -> Option<&mut dyn crate::durable::DurableWrites> {
505        self.profile.capability()
506    }
507
508    fn advance_monotonic_time_internal(&mut self, now: std::time::Duration) -> bool {
509        self.profile.expire(now);
510        false
511    }
512
513    fn property_metadata(&self) -> Cow<'_, [PropertyMetadata]> {
514        metadata::for_object(self)
515    }
516
517    fn property_list(&self) -> Cow<'static, [PropertyIdentifier]> {
518        crate::property_metadata::property_list_from_metadata(self.property_metadata().as_ref())
519    }
520
521    fn is_createable(&self) -> bool {
522        true
523    }
524
525    fn set_reliability_internal(&mut self, reliability: Reliability) -> Result<(), Error> {
526        if self.out_of_service || self.reliability_inhibit.enabled() {
527            return Err(common::write_access_denied_error());
528        }
529        if !common::is_reliability_value_valid(reliability) {
530            return Err(common::value_out_of_range_error());
531        }
532        self.reliability = reliability;
533        Ok(())
534    }
535
536    fn set_present_value_internal(&mut self, value: PropertyValue) -> Result<(), Error> {
537        match self.access {
538            PresentValueAccess::Commandable => {
539                Err(common::optional_functionality_not_supported_error())
540            }
541            _ if self.out_of_service => Err(common::write_access_denied_error()),
542            PresentValueAccess::ReadOnly | PresentValueAccess::Writable => {
543                self.present_value = Self::checked_present_value(value)?;
544                self.write_source.forget();
545                Ok(())
546            }
547        }
548    }
549
550    fn set_present_value_from_internal(
551        &mut self,
552        value: PropertyValue,
553        origin: &crate::command_source::CommandOrigin,
554    ) -> Result<(), Error> {
555        self.write_source.admit(origin)?;
556        self.set_present_value_internal(value)?;
557        self.write_source.record(origin);
558        Ok(())
559    }
560
561    fn reliability_evaluation_inhibited_internal(&self) -> bool {
562        self.reliability_inhibit.enabled()
563    }
564}
565
566#[cfg(test)]
567#[path = "tests/value.rs"]
568mod value_tests;